Hello every one,
i m trying to use session in jsp application for remembering username from one page to another. it is working fine but when i use hyperlink to come back to home page the username becomes null.
please help me how to remember username when user is using hyperlink?

Recommended Answers

All 10 Replies

If you put it in the session it shouldn't got away. You probably put it in the request, so better show some code.

hello,

the code which i m using to display username on each page is:
this is first page code: content.jsp

<% 
  	String username = request.getParameter("username"); 
session.setAttribute("username",                                                    request.getParameter("username"));
%>
<strong>  		
Welcome : <%=session.getAttribute("username") %></strong>

this code i am using on the next page: view.jsp

<%
		String username = request.getParameter("username");
		
		session.setAttribute("username", session.getAttribute("username")); 
		session.getAttribute("username");
		  %>
		Welcome : <%=session.getAttribute("username")%><br/>
			<a href="content.jsp">Home</a>

with the help of hyper link i am trying to go back. but when i click on "Home" it is showing null as username on the content page.

You are not suppose to change the username in the session. You put it once when you log in. You don't set it every time you load a page.
Of course it is null every time you do this:

String username = request.getParameter("username");
session.setAttribute("username", request.getParameter("username"));

If you don't pass the "username" as parameter in the request the first call will return null and then you will set null in the attribute.
The first call is completely useless if you have already put the username in the session after login.

So once you login put the username in the session and that's it. You don't need anything else. All you need to do next is get it from the session whenever you need it.
And after logout set it to null

Hello JavaAddict,
I am passing you my loginpage, content page and view page full code.
please help me how to make session true everywhere, while using hyperlink also.

login.jsp

<%@page import="java.util.Calendar, java.io.*, java.sql.Statement, java.sql.ResultSet, java.sql.Connection, com.userSet.userSet, com.dataEntry.*" session="true"%>
<%@ taglib uri="JavaclassTaglib.tld" prefix="mytaglib" %>
<html>
	<head>
		<title>LoginPage</title>
		<script language="javascript" src="username.js"></script>
		<script language="javascript" src="password.js"></script>
	</head>
	<body bgcolor="#C3D9FF" onload="func1(); func2();">
		<h1><font color="blue"><marquee style="margin: 0pt 0px; display: -moz-box;"> 
		
		</marquee></font></h1>
		<hr>
		<hr>
		<% 
			Calendar cale = Calendar.getInstance();
		%>
		<table align="right" border="0">
  	 	<%= "Date:"+cale.get(Calendar.DATE)+"/"+cale.get(Calendar.MONTH)+"/"+cale.get(Calendar.YEAR)%>
  	 	</table>
  	 	<a href="http://prashantp:8080/inventoryManagment/">Home</a>
  	 	<%
  	 		request.getSession(true);
  	 		session.setAttribute("username", request.getAttribute("username"));
  	 		
		%>
  	 	<center>
		<h1>Inventory <strong>Management System</strong></h1>
		</center>
	     <strong>
	     <%  
			connectionFile conef = new connectionFile(); 
			try 
			{ 
			String query = "Select * from login" ; 
			conef.coonnectionfile(query); 
			while(conef.rs.next()) 
				{ 
				String txt = request.getParameter("username"); 
				String txt1 = request.getParameter("password"); 
						
				String chk = conef.rs.getString("username"); 
				String chk1 = conef.rs.getString("password"); 
				 if (chk.equals(txt)&& txt!="" && txt!= null && chk1.equals(txt1) && txt1!="" && txt1!= null) 
					{ 
						System.out.println("Hello..."); 
		%></strong>
				<strong><jsp:forward page="content.jsp"></jsp:forward></strong>
		<strong><%	 
			 	   } 
					else 
					{ 
						System.out.println("Sorry...");	 }	 
				   }
		%></strong>
			
					<table align="right" >
					<tr>	
						<td>
							<font size="3"color="red" >	 
						 		The username or password you entered is incorrect. [?]
						 	</font>
						 </td> 
					</tr>	
					</table>
			
		<strong><%
				}catch(Exception ex)  
				{  
					System.out.println("EXCeption\t"+ex);  
				}  
			finally  
				{  
					if(conef.con!=null)  
						{  
							conef.rs.close();  
							conef.stmt.close();  
							conef.con.close();  
						}  
					else  
						{  
						     System.out.println("connection not closed in login.jsp");  
						}	  
				}  
		%><br/></strong><br/><table border="2" bordercolor="#5B77CC" bgcolor="white" width="338" height="100" align="right" cellspacing="5" cellpadding="1">
		<tr ><td><strong>To make your password more secure:<br> - Use letters and numbers  <br>-Use special characters(e.g., @)<br> - Mix lower and uppercase 
		</strong></td>
		</tr>
		<tr align="center" height="200" >
			<td >
				<form  method="post" name="form1" onsubmit="displayusername(); displaypassword()"><strong> 
					Username: 	<input type="text" name="username" ><br> 
								&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(e.g. [email]fr2rhy@yahoo.com[/email])<br> 
					Password: 	<input type="password" name="password"  maxlength="32"> <br> 
								&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  
					<span style="border-collapse: separate; color: rgb(0, 0, 0); font-family: 'Times New Roman'; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: normal; orphans: 2; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px;" class="Apple-style-span"> 
					<span style="color: rgb(80, 80, 80); font-family: arial; font-size: 10px; line-height: 12px; text-align: left;" class="Apple-style-span">Capitalization matters.<br>  
								&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
								&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Use 6 to 32 characters, no spaces, . 
								</span></span><br> 
	     						&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
	     			<input type="submit" value="submit"> 
	     			<input type="reset" name="reset" value="   reset   "><br></strong>
	     	</form>
	     </td>
	  </tr> 
	  <tr >
		<td><form action="registration.jsp" method = "Post"><strong> 
			I can not access my account!<a href="http://prashantp:8080/inventoryManagment/forgot.jsp">help</a><br><input type="button" name="forgot" value="Create an account&gt;&gt;"></strong>
			 </form>
		</td> 
	</tr>
