I am trying to add or insert values into table of database using servlet and jsp and MySQL Workbench as database. These are the following details:
1.> Register.java
package register.com;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import javax.servlet.*;
/**
* Servlet implementation class Register
*/
#WebServlet("/register")
public class Register extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Register() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
//String connectionURL = "jdbc:mysql://127.0.0.1:3306/newData";// newData is the database
//Connection connection;
Connection conn=null;
String url="jdbc:mysql://localhost:3306/";
String dbName="userlogindb";
String driver="com.mysql.jdbc.Driver";
//String dbUserName="root";
//String dbPassword="root";
try{
String Fname = request.getParameter("fname");
String Mname = request.getParameter("mname");
String Lname = request.getParameter("lname");
String Uname = request.getParameter("username");
String Emailid = request.getParameter("emailid");
String Mobno = request.getParameter("mobno");
String Address = request.getParameter("address");
String Password1 = request.getParameter("password1");
String Password2 = request.getParameter("password2");
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,"root", "root");
PreparedStatement pst =(PreparedStatement) conn.prepareStatement("insert into 'userlogindb'.'registerutable'(fname,mname,lname,username,emailid,mobno,address,password1,password2) values(?,?,?,?,?,?,?,?,?)");//try2 is the name of the table
pst.setString(1,Fname);
pst.setString(2,Mname);
pst.setString(3,Lname);
pst.setString(4,Uname);
pst.setString(5,Emailid);
pst.setString(6,Mobno);
pst.setString(7,Address);
pst.setString(8,Password1);
pst.setString(9,Password2);
int i = pst.executeUpdate();
conn.commit();
String msg=" ";
if(i!=0){
msg="Record has been inserted";
pw.println("<font size='6' color=blue>" + msg + "</font>");
}
else{
msg="failed to insert the data";
pw.println("<font size='6' color=blue>" + msg + "</font>");
}
pst.close();
}
catch (Exception e){
pw.println(e);
}
}
}
2.> index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form name="registrationform" action="register" method="post">
<p>
Enter your first name: <input type="text" name="fname"><br>
Enter your middle name: <input type="text" name="mname"><br>
Enter your last name: <input type="text" name="lname"><br>
</p><br>
<p>
Enter username: <input type="text" name="username"><br>
</p><br>
<p>
Enter email id: <input type="text" name="emailid"><br>
Enter mobile number: <input type="text" name="mobno"><br>
Enter address: <textarea rows="5" cols="5" name="address"></textarea><br>
</p><br>
<p>
Enter the password: <input type="password" name="password1"><br>
Reenter the password: <input type="password" name="password2"><br>
</p><br>
<p>
<input type="submit">
</p><br>
</form>
</body>
</html>
3.> web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>RegisterExample</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description>Register Servlet</description>
<display-name>Register</display-name>
<servlet-name>Register</servlet-name>
<servlet-class>register.com.Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
</web-app>
4.> I have added mysql-connector-java-5.0.8-bin.jar and servlet-api-3.0.jar is anything else needed to add it. I have created a connection to database in Data Source Explorer.
When I m compiling or debuging it shows no error. During runtime also there is no error.
When I fill in the form and submit it shows only blank screen :(
No output is displayed. :(
Also in the database values are not updated.
Please help me. I m getting hangover with this snippet.
Check that doPost() method of servlet is called from the jsp form and remove conn.commit.
Can you check value of i by putting logger or println(). and check with closing db conn at the end. Rest your code looks fine and it should work.
Same problem fetch main problem in PreparedStatement use simple statement then you successfully insert record same use below.
String st2="insert into
user(gender,name,address,telephone,fax,email,
destination,sdate,edate,Participant,hcategory,
Culture,Nature,People,Cities,Beaches,Festivals,username,password)
values('"+gender+"','"+name+"','"+address+"','"+phone+"','"+fax+"',
'"+email+"','"+desti+"','"+sdate+"','"+edate+"','"+parti+"',
'"+hotel+"','"+chk1+"','"+chk2+"','"+chk3+"','"+chk4+"',
'"+chk5+"','"+chk6+"','"+user+"','"+password+"')";
int i=stm.executeUpdate(st2);
In your JSP at line <form> tag,
try this code
<form name="registrationform" action="Register" method="post">
String user = request.getParameter("uname");
out.println(user);
String pass = request.getParameter("pass");
out.println(pass);
Class.forName( "com.mysql.jdbc.Driver" );
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/rental","root","root" ) ;
out.println("hello");
Statement st = conn.createStatement();
String sql = "insert into login (user,pass) values('" + user + "','" + pass + "')";
st.executeUpdate(sql);
Remove conn.commit from Register.java
In your jsp change action to :<form name="registrationform" action="Register" method="post">
I had a similar issue and was able to resolve it by identifying which JDBC driver I intended to use. In my case, I was connecting to an Oracle database. I placed the following statement, prior to creating the connection variable.
DriverManager.registerDriver( new oracle.jdbc.driver.OracleDriver());
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am writing a program in java that validate users and if the logged in user was admin he can add another user from registeration form to the database. but when I am going to register someone and press register button it shows me this error.
Here is my code:
index.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Application</title>
</head>
<body>
<form action="loginServlet" method="post">
<fieldset style="width: 300px">
<legend> Login to App </legend>
<table>
<tr>
<td>User ID</td>
<td><input type="text" name="username" required="required" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="userpass" required="required" /></td>
</tr>
<tr>
<td><input type="submit" value="Login" /></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
welcome.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome <%=session.getAttribute("name")%></title>
</head>
<body>
<h3>Register form</h3>
<form method="post" action="Register.jsp">
Name:<input type="text" name="name" /><br/>
Password:<input type="text" name="pass" /><br/>
Email:<input type="text" name="email" /><br/>
<input type="submit" value="register" />
</form>
</body>
</html>
NewFile.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome <%=session.getAttribute("name")%></title>
</head>
<body>
<h3>Login successful!!! user</h3>
<h4>
Hello,
<%=session.getAttribute("name")%></h4>
</body>
</html>
LoginCheck.java:
package com.example.saeid;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class LoginCheck {
static Boolean isadmin = false;
public static boolean validate(String name, int pass) {
boolean isValid = false;
Connection conn = null;
ResultSet rs = null;
String db_userName = "root";
String db_Password = "uyhgbv098";
String db_Name = "my_demo_database";
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
PreparedStatement ps = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url+db_Name,db_userName,db_Password);
ps =conn.prepareStatement
("select * from user_account where username=? and password=?");
ps.setString(1, name);
ps.setInt(2, pass);
rs = ps.executeQuery();
if(rs.next()) {
isValid = true;
isadmin = rs.getBoolean("isadmin");
}
}catch (Exception e) {
System.out.println(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return isValid;
}
public static Boolean admin(){
return isadmin;
}
}
loginservelet.java:
package com.example.saeid;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import com.example.saeid.LoginCheck;
public class LoginServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
String p=request.getParameter("userpass");
int p2 = Integer.parseInt(p);
HttpSession session = request.getSession(false);
if(session!=null)
session.setAttribute("name", n);
if(LoginCheck.validate(n, p2)){
if(LoginCheck.admin()){
RequestDispatcher rd=request.getRequestDispatcher("welcome.jsp");
rd.forward(request,response);
}
else{
RequestDispatcher rd=request.getRequestDispatcher("NewFile.jsp");
rd.forward(request,response);
}
}
else{
out.print("<p style=\"color:red\">Sorry username or password error</p>");
RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
rd.include(request,response);
}
out.close();
}
}
register.java:
package com.example.saeid;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Register extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String pass1 = request.getParameter("pass");
int pass = Integer.parseInt(pass1);
String email = request.getParameter("email");
try{
//loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
//creating connection with the database
String db_userName = "root";
String db_Password = "uyhgbv098";
String url = "jdbc:mysql://localhost:3306/";
String db_Name = "my_demo_database";
Connection con=DriverManager.getConnection
(url+db_Name,db_userName,db_Password);
PreparedStatement ps=con.prepareStatement
("insert into user_acount values(?,?,?)");
ps.setString(1, name);
ps.setInt(2, pass);
ps.setString(3, email);
int i=ps.executeUpdate();
if(i>0)
{
out.println("You are successfully registered");
}
}
catch(Exception se)
{
se.printStackTrace();
}
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>FirstHomework</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.example.saeid.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>register</servlet-name>
<servlet-class>com.example.saeid.Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>register</servlet-name>
<url-pattern>/Register</url-pattern>
</servlet-mapping>
</web-app>
You have not given the fully qualified name of Register servlet in web.xml:-
</servlet-mapping>
<servlet>
<servlet-name>register</servlet-name>
<servlet-class>Register</servlet-class> // give the full path
</servlet>
and another thing is that you are storing the password as a String in register.java but when you run the query in Loginservelet you are setting the password as Int. Please prefer password as a String in both classes.
Just as Mayank Sharma said
First, in the web.xml file, you have to specify Register servlet's full path in the servlet-class tag same way you did for LoginServlet class.
Secondly, the value of your register servlet url-pattern tag should be the same value (excluding /) given to the action attribute of the form tag in your welcome.jsp page.
Lastly, take note of Mayank Sharma's second observation.
I must suggest you have to start learning how to develop java web applications using framework. It will help you a lot.
I am beginner in JSP and Servlets. I have searched about the issue and couldn't found exactly what the solution is.
I am passing data from jsp to servlet and inserting in database and from there retrieving the same and passing to JSP for display
I was able to pass data from JSP and insert in database successfully but unable to retrieve and display in jsp again. Below is code.
jsp:
<!DOCTYPE HTML><%#page language="java"
contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>loginform</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<form name=loginform action=TestServlet method=post>
Input ID <input type=text name="id" size=10></input> <br><br>
<Input type="button" value=Retrive> <br>
<label for = "getdata" ></label> <br>
value is <%= request.getSession().getAttribute("data") %>
<input type=submit value=submit></input>
</form>
</body>
</html>
Servlet:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.*;
/**
* Servlet implementation class TestServlet
*/
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public TestServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
// Actual logic goes here.
try {
String getvalue=request.getParameter("id");
PrintWriter out = response.getWriter();
out.println(getvalue);
out.println("attempting to read from table");
Class.forName("oracle.jdbc.driver.OracleDriver");
// Open a connection
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#IP:Port:ServiceName, UN, Pass);
// Execute SQL query
Statement stmt = conn.createStatement();
String sqlinsert, sqlselect;
sqlinsert = "Insert into abc(abc) values("+getvalue+")";
sqlselect="Select abc from abc";
ResultSet rs = stmt.executeQuery(sqlinsert);
ResultSet rs1 = stmt.executeQuery(sqlselect);
int id=0 ;
// Extract data from result set
while(rs1.next()){
//Retrieve by column name
id = rs1.getInt("ABC");
//Display values
out.println("ID: " + id + "<br>");
}
HttpSession session = request.getSession(false);
request.setAttribute("data", "0");
request.getRequestDispatcher("/loginform.jsp").forward(request, response);
// out.println("</body></html>");
// Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
}
}
I am unable to understand where is the problem. Every time I run the code I am able to see only null in JSP.
Simply change request.getSession().getAttribute("data") to request.getAttribute("data") and it will work fine.
In your Java code you use request.setAttribute("data", "0"); ,but in you JSP page you use request.getSession().getAttribute("data") ,so you will not get the data.
you are actually storing your data in session and try to fetch it from request scope so i think you are getting null value.
in jsp remove <%= request.getSession().getAttribute("data") %> line and use this line <%= request.getAttribute("data") %>
i have problem how to call post method in java.When i pressed click button on login page after that did not show any thing on the browser.please tell me proper solution.my output show on console.so please tell me what is mistake.thanks in advance.
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="css/loginPage.css" />
<!-- <script src="js/jquery-ui.1.10.4.js"></script> -->
<title>Login Page</title>
</head>
<section class="login">
<div class="titulo">Staff Login</div>
<form action="/AdminLogin" name="AdminLogin" method="post">
<input type="text" title="Username required" placeholder="Username" data-icon="U">
<input type="password" title="Password required" placeholder="Password" data-icon="x">
<div class="olvido">
<div class="col">Register Student</div>
<div class="col">Fotgot Password?</div>
</div>
<button class="enviar">submit</button>
</form>
</section>
</html>
AdminLogin.java
package com.admin.main;
import java.beans.Statement;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.admin.dao.UserMasterConnection;
#WebServlet("/AdminLogin")
public class AdminLogin extends HttpServlet {
private static final long serialVersionUID = 1L;
Statement stmt;
UserMasterConnection userMasterConnection = new UserMasterConnection();
public AdminLogin()
{
super();
}
public void init(ServletConfig config) throws ServletException {
}
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("doget");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
System.out.println("doPost()");
/*System.out.println("dopost");
// connection with database
// Connection connection =
Connection connection = userMasterConnection.getConnection();
String selectTableSQL = "select * from user_detail where username=? and password=?";
try {
stmt = connection.createStatement();
// execute select SQL stetement
ResultSet rs = stmt.executeQuery(selectTableSQL);
while (rs.next())
{
// get username and password from login page
String username = request.getParameter("password");
String password = request.getParameter("username");
System.out.println(username);
}
} catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}*/
String username = request.getParameter("Password");
String password = request.getParameter("Username");
System.out.println("username :-"+username);
System.out.println("password"+password);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>SBTsystemAdminView</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>loginPage</servlet-name>
<servlet-class>com.Admin.main.AdminLogin</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginPage</servlet-name>
<url-pattern>/loginPage/*</url-pattern>
</servlet-mapping>
</web-app>
Get rid of the empty service method override. Its making the servlet do absolutely nothing. Read the documentation for HTTPServlet concerning the service method:
protected void service(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException,
java.io.IOException
Receives standard HTTP requests from the public service method and dispatches them
to the doXXX methods defined in this class. This method is an HTTP-specific version
of the Servlet.service(javax.servlet.ServletRequest,
javax.servlet.ServletResponse) method. There's no need to override
this method.
In other words, the standard implementation of this method figures out whether the request is GET or POST and routes to the doGet or doPost functions. If you override this method, especially with a blank function, then you are preventing the doGet and doPost functions from ever being reached.
I am newbie here. I have an assignment that requires to connect mysql, servlet and java (because i want to separate java code and html code. Previously, i combined the codes to make it easier and was rejected)
So, basically, in mySql i write this,
create table login2 (username varchar (30), password varchar(30), designation varchar(10));
insert into login2 values('lala','123','A');
and i create loginDisp.java in the servlet using eclipse. This is my command
package Servlet;
import java.io.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class loginDisp extends HttpServlet {
public void service(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException{
// String username=request.getParameter("Username");
// String password=request.getParameter("Password");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Servlet JDBC</title></head>");
out.println("<body>");
out.println("<h1>Servlet JDBC</h1>");
out.println("</body></html>");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con =DriverManager.getConnection
("url/tablename","uname","pssword");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM login2");
// displaying records
while(rs.next()){
out.print(rs.getObject(1).toString());
out.print("\t\t\t");
out.print(rs.getObject(2).toString());
out.print("<br>");
}
} catch (SQLException e) {
throw new ServletException("Servlet Could not display records.", e);
} catch (ClassNotFoundException e) {
throw new ServletException("JDBC Driver not found.", e);
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(con != null) {
con.close();
con = null;
}
} catch (SQLException e) {}
}
out.close();
}
}
When i execute, it is well displayed. Hence, i started to make the Login.jsp as i want to make a text.box for user to insert username and password. This is my code
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<body>
<center>
<div class="wrapper">
<br>
<br>
<h2>Doctor</h2>
<form name="form1" method="post" action="loginDisp" > <!-- onsubmit="return validateForm()" -->
<table width="326" border="1" align="center">
<center> <tr>
<th width="138" scope="row">Username</th>
<td width="142"><input type="text" name="Username"></td>
</tr>
</center>
<tr>
<th height="31" style="width: 162px;"><span class="style2">Password</span>
</th>
<td width="142"><input type="password" name="Password"></td>
</tr>
<tr>
</tr>
</table>
<p align="center">
<input type="submit" name="Submit" value="Submit">
</p> ${message}
</form>
</div>
</center>
</body>
</body>
</html>
and I get the data from mySQL displayed. I add another log.java in servlet because i thought when we need a data fetched from jsp to databased and displayed when be called. This is code in log.java
package Servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class log extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Get username and password from the JSP page
String username=request.getParameter("Username");
String password=request.getParameter("Password");
//Print the above got values in console
System.out.println("The username is" +username);
System.out.println("\nand the password is" +password);
}
}
The username and password inserted in login.jsp does not inserted automatically in mySQL, hence when i try to executed loginDisp.java , it will display only the data i inserted manually in mySQL.
You can not use the java file name as action this is defined in the web.xml file and there is servlet mapping and you can use
<servlet>
<servlet-name>log</servlet-name>
<servlet-class>loginDisplay</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>log</servlet-name>
<url-pattern>/loginDisplay</url-pattern>
</servlet-mapping>
and now you can use the action = "loginDisplay" in the action tag and by using this
I hope you did not face the problem of 404 error.
You entered a wrong action in form.
Since form's action attribute takes the path of the servlet you should give the relavent mapping specified in web.xml
action="loginDisplay.java"
should be action="/loginDisplay"
<form name="form1" method="post" action="loginDisplay.java" onsubmit="return validateForm()">
It should be
<form name="form1" method="post" action="/loginDisplay" onsubmit="return validateForm()">
If /loginDisplay is not the exact mapping in your web.xml check the web.xml file and see the mapping for loginDisplay and give that path as action.
A quick example
Create a new package (called dao or model) where you put your logic to access to the DB.
Then create a Java Bean Object where store the results of your DB and instanciate your class of the logic in the servlet, then access to the properties of the Bean and show it in the WEB.
package model:
class DaoAccess (methods to connect with DB)
class Login (properties of the table with getXXX and setXXX of each one)
package Servlet.
class loginDisplay:
public class loginDisplay extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Servlet JDBC</title></head>");
out.println("<body>");
out.println("<h1>loginDisplay</h1>");
out.println("</body></html>");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
DaoAccess dao = new DaoAccess();
List<Login> list = dao.readAll();
for(Login obj: list){
out.write(obj.getName());
out.write(obj.getPassword());
}
out.close();
}
}
I have a query that is being used to pull usernames and info about the user. In Access I had the LIKE function so that the user didn't have to type in a specific name. I am now transferring it over to JSP. Here is the line in the query that I am having troubles with in JSP:
WHERE ObjectName Like '" + "%"+ VariableName + "%" +"';
The query runs fine but does not show any information even if I put in the entire name. If I change it to:
WHERE ObjectName = '" + VariableName +"';
it works, but I would like to give the user a chance to have to ability to put in partial names in case they do not know how to spell the name or typ eit incorrectly. Any help would be apprecited.
Thanks
The line you've shown is a bit odd, but syntactically valid. So the problem lies somewhere else. What does variableName actually contain?
That said, you shouldn't be writing raw Java code in JSP files. Do that in a Java class. You can use a Servlet class to preprocess or postprocess requests. Also grab PreparedStatement to avoid SQL injections. Here's a kickoff example:
public List<User> search(String username) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
List<User> users = new ArrayList<User>();
try {
connection = database.getConnection();
statement = connection.prepareStatement("SELECT id, username, age, email FROM user WHERE username LIKE ?");
statement.setString(1, "%" + username + "%");
resultSet = statement.executeQuery();
while (resultSet.next()) {
users.add(mapUser(resultSet));
}
} finally {
close(connection, statement, resultSet);
}
return users;
}
Avoid writing SQL queries in JSP
"SELECT * FROM something WHERE ObectName LIKE '%" + VariableName + "%'" should work
this is an answer for starting users
i am created a data base in a name ASHRAF, then i create a table in name CASH. the code is given below
CREATE TABLE CASH(NO INT NOT NULL PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(50) NOT NULL,ADDRESS VARCHAR(100),PET_NAME VARCHAR(50),PLACE VARCHAR(50),TYPE VARCHAR(20),TYPE_OF_PAY VARCHAR(20),AMOUNT INT(6) NOT NULL);
here the NO is auto increment ant it is primary key anyway you can search the contents from the table using jsp code that i given below
am search here using both NAME ADDRESS you can pass the parameters using a html page and a servlet
The html page(show.html) that i created is given below
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>show.html</title>
</head>
<body>
<h1><b><font color=020202>SHOW</font></b></h1><br><br>
<form name="f6" action="getshow" method="POST" onsubmit="return check(this)">
<table border="0">
<tr>
<td>Name :</td><td><input type="text" name="name"></td>
</tr>
<tr>
<td>House Name :</td><td><input type="text" name="address"></td>
</tr>
<tr>
<td><br><input type="SUBMIT" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
The servlet is(getshow.java) given below
package Servlets;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class getdata
*/
public class getshow extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public getshow() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
`` throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**`
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
``response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try{
String url=null;
String s1=request.getParameter("name");
String s2=request.getParameter("address");
request.setAttribute("name",s1);
request.setAttribute("address",s2);
url="show.jsp";
RequestDispatcher view=request.getRequestDispatcher(url);
view.forward(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The jsp file is(show.jsp) given below
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>`
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>show.jsp</title>
</head>
<body>
<%String aid=(String)request.getAttribute("name"); %>
<%String sid=(String)request.getAttribute("address"); %>
<%
Connection con=null;
ResultSet rs=null;
String records=null;
StringBuffer appender=new StringBuffer();
java.sql.PreparedStatement st=null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection("jdbc:mysql://localhost/ASHRAF?user=root&password=password");
st=con.prepareStatement("select *from CASH where NAME like '" + aid + "%" +"' and ADDRESS like '" + sid + "%" +"'");
rs=st.executeQuery();
%>
<center><TABLE cellpadding="15" border="2">
<TR>
<TH>NO</TH>
<TH>NAME</TH>
<TH>HOUSE NAME</TH>
<TH>PET NAME</TH>
<TH>PLACE</TH>
<TH>TYPE OF OCCATION</TH>
<TH>TYPE OF PAY</TH>
<TH>AMOUNT</TH>
</TR>
<%
while (rs.next()) {
%>
<TR>
<TD><%=rs.getString(1)%></TD>
<TD><%=rs.getString(2)%></TD>
<TD><%=rs.getString(3)%></TD>
<TD><%=rs.getString(4)%></TD>
<TD><%=rs.getString(5)%></TD>
<TD><%=rs.getString(6)%></TD>
<TD><%=rs.getString(7)%></TD>
<TD><%=rs.getString(8)%></TD>
</TR>
<% } %>
</TABLE>
</center>
</div>
<%
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} %>
</body>
</html>
now you can search either with the name nor with the address or with both.