Oct 23, 2014

Using Session In JSP Pages

Normally when it come to a websites users will visit many pages. As the developer of the web site some time you need to keep some data that need to gets in all the pages. You can use session to keep those data.

To set and retrieve the session variable value you can use following codes.

Setting The Value
session.setAttribute("Variable_Name","Value_You_Want_To_Store");

Retrieving The Value
String Your_Variable = (String)session.getAttribute("Variable_Name");


Following Example Demonstrate a Simple Program To Explain The JSP Pages. Following Example Contains Three JSP Files. One Is To Get The User Inputs. Then Another One To Set The User Inputs In The Session. And The Last One Is To Access The Session value And Display It.

index.jsp
<html>
   <head>
      <title>Getting User Inputs</title>
   </head>
   <body>
      <form action ="SetSession.jsp" method ="POST">
         First Name :<input type ="text" name="firstName" size ="20"/></br>
         Last Name :<input type ="text" name="lastName" size ="20"/></br>
         <input type="submit" value="Set Session"/>
      </form>
    </body>
 </html>

SetSession.jsp
<%
    String sFName = request.getParameter("firstName");
    String sLName = request.getParameter("lastName");

    session.setAttribute("sFirstName",sFName);
    session.setAttribute("sLastName",sLName);
    response.sendRedirect("ViewSession.jsp");
%>

ViewSession.jsp
<html>
   <head>
      <title>Retrieving Session</title>
   </head>
   <body>
      <h1>Getting Session Variables</h1>
      <h1>This page is used to get the session variables that we set early</h1>
      <%
         String FName = (String)session.getAttribute("sFirstName");
         String LName = (String)session.getAttribute("sLName");
      %>
      <h1>First Name : <% out.print(FName); %></h1>
      <h1>Last Name : <% out.print(LName); %></h1>
   </body>
 </html>


No comments:

JWT Token Decode Using Jquery

When it come to authentication we use many mechanism. Ones the user authenticated we must keep these details somewhere safe. So we can share...