</table>
</body>
</html>

"content.jsp"

<%@page language="java" import="java.util.Calendar,java.io.*, javax.servlet.http.*, java.sql.*, java.sql.SQLException, java.sql.Statement, java.sql.ResultSet, java.sql.Connection, com.dataEntry.*, com.userSet.userSet" errorPage="exceptionHandler.jsp" contentType="text/html" session="true" %>
<html>
	<head>
	<title>Content Page</title>
	<script language="JavaScript" type="text/JavaScript">

    </script>
	</head>
	<body bgcolor="#C3D9FF" link="#0000FF">
		<marquee>
			<font color="blue" size="30"</font>
		</marquee><hr>
		<% 
			Calendar cale = Calendar.getInstance();
		%>
		<table align="right" border="0">
		<tr>
			<td align = "right">
  	 			<%= "Date:"+cale.get(Calendar.DATE)+"/"+cale.get(Calendar.MONTH)+"/"+cale.get(Calendar.YEAR)%><br/>
  	 		 		 		
			</td>
  	 	</tr>
  	 	</table>
  	 		 	
  	 		 <% 
  	 		 	
				session.setAttribute("username", request.getParameter("username"));
			%>
				<strong>  
				
				Welcome : <%=session.getAttribute("username") %></strong>
				
				<% 	
				try
					{
						connectionFile conef=new connectionFile(); 
						String query = "Select username from login" ; 
						conef.coonnectionfile(query); 
						int count=0;
						conef.stmt.close();
						conef.con.close();
					}
					catch(Exception e)
					{
						System.out.println("EXCEPTION"+e);
					}
			%>
		
  	 	<center>
		<h1><strong>Inventory Management System</strong></h1><strong><br></strong>
		</center>
		<div id="Layer1" style="position:absolute; width:794px; height:115px; z-index:1; left: 217px; top: 178px;" >
		  <table width="748" border="0">
            <tr>
              <td width="641">  <strong><font size="+1">Inventory is a list for goods and materials held in stock by a business. </font></strong></td>
              <td width="97" ><strong><a href="http://prashantp:8080/inventoryManagment/view.jsp"> view</a></strong> </td>
            </tr>
            <tr>
              <td>  <strong><font size="+1">Inventories not intended for sale to customers or to clients may be held in any premises for organization uses. </font></strong></td>
              <td><strong><a href="http://prashantp:8080/inventoryManagment/add.jsp">add</a> &nbsp;</strong></td>
            </tr>
            <tr>
              <td> <strong><font size="+1">Inventory is a necessary part of doing business </font></strong></td>
              <td><strong><a href="http://prashantp:8080/inventoryManagment/update.jsp">update</a> &nbsp;</strong></td>
            </tr>
            <tr>
              <td> <strong><font size="+1">The functional factors explain the existence of inventory. </font></strong></td>
              <td><strong><a href="http://prashantp:8080/inventoryManagment/delete.jsp">delete</a> &nbsp;</strong></td>
            </tr>
            <tr>
              <td><strong><font size="+1">With the help of following link you can view, add update and delete the data from the database. </font></strong></td>
              <td><strong><a href="http://prashantp:8080/inventoryManagment/content.jsp">cancel</a> &nbsp;</strong></td>
            </tr>
          </table>
		</div>
	</body>
