I have login.jsp page where I try to username and password from text boxes are passed to servlet though session. The code o login.jsp is given below:
<form name="frm" action="DisplayData" method="post" onsubmit="return Validate()" >
<table align="center">
<tr>
<td align="left">UserName:</td>
<td><input type="text" name="username" value=""></input></td>
</tr>
<tr>
<td align="left">Password:</td>
<td><input type="password" name="password" value=""></input> </td>
</tr>
</table>
<%
String name = request.getParameter("username");
String password = request.getParameter("password");
session.setAttribute("name",name);
session.setAttribute("pass", password);
%>
<table align="center">
<tr>
<input type="hidden" name="hiddenname" value="login">
<td><input align="middle" type="submit" name="Sign_in" value="Sign_in" onclick="return Validate()"></input></td>
<td><input type="button" value="Signup" onClick="javascript:window.location='Signup.jsp';"></input></td>
</tr>
</table>
</form>
I would like to retrieve the username and password that is set in login.jsp to servlet. I tried using the following code but it gives me null value. The java code I used in servlet is given below:
HttpSession session = request.getSession(true);
String name=(String)session.getAttribute("name");
System.out.println("Welcome"+name);
Could anyone tell me where I am making mistake. I Need the username to be stored in session so that I can make use of this for multiple request in that servlet
You are getting null being returned from
session.getAttribute("name")
because you are setting the name attribute in the session when the jsp is rendered. At this time, the username is not entered. What you need to do is get the username usinggetParameter()
in the servlet and save it in the session if you want.