Getting null value when passing the variable from jsp to servlet - java

I am trying to get a value from jsp to sevlet.First the variable value is taken by session setArribute(), getAttribute() then I need to pass that particular variable from jsp to servlet but I am getting null value for that variable.
Here below I am sharing my code, can anyone findout how can I solve this issue?
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%#page import="java.sql.*"%>
<html>
<head>
<title>Welcome to survey</title>
</head>
<body>
<%
ResultSet rset;
String sur_id = request.getParameter("surveyid");
session.setAttribute( "surveyid", sur_id );
int new_survey_id = Integer.parseInt(sur_id);
if (request.getParameter("surveyid") == null) {
out.println("Please enter your name.");
} else {
out.println("Hello <b>"+request.getParameter("surveyid")+"</b>!");
}
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/surveysample", "root", "root");
String query = "select * from surveydetail where surveyid ="+ new_survey_id ;
Statement stmt = con.createStatement();
rset = stmt.executeQuery(query);
while(rset.next()){
// out.println(rset.getString(1));
// out.println(rset.getString(2));
// out.println(rset.getString(3));
// out.println(rset.getString(4));
%>
<table border="3">
<tr><td>Survey_Id</td><td><%=rset.getString(1)%></td></tr>
<tr><td>Family name</td><td><%=rset.getString(2)%></td></tr>
<tr><td>First name</td><td><%=rset.getString(3)%></td></tr>
<tr><td>Middle name</td><td><%=rset.getString(4)%></td></tr>
<tr><td>gender</td><td><%=rset.getString(5)%></td></tr>
<tr><td>dat of birth</td><td><%=rset.getString(6)%></td></tr>
<tr><td>income</td><td><%=rset.getString(7)%></td></tr>
<tr><td>complete address</td><td><%=rset.getString(8)%></td></tr>
<tr><td>coordinates</td><td><%=rset.getString(9)%></td></tr>
<tr><td>mobile number</td><td><%=rset.getString(10)%></td></tr>
<tr><td>email address</td><td><%=rset.getString(11)%></td></tr>
<tr><td>present Internet provider</td><td><%=rset.getString(12)%></td></tr>
<tr><td>comments</td><td><%=rset.getString(13)%></td></tr>
<tr><td>remarks</td><td><%=rset.getString(14)%></td></tr>
<br>
<form>
<table>
<tr><td><input type="button" value="edit" onclick="javascript:document.forms[0].action = 'EditSurvey.jsp'; document.forms[0].submit();"></td>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
<td><input type="button" value="delete"></td>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
<td><input type="button" value="print"></td>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
<td><input type="button" value="send mail"></td>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
</tr>
</table>
</form>
</table>
<%
}
%>
</body>
</html>
from the above code I have set the session variable as surveyid
and I can get it from the below code.It is working properly
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Edit survey</title>
</head>
<body>
<%
ResultSet resultSet;
String surveyId = (String) session.getAttribute("surveyid");
out.println("check"+surveyId);
request.setAttribute("surveyid", surveyId);
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/surveysample", "root", "root");
String query = "select * from surveydetail where surveyid ="+ surveyId ;
Statement stmt = con.createStatement();
ResultSet rset = stmt.executeQuery(query);
while(rset.next()){
%>
<form name="Editsurveyform" method="post" action="EditSurvey">
<table>
<tr><td>Family name:</td><td><input type="text" name="familyName" value='<%=rset.getString(2)%>'></td></tr>
<tr><td>First name:</td><td><input type="text" name="firstName" value='<%=rset.getString(3)%>'></td></tr>
<tr><td>Middle name:</td><td><input type="text" name="middleName" value='<%=rset.getString(4)%>'></td></tr>
<tr><td>Gender:</td>
<td>
<%
if(rset.getString(5).equals("male")){
%>
<input type="radio" name="sex" value="male" checked>Male
<input type="radio" name="sex" value="female">Female
<%}
else{
%>
<input type="radio" name="sex" value="male">Male
<input type="radio" name="sex" value="female" checked>Female
<%
}
%>
</td>
</tr>
<tr><td>Birthday:</td><td><input type="date" name="dob" value='<%=rset.getString(6)%>'></td></tr>
<tr><td>Income : A?B?C?D?</td><td><input type="text" name="income" value='<%=rset.getString(7)%>'></td></tr>
<tr><td>Complete Address:</td><td><input type="text" name="address" value='<%=rset.getString(8)%>'></td></tr>
<tr><td>Coordinates:</td><td><input type="text" name="coordinates" value='<%=rset.getString(9)%>'></td></tr>
<tr><td>Mobile number:</td><td><input type="tel" name="mobileno" value='<%=rset.getString(10)%>'></td></tr>
<tr><td>Email Address:</td><td><input type="email" name="email" value='<%=rset.getString(11)%>'></td></tr>
<tr><td>Present internet provider:</td><td><input type="text" name="iprovider" value='<%=rset.getString(12)%>'></td></tr>
<tr><td>Positive comments with present provider:</td><td><textarea name="comments" cols="40" rows="5"><%=rset.getString(13)%></textarea></td></tr>
<tr><td>Negative remarks with present provider:</td><td><textarea name="remarks" cols="40" rows="5"><%=rset.getString(14)%></textarea></td></tr>
<tr><td><input type="submit" name="editsurvey" value="update survey details"></td><td><input type="reset" name="cancel" value="cancel"></td></tr>
</table>
</form>
<%}
//response.sendRedirect("EditSurvey?surveyId="+surveyId);
%>
</body>
</html>
But I encounter the problem in below java
package com.survey;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
/**
* Created by rajee on 2/18/15.
*/
public class EditSurvey extends HttpServlet {
public String familyName;
public String firstName;
public String middlename;
public String gender;
public String dateOfBirth;
public String income;
public String completeAddress;
public String coordinates;
public String mobileno;
public String emailAddress;
public String presentIP;
public String comment;
public String remark;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String surveyId = (String) request.getAttribute("surveyid");
System.out.println(surveyId);
familyName = request.getParameter("familyName");
firstName = request.getParameter("firstName");
middlename = request.getParameter("middleName");
gender = request.getParameter("sex");
dateOfBirth = request.getParameter("dob");
income = request.getParameter("income");
completeAddress = request.getParameter("address");
coordinates = request.getParameter("coordinates");
mobileno = request.getParameter("mobileno");
emailAddress = request.getParameter("email");
presentIP = request.getParameter("iprovider");
comment = request.getParameter("comments");
remark = request.getParameter("remarks");
System.out.println(familyName);
System.out.println(firstName);
System.out.println(middlename);
System.out.println(gender);
System.out.println(dateOfBirth);
System.out.println(income);
System.out.println(completeAddress);
System.out.println(coordinates);
System.out.println(mobileno);
System.out.println(emailAddress);
System.out.println(presentIP);
System.out.println(comment);
System.out.println(remark);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
Connection conn=null;
String url="jdbc:mysql://localhost:3306/";
String dbName="surveysample";
String driver="com.mysql.jdbc.Driver";
//String dbUserName="root";
//String dbPassword="root";
// try{
//
//
// Class.forName(driver).newInstance();
// conn = DriverManager.getConnection(url + dbName, "root", "root");
// PreparedStatement pst =(PreparedStatement) conn.prepareStatement("insert into surveysample.surveydetail(familyname,firstname,middlename,gender,dateofbirth,income,complete_address,coordinates,mobilenumber,emailaddress,presentiprovider,comments,remarks) values (?,?,?,?,?,?,?,?,?,?,?,?,?)");//try2 is the name of the table
//
// pst.setString(1,familyName);
// pst.setString(2,firstName);
// pst.setString(3,middlename);
// pst.setString(4,gender);
// pst.setString(5,dateOfBirth);
// pst.setString(6,income);
// pst.setString(7,completeAddress);
// pst.setString(8,coordinates);
// pst.setString(9,mobileno);
// pst.setString(10,emailAddress);
// pst.setString(11,presentIP);
// pst.setString(12,comment);
// pst.setString(13,remark);
//
//
// 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);
// }
//
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
code

If your problem is for surveyId being null is servlet, it is normal because you try to get it from request :
String surveyId = (String) request.getAttribute("surveyid");
As you put it in session, you should read it from there :
String surveyId = (String) request.getSession().getAttribute("surveyid");

You can try below code in your servlet as :
HttpSession session = request.getSession(false);
String surveyId = (String) session.getAttribute("surveyid");
this method request.getSession(false) will not create new session if session object is already exists. it will simply return old session object if its there otherwise it will return null.

Related

How to show data of current loged in user?

I want to show firstname, lastname, username and password of logged in user in jsp textbox, but it show details of every user like this:
For now I have only two users in MySql database.
But, for example if I log in as a gordon_k, how to show only his data?
I have servlet (LoginServlet.java) like this:
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
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 javax.servlet.http.HttpSession;
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/e-book", "root", "root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select username,password from users where username='" + username
+ "' and password='" + password + "'");
if (rs.next()) {
response.sendRedirect("mainMenu.jsp");
HttpSession session = request.getSession();
session.setAttribute("username", username);
} else {
out.println("Wrong id and/or password");
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And jsp file like this:
changePersonalData.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%
String id = request.getParameter("id");
String driver = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String database = "e-book";
String userid = "root";
String password = "root";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<!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>Change</title>
</head>
<body>
<form method="post" action="ChangePersonalDataServlet">
<table align="left">
<%
try {
connection = DriverManager.getConnection(connectionUrl + database, userid, password);
statement = connection.createStatement();
String sql = "select * from users";
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
%>
<tr>
<td>First name</td>
<td><input type="text" name="firstname"
value="<%=resultSet.getString("first_name")%>"></td>
</tr>
<tr>
<td>Last name</td>
<td><input type="text" name="lastname"
value="<%=resultSet.getString("last_name")%>"></td>
</tr>
<tr>
<td>User name</td>
<td><input type="text" name="username"
value="<%=resultSet.getString("username")%>"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password"
value="<%=resultSet.getString("password")%>"></td>
</tr>
<%
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
<tr>
<td></td>
<td><input type="submit" value="Change"></td>
</tr>
</table>
</form>
</body>
</html>
Change in changePersonalData.jsp like following to get username from session and pass this username in your sql query to get selected user data:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%
String id = request.getParameter("id");
String driver = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String database = "e-book";
String userid = "root";
String password = "root";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<!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>Change</title>
</head>
<body>
<form method="post" action="ChangePersonalDataServlet">
<table align="left">
<%
try {
connection = DriverManager.getConnection(connectionUrl + database, userid, password);
statement = connection.createStatement();
String username = (String) request.getSession().getAttribute("username");
String sql = "select * from users where username='"+username+"'";
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
%>
<tr>
<td>First name</td>
<td><input type="text" name="firstname"
value="<%=resultSet.getString("first_name")%>"></td>
</tr>
<tr>
<td>Last name</td>
<td><input type="text" name="lastname"
value="<%=resultSet.getString("last_name")%>"></td>
</tr>
<tr>
<td>User name</td>
<td><input type="text" name="username"
value="<%=resultSet.getString("username")%>"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password"
value="<%=resultSet.getString("password")%>"></td>
</tr>
<%
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
<tr>
<td></td>
<td><input type="submit" value="Change"></td>
</tr>
</table>
</form>
</body>
</html>

request.getParameter returns null in JSP

Form.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Form</title>
<body bgcolor="#FFFFFF" text="#000000">
<h1>Please enter your details</h1>
<form name="RegistrationForm" action="NewUser" method="post">
<table cellspacing="5" cellpadding="5" border="1">
<tr>
<td align="right">First Name:</td>
<td><input type="text" name="NewFirstName"></td>
</tr>
<tr>
<td align="right">Last Name:</td>
<td><input type="text" name="NewLastName"></td>
</tr>
<tr>
<td align="right">Email Address:</td>
<td><input type="text" name="EmailAddress"></td>
</tr>
<tr>
<td align="right">Phone Number:</td>
<td><input type="text" name="Phone Number"></td>
</tr>
<tr>
<td align="right">Semester</td>
<td><input type="text" name="Semester"></td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
</body>
</html>
NewUser.java(Servlet Class)
package com.seria.quiz;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class NewUser
*/
#WebServlet("/NewUser")
public class NewUser extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public NewUser() {
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 {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
Connection conn = null;
try {
String FirstName = request.getParameter("firstName");
System.out.println("Your firstname: " + FirstName);
String LastName = request.getParameter("lastName");
System.out.println("Your LastName: " + LastName);
String Emailid = request.getParameter("email");
String PhoneNumber = request.getParameter("phoneNumber");
String Semester = request.getParameter("semester");
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/seriaquiz", "root", "root");
PreparedStatement pst = (PreparedStatement) conn
.prepareStatement("insert into formdetails(firstName,lastName,email,phoneNumber,semester) values(?,?,?,?,?)");// try2
// the
// name
pst.setString(1, FirstName);
System.out.println("Your firstname1: " + FirstName);
pst.setString(2, LastName);
System.out.println("Your LastName1: " + LastName);
pst.setString(3, Emailid);
pst.setString(4, PhoneNumber);
pst.setString(5, Semester);
int i = pst.executeUpdate();
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);
}
}
}
As the title says request.getParameter is returning null every time. I put sysout statements after requestParameter, and it shows null value. Any help will be appreciated. Sorry for any inconvenience, I'm new here.
The parameter names in servlet need to match them in the JSP
so
String FirstName = request.getParameter("firstName");
should be
String FirstName = request.getParameter("NewFirstName");
you are asking for wrong parameters
you should always ask for same id/name as described in your html
request.getParameter("NewFirstName");
From w3.org section 17.2 Controls
Users interact with forms through named controls.
A control's "control name" is given by its name attribute. The scope of the name attribute for a
control within a FORM element is the FORM element.
When a form is submitted for processing, some controls have their name paired with their current
value and these pairs are submitted with the form.
Example of control is your
<input type="text" name="NewFirstName">
So when the form gets submitted, it contains a control name=value e.g.
NewFirstName=YourFirstName
In your JSP, you should do access it using the the control name
String FirstName = request.getParameter("NewFirstName");
Reference: http://www.w3.org/TR/html401/interact/forms.html
Get the exact value of a form parameter try this....
String FirstName = request.getParameter("NewFirstName");
because ..
you specify name attribute by 'NewFirstName'...

How to fetch an id from the database after record inserted in db [duplicate]

This question already has answers here:
How to get the insert ID in JDBC?
(14 answers)
Closed 8 years ago.
How to fetch id from db using JSP servlet. This is my JSP servlet code and I need code for display id through alert message box and in my db I will gave id as auto-increment in data base. I am trying this for last two days .
How to fetch a id from the database after record inserted in db?
Kindly help me out for displaying an id like "registration is suss-your id is ........."
package controller;
import java.io.IOException;
import java.io.PrintWriter;
javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
//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 = 2945154063362413961L;
/**
* #see HttpServlet#HttpServlet()
*/
public Register() {
super();
// TODO Auto-generated constructor 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 fname=request.getParameter("firstname");
String lname=request.getParameter("lastname");*/
//pw.println("Firstname is" +fname);
//pw.println("Firstname is" +lname);
/*System.out.println("first=="+fname);
System.out.println("last==="+lname);
*/
//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="Registrationform";
String driver="com.mysql.jdbc.Driver";
String dbUserName="root";
String dbPassword="root";
try{
String Fname = request.getParameter("firstname");
String Lname = request.getParameter("lastname");
String dob = request.getParameter("dob");
String email= request.getParameter("email");
Class.forName(driver).newInstance();
System.out.println("welcome");
conn = DriverManager.getConnection(url+dbName,dbUserName, dbPassword);
System.out.println("Connection created");
PreparedStatement pst =(PreparedStatement) conn.prepareStatement("insert into event (firstname,lastname,dob,email) values(?,?,?,?)");//try2 is the name of the table
pst.setString(1,Fname);
pst.setString(2,Lname);
pst.setString(3,dob);
pst.setString(4,email);
int i = pst.executeUpdate();
System.out.println("Query updated");
PreparedStatement pstr =(PreparedStatement) conn.prepareStatement("select * from event(id);");//try2 is the name of the table
//conn.commit();
String msg=" ";
if(i!=0){
msg="You Are Succesfully Register For The Event Meet";
//alert("You Are Succesfully Register For The E;vent Meet")
// response.sendRedirect("reg.jsp");
pw.println("<font size='4' color=black font family = times new roman >" + msg + "</font>");
}
else{
msg="Failed to insert the data";
pw.println("<font size='4' color=black font family = times new roman >" + msg + "</font>");
}
pst.close();
}
catch (Exception e){
pw.println(e);
}
}
}
java script code
<%# 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">
<link rel="stylesheet" type="text/css" href="reg.css">
<title>Event Registration From</title>
</head>
<body class= "main">
<script type="text/javascript">
function register(registerform)
{
if(registerform.firstname.value == "") {
alert("Please enter your Firstname");
registerform.firstname.focus();
return false;
}
if(registerform.lastname.value == "") {
alert("Please enter your Lastname");
registerform.lastname.focus();
return false;
}
if(registerform.dob.value == "") {
alert("Please select your DOB");
registerform.dob.focus();
return false;
}
if(registerform.email.value == "") {
alert("Please enter your Email-id");
registerform.email.focus();
return false;
}
/* var x=document.forms["form"]["email_id"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
} */
return true;
}
</script>
<form name="registerform" action ="Register" method = "post">
<div>
<h3> Event Registration Form </h3>
<div>
<label for ="first" class ="label" > First Name </label>
<input type="text" id="first" name="firstname" class="text" />
</div>
<div>
<label for ="last" class ="label">Last Name</label>
<input type="text" id="last" name="lastname" class="text">
</div>
<div>
<label for ="dob" class ="label">Date Of Birth </label>
<input type="text" id="dob" name="dob" class="text">
</div>
<div>
<label for ="email" class ="label">Email_Id</label>
<input type="text" id="email" name="email" class="text">
</div>
<div><input type="submit" value ="submit" class="button" onclick="register(registerform)"></div>
</div></form>
</body>
</html>
You can try something like this with MySQL:
PreparedStatement ps = connection.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
// Get generated key.
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
if (rs.next()) {
int key = rs.getInt(1);
}
Where ps is the PreparedStatement and you retrieve the key from the ResultSet object.
To get the last generated auto-increment id you can use the MySql function LAST_INSERT_ID().
Another option would be to use the MAX aggregation function to return the maximum value for the id field. Since the last inserted id is always the max MAX(id).
Because this is a standard way, this has been added to a constant, so doing:
PreparedStatement ps = con.prepareStatement(YOUR_SQL, Statement.RETURN_GENERATED_KEYS);
For some JDBC drivers like Oracle you have to specify the columns explicitly:
PreparedStatement ps = con.prepareStatement(YOUR_SQL, new String[]{"USER_ID"});

In struts 1.3 how to retrieve data from database and display it using DAO

*M new to struts. I am making simple login page that display username and password by retrieving it from database. I m using DAO.
I have LoginDAO.java, LoginAction.java and Displaydata.jsp pages. *
LoginDAO.java
public boolean login(String user,String pass) throws SQLException
{
Connection con = getConnection();
Statement st;
try {
st = con.createStatement();
st.executeQuery("select * from login where Username='" + user + "' and Password='" + pass + "'");
return true;
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return false;
}
LoginAction.java
public class LoginAction extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm rf= (DynaValidatorForm) form;
String username = rf.get("username").toString();
String password = rf.get("password").toString();
HttpSession session=request.getSession();
session.setAttribute("user", username);
Login dao= new Login();
if(dao.login(username,password))
{
System.out.println("GOT");
return mapping.findForward("success");}
else
{System.out.println("NOT");
return mapping.findForward("failure");
}
}
}
and also what do i write in Dislpaydata.jsp to display username and password in it dont want any java code in it.
Thankyou
Right. Some time ago I built an application with Struts 1.x and MySql with login.
LoginAction
public ActionForward login( ... ) throws Exception {
String forward;
final String mail = PropertyUtils.getProperty(form, "mail");
final String password = PropertyUtils.getProperty(form, "password");
if (LoginService.getInstance().validate(mail, password)) {
// Do something e.g. put name of user in session
forward = SUCCESS;
} else {
forward = ERROR;
}
return mapping.findForward(forward);
}
LoginService
public boolean validate(final String mail, final String password)
throws ServiceException {
try {
final boolean valid;
// Validate null and empty
// Validate with DB
final UserDAO dao = new UserDAO();
final User user = dao.findByPk(mail);
if (user == null) {
valid = false;
} else {
if (password.equals(user.getPassword())) {
valid = true;
} else {
valid = false;
}
}
return valid;
} catch (DAOException e) {
throw new ServiceException("Error validating user and password.", e);
}
}
UserDAO
private static final String FIND_BY_PK_SQL
= "SELECT mail, name, password, admin FROM user WHERE mail = ?";
public User findByPk(final String mail) throws DAOException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = getConnection();
ps = conn.prepareStatement(FIND_BY_PK_SQL);
ps.setString(1, mail); // PK, NOT NULL
rs = ps.executeQuery();
if (rs.next()) {
return fill(rs);
}
return null;
} catch (final SQLException e) {
throw new DAOException(e);
} finally {
// Close DB resources
}
}
private User fill(final ResultSet rs) throws SQLException {
final User user = new User();
user.setMail(rs.getString("mail"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("password"));
user.setAdmin(rs.getBoolean("admin"));
return user;
}
In my case I have a table user with mail as a primary key. There are various forms.
More examples:
Building a Login Application
Struts Login Application Using Action Form Tutorial | DZone
Creating a Email Login Web Application with Struts
e.g. For show the name of variable user in session scope from the database:
LoginAction
if (LoginService.getInstance().validate(mail, password)) {
final HttpSession session = request.getSession();
final User user = UserService.getInstance().getUser(mail);
session.setAttribute("user", user);
forward = SUCCESS;
}
home.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
Welcome,
<bean:write scope="session" name="user" property="name" filter="false" />
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Login Page</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript"
src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script>
</head>
<body bgcolor="#2EFEF7">
<form action="action" method="post" id="formDemo" name="MyForm">
<div id="header">
<h2 style="color: red;">Training</h2>
</div>
<hr>
<h3>Login</h3>
<div id="center" style="padding-top: 50px; padding-bottom: 220px;">
<table align="center">
<tr>
<th colspan="2"><h1 style="color: BLUE;">LOGIN</h1></th>
</tr>
<tr>
<th colspan="2"><h5 id="error" style="color: red;"></h5></th>
</tr>
<tr>
<td>UserID:</td>
<td><input type="text" size="40" name="UserId" maxlength="8"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" size="40" name="Password" maxlength="8"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit"
value="Login"> <input type="button" id="reset"
value="Clear"></td>
</tr>
</table>
</div>
<hr>
<div id="footer">
<label>Copy right# 2000-2008 FUJINET, All Rights Reserved.</label>
</div>
</form>
<script type="text/javascript">
<!--
// Form validation code will come here.
function validate() {
if (document.MyForm.UserId.value === ""
|| document.MyForm.UserId.value === null) {
document.getElementById("error").innerHTML = "Please insert userId";
return false;
}
if (document.MyForm.Password.value === ""
|| document.MyForm.Password.value === null) {
document.getElementById("error").innerHTML = "Please insert password";
return false;
}
return (true);
}
$("#reset").click(function(event) {
document.MyForm.UserId.value = "";
document.MyForm.Password.value = "";
document.getElementById("error").innerHTML = "";
});
$("#formDemo").submit(function(event){
return validate();
});
</script>
</body>
</html>

How to implement username availability using JSP

In my application I have a username with a textbox, a checkbutton and a password. After entering the username into the textbox, if I click on check button it should search in the MySQL database for the username, if it is available it should display the message if not an other message should be displayed.
How do I do that with JSP?
i tried the follwing code:
<form method="post" name="frm_addUser" action="./adduserserver.jsp"><br><br>
<table width="500px;" border="0" cellpadding="5" cellspacing="1" bgcolor="#f8f8ff" bordercolor="#333366" align="center">
<tr>
<td bordercolor="Gainsboro"><font size="4">User ID</font></td>
<td bordercolor="Gainsboro"><input name="userid" style="WIDTH: 200px"></td></tr>
<tr>
<td bordercolor="Gainsboro"><font size="4"> </font></td>
<!--<td><input value="Check availability" onclick="" class="btn_checkavail" type="button"></td></tr>-->
</td>
<td>
<input type="submit" value="check" name="check"
onclick="" /></td></tr>
<tr>
<td bordercolor="Gainsboro"><font size="4">Pass Word </font></td>
<td bordercolor="Gainsboro"><input name="password" type="password" style="WIDTH: 200px"></td></tr>
<tr>
<td bordercolor="Gainsboro"><font size="4">Confirm Password </font></td>
<td bordercolor="Gainsboro"><input name="confirmpassword" type="password" style="WIDTH: 200px"></td></tr>
<tr>
<%
try{
String username=request.getParameter("username");
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","sumith");
st=con.createStatement();
sqlQuery="select distinct username from usernameexist where username='"+username+"'";
rs=st.executeQuery(sqlQuery);
int count=0;
while(rs.next())
{
count++;
}
if(count>0)
{
out.println("<html>");
out.println("<head>");
out.println("<title>MeterDetailsPage</title>");
out.println("</head>");
out.println("<body>");
out.println("<table align='center' color='red'>");
out.println("<tr color='red'>");
out.println("<td ><font size=4 color=red >username Already Exist</font></td>");
out.println("</tr>");
out.println("</table>");
out.println("</body>");
out.println("</html>");
}
else
{
if(username!=null )
{
if(!username.equals(""))
{
//st.executeUpdate("insert into usernameexist(username) values('"+username+"')");
out.println("<html>");
out.println("<head>");
out.println("<title>username</title>");
out.println("</head>");
out.println("<body>");
out.println("<table align='center'>");
out.println("<tr>");
out.println("<td ><font size=4 color=green><b>available </b></font></td>");
out.println("</table>");
out.println("</body>");
out.println("</html>");
}
}
}
st.close();
con.close();
}
catch(Exception e){}
%>
</table>
</form>
</body>
</html>
Try This it will work,
<%# 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>Index Page</title>
<script src="http://code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
<script src="js/app-ajax.js" type="text/javascript"></script>
</head>
<body>
Enter Your Name: <input type="text" id="name" /><br>
Enter our user name :<input type="text" id="userName"><br>
Enter your Password :<input type="password" id="password"><br>
<input type="button" value="Submit" onclick="ajaxCall();">
<br>
<strong> Response</strong>:
<div id="ajaxGetUserServletResponse"></div><br>
</body>
</html>
Ajax file
function ajaxCall(){
var name = jQuery("#name").val();
var userName = jQuery("#userName").val();
var password= jQuery("#password").val();
alert(name);
alert(userName);
alert(password);
jQuery.ajax({
url : "GetUserServlet",
method: "GET",
type : "JSON",
data : "name="+name+"&userName="+userName+"&password="+password,// query parameters 1st
success : function(response){
$('#ajaxGetUserServletResponse').text(response);
}
});
}
Servlet
import java.io.IOException;
import java.util.ArrayList;
import javax.management.relation.RelationSupportMBean;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetUserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
userBean ub = new userBean();
String name = request.getParameter("name").trim();
String userName = request.getParameter("userName").trim();
String password = request.getParameter("password").trim();
System.out.println("name catched "+name);
System.out.println("username catched"+userName);
System.out.println("Password catched"+password);
ArrayList<userBean> list = new ArrayList<userBean>();
ub=new userBean();
ub.setName(name);
ub.setUserName(userName);
ub.setPassword(password);
list.add(ub);
response.setContentType("text/plain");
response.getWriter().print(list);
}
}
Pojo Class
public class userBean
{
private String name;
private String userName;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
My scenario was little bit different you can alter the code in index.jsp and add the call on button "Check Availability" and bring the response from servlet.
check your table name in query
select distinct username from usernameexist where username='"+username+"'";
make sure your table is usernameexist
and
String username=request.getParameter("username");
here parameter is userid not username
so use
String username=request.getParameter("userid");
Your should do below :
Make sure that your jsp is passing all fields including checked field to servlet. You can do form post which has all attributes.
Your servlet should read all parameters and if check-box is checked then you put appropriate logic in servlet (like querying your MySQL db)
Return proper response from your servlet so that jsp can show appropriate message. You can keep messages in your jsp/js and based on flag you can show appropriate message to user.
you can use as follows.. attach jquery file in source code
<script src="jquery-1.9.1.js">
IN Form
<input type="text" name="userName" id="userName" onBlur="checkId(this.value)">
<span id="status"></span>
<script type="text/javascript">
function checkId(member_id)
{
$.ajax({
type: "POST",
url: "processAjax.jsp", /* The request will be processed in this file.. */
beforeSend: function() {
$("#divIdStatus").html("geting name...");
},
data: "member_id=" + member_id ,
success: function(msg) {
$("#divIdStatus").html(msg);
}
});
}
IN processAjax.js
String member_id = (request.getParameter("member_id")).trim();
if (member_id.equals("")) {
out.print("! This is Required");
} else {
ResultSet result = // check in database if any record with this user name;
if (result.next()) {
out.print("! Not Available");
} else {
out.print("OK..");
}
}

Categories

Resources