</html>

"view.jsp"

<%@page language="java" import="java.util.Calendar,java.io.*, javax.servlet.http.*, java.sql.*, java.sql.SQLException, java.sql.Statement, java.sql.ResultSet, java.sql.Connection, com.dataEntry.*, com.userSet.userSet" errorPage="exceptionHandler.jsp" contentType="text/html" session="true" %>
<html>
	<head>
	<title>Content Page</title>
	<script language="JavaScript" type="text/JavaScript" ></script>
	</head>
	<body bgcolor="#C3D9FF">
		<marquee>
			<font color="blue" size="30"></font>
		</marquee><hr><hr>
		<%connectionFile cone = new connectionFile(); %>
		<% 
			Calendar cale = Calendar.getInstance();
		%>
		<table align="right" border="0">
		<tr>
			<td align="right">
  	 			<%= "Date:"+cale.get(Calendar.DATE)+"/"+cale.get(Calendar.MONTH)+"/"+cale.get(Calendar.YEAR)%><br/>
  	 		</td>
  	 	</tr>
  	 	</table>
  	 	
		
		Welcome : <%=session.getAttribute("username")%><br/>
			<a href="content.jsp">Home</a>
	
  	 	<center>
		<h1>Inventory Management System</h1>
		
		<table border="1" cellspacing="15" bgcolor="white">
		<tr> 
			<th>productId</th>
			<th>&nbsp; &nbsp;&nbsp;&nbsp; itemid &nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <br></th>
			<th>&nbsp;&nbsp; &nbsp;&nbsp; name&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; <br></th>
			<th>Type</th>
			<th>&nbsp;&nbsp; &nbsp;&nbsp; companyname &nbsp; &nbsp; &nbsp; <br></th>
			<th>&nbsp;dateOfComingStock</th>
			<th>&nbsp;&nbsp;&nbsp;&nbsp; quantity&nbsp;&nbsp;&nbsp; <br></th>
			<th>weight</th>
			<th>&nbsp;&nbsp;&nbsp; costPrice&nbsp;&nbsp;&nbsp;&nbsp; <br></th>
			<th>&nbsp;&nbsp;&nbsp; sellingPrice&nbsp;&nbsp;&nbsp; <br></th>
			<th>manufacturingDate</th>
			<th>expiryDate</th>
			<th>color</th>
		</tr>
		</table>
		</center>
		
  	 	<% 
			String que="Select * from itemdetail";
			cone.coonnectionfile(que);
			while(cone.rs.next())
			{
				String productId = cone.rs.getString("productId");
				String itemid = cone.rs.getString("itemid");
				String name = cone.rs.getString("name");
				String Type = cone.rs.getString("Type");
				String companyname = cone.rs.getString("companyname");
				String dateOfComingStock = cone.rs.getString("dateOfComingStock");
				String quantity = cone.rs.getString("quantity");
				String weight = cone.rs.getString("weight");
				String costPrice = cone.rs.getString("costPrice");
				String sellingPrice = cone.rs.getString("sellingPrice");
				String manufacturingDate = cone.rs.getString("manufacturingDate");
				String expiryDate = cone.rs.getString("expiryDate");
				String color = cone.rs.getString("color");
		%>	
		<center>
		<table border="1" width="25" height="20" cellspacing="10" cellpadding="5" bgcolor="white">
			<tr>
				<th>
					<%=productId%>
				</th>
				<th>
					<%=itemid%>
				</th>
				<th>
					<%=name%>
				</th>
				<th>
					<%=Type%>
				</th>
				<th>
					<%=companyname%>
				</th>
				<th>
					<%=dateOfComingStock %>
				</th>
				<th>
					<%=quantity %>
				</th>
				<th>
					<%=weight%>
				</th>
				<th>
					<%=costPrice %>
				</th>
				<th>
					<%=sellingPrice %><br/>
				</th>
				<th>
					<%=manufacturingDate%>
				</th>
				<th>
					<%=expiryDate%>
				</th>
				<th>
					<%=color%>
				</th>
			</tr>
		</table>
		</center>	
			<%
				}
 			%>
		 </body>
</html>

please help me.....

When the user logs in take the username and put it the session:

String username = request.getParameter("username");
String password = request.getParameter("password");

boolean b = checkLogin(username, password);

if (b) {
  // user valid
  request.getSession.setAttribute("username", username);
} else {
  // Error: invalid username, password
}

That's it. It's in the session. You don't need to put it every time you go to a page, because it's IN THE SESSION . Just get it and check if it is not null.
Also learn the difference between session and request, and what it means to put something inside each one of them.

Also when you logout do this:

request.getSession.setAttribute("username", null);

These are the only two times where you will need to set the value of the session.

I didn't read your code nor will I ever read such un-formatted code.

hello javaAddict,
sorry to disturbe you, but as you suggested me the code like
[
request.getSession.getAttribute("username");
]
i tried this, but it is not working.

please check my this sample code.

Demosession.html
[
<<HTML>
<BODY>
<FORM METHOD=POST ACTION="DemoSession.jsp">
What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>

>
]
in this page i have written just input box and sending it to the next page DemoSession.jsp

[
<%
String name = request.getParameter( "username" );
session.setAttribute( "theName", name );
%>
<HTML>
<BODY>
Hello, <%=session.getAttribute("theName")%>
<A HREF="NextPage.jsp">Continue</A>
</BODY>
</HTML>
]
in this, i have given one link for another page and displaying the username.
Now from the NextPage.jsp, i am trying to come back to DemoSession.jsp and trying to display the username on NextPage.jsp.
code of NextPage.jsp is
[
<HTML>
<BODY>
Hello, <%= session.getAttribute( "theName" ) %>
<a href= "DemoSession.jsp">home</a>
</BODY>
</HTML>
]

In the above code everything is working fine, but when i click Home link on NextPage.jsp to come back at DemoSession.jsp the username is becoming null.
Please help me how to make it correct, so if user come back the username should not be null.

When you go back to the DemoSession.jsp this code is executed:

String name = request.getParameter( "username" );
session.setAttribute( "theName", name );

But this: request.getParameter( "username" ) will return null since you didn't submit anything in the request. So you get null and you put null. There are ways to fix this but we generally don't do things that way. You could do this:

<a href= "DemoSession.jsp?username=<%= session.getAttribute( "theName" ) %>">home</a>

Also whenever you go to that page you need to make sure that you have submitted a field with name "username" or put it in the link as described.

Usually I don't get such a problem because I don't put these things together:

String name = request.getParameter( "username" );
session.setAttribute( "theName", name );

I put the setting of the session at a page before the homepage. So when I go to homepage I already have the session. And I don't return to the first page unless I have logged out.


You can also do this:

String name = request.getParameter( "username" );
String sessName = session.getAttribute( "theName" );

//check whether one of the above is null and act accordingly

Example: if name is null and sessName not null you can do this:
name = sessName
Or put the name in the session only when it is not null.

@javaAddict,
Thanks javaAddict. this is working fine.
but as you suggested, i tried storing session first in login page only but the same error was coming so i tried to store it in the content page.
but i want to say thanks again!!!

I have similar prob. The get attribute is null while the id is not null.
for my java:

if(session.getAttribute(abc)==null)
 System.out.println(abc is null
else
 System.out.println(abc is not null)

if(session.getId()==null)
 System.out.println(id is null)
else
  System.out.println(abc is not null)

Do i need to also use session.setAttribute(abc) in the jsp?

I have similar prob. The get attribute is null while the id is not null.
for my java:
if(session.getAttribute(abc)==null)
System.out.println(abc is null
else
System.out.println(abc is not null)

if(session.getId()==null)
System.out.println(id is null)
else
System.out.println(abc is not null)

Do i need to also use session.setAttribute(abc) in the jsp?

Start your own thread, be more descriptive, did you put it in the session?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.