Step8- Session Management + code

Learn with our youtube video –

Basic concept of session- store some data of client temporarily which should be available until client destroy it.

Session management definition- It’s a mechanism used by web container to save state of client.

Session management includes-
1- session (interface)
2- cookies(class)
3- url rewriting
4- Hidden form field

FeatureSessionCookiesURL RewritingHidden Form Field
DefinitionA session is a way to store information (in variables) to be used across multiple pages.Cookies are small
text files
stored
on a user’s
computer by
a web server
to remember
stateful
information.
URL rewriting is the technique of manipulating the URL in the address bar to include additional information, such as session data.Hidden form fields are inputs in an HTML form that are not displayed to the user, but are sent to the server when the form is submitted.
Use CaseStoring user-specific information, such as a user’s shopping cart or login status.Remembering
user preferences,
login information,
and other
stateful information across multiple web pages.
Maintaining stateful information, such as a user’s session, without using cookies.Sending information to the server that is not meant to be modified by the user, such as a unique identifier for a form submission.
ImplementationUsing HttpSession in Java Servlets.Using the javax.servlet.http.
Cookie class in Java Servlets.
Manipulating the URL in the address bar manually or using a library such as Apache UrlRewriteFilter.Adding hidden inputs to an HTML form using the <input type="hidden"> tag.

1-Session-
Step 1- creation of sessions-

(i)HttpSession ses=request.getsession();

-Returns existing session object else creates new session object.

(ii)HttpSession ses=request.getsession(true);

-Always returns existing session object.

(iii)HttpSession ses=request.getsession(false);

-Always creates new session object.

Step 2- Initialization of servlet-

ses.setAttribute(key, value);

Note- Remove Attribute-
ses.removeAttribute(key);

Step 3- Access of session-

ses.getAttribute(key);

4- Deletion of session-

ses.invalidate ();

Example 7- Wep app to create session at correct login, get session data from at profile page, and then logout to delete session.

Project 5 files-

1-index.html(inside WebContent)

2-Login.java(inside pacage=’ab’)

3-Profile.java(inside pacage=’ab’)

4-profile.html(inside WebContent)

5-Logout.java(inside pacage=’ab’)

1-index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="a">
email
<input type="text" name="e">
password
<input type="password" name="p">
<input type="submit">
<a href="b">View Profile</a>
</body>
</html>

2-Login.java(servlet)

package ab;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
@WebServlet("/a")
public class Login extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String E1="mrjava@gmail.com";
String P1="java123";

String E2=request.getParameter("e");
String P2=request.getParameter("p");

if(E1.equals(E2) && P1.equals(P2)){

HttpSession ses=request.getSession();
ses.setAttribute("mail", E2);
response.sendRedirect("b");

}else{
response.sendRedirect("index.html");
}

}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

doGet(request, response);
}

}


3-Profile.java(servlet)

package ab;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;
@WebServlet("/b")
public class Profile extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

PrintWriter out=response.getWriter();
HttpSession ses=request.getSession();
String m=(String) ses.getAttribute("mail");

if(m!=null){
response.sendRedirect("profile.html");
}else{
RequestDispatcher rd=request.getRequestDispatcher("index.html");
rd.include(request, response);
out.println("You are not logged in.");
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}

}

4-profile.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Welcome user
<a href="c">Logout(remove the session)</a>
<a href="index.html">Go back(Keep the session)</a>
</body>
</html>

5-Logout.java(servlet)

package ab;

import java.io.IOException;
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;

/**
* Servlet implementation class Logout
*/
@WebServlet("/c")
public class Logout extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public Logout() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

HttpSession ses=request.getSession();
ses.invalidate();
response.sendRedirect("index.html");
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}

}

2- Cookies-

-cookie is a class.
-It stores textual data at client side.
-Less secure than session.

Step 1- creation of cookie-
Cookie ck= new cookie(key, value);

Step 2- send to the client side(browser)-
response. addCookie(ck);

Step 3- access the cookie-
Cookie[] c= request.getCookies();

Step 4- deletion of cookie-
ck.setAge(0);
response.addCookie(ck);

Example 8- Wep app to create cookie and add into browser at correct login, get cookies data from at profile page, and then logout to delete cookie.

output-

ckks

Project Structure-

5 files-

1-index.html(inside WebContent)

2-Login.java(inside pacage=’ab’)

3-Profile.java(inside pacage=’ab’)

4-profile.html(inside WebContent)

5-Logout.java(inside pacage=’ab’)

1-index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="login">
email
<input type="text" name="e">
password
<input type="password" name="p">
<input type="submit">
<a href="profile">View Profile</a>
</body>
</html>

2-Login.java(servlet)

package ab;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
@WebServlet("/login")
public class Login extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String E1="mrjava@gmail.com";
String P1="java123";
String E2=request.getParameter("e");
String P2=request.getParameter("p");
if(E1.equals(E2) &amp;&amp; P1.equals(P2)){
Cookie cookie = new Cookie("mail",E2);
response.addCookie(cookie);
response.sendRedirect("b");
}else{
response.sendRedirect("index.html");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response); } }

3-Profile.java(servlet)

package ab;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;
@WebServlet("/profile")
public class Profile extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();

Cookie[] ck2=request.getCookies();
System.out.println(ck2);

if(ck2!=null){
response.sendRedirect("profile.html");
}else{
RequestDispatcher rd=request.getRequestDispatcher("index.html");
rd.include(request, response);
out.println("You are not logged in.");
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}

}

4-profile.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Welcome user
<a href="logout">Logout(remove the session)</a>
<a href="index.html">Go back(Keep the session)</a>
</body>
</html>

5-Logout.java(servlet)

package ab;

import java.io.*;
import javax.servlet.http.*;
@WebServlet("/logout")
public class Logout extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

Cookie[] ck2=request.getCookies();
for (Cookie c : ck2) {
c.setMaxAge(0);
response.addCookie(c);
}
response.sendRedirect("index.html");
}

3- Url Rewriting-
Step 1- add “?” At the end of url
Step 2 -add data in following format-
Attribute=value
Step 3- separate these attribute and value with “&” symbol

Example 9- Web app to add data with url and get it on next servlet.

output-

Project Structure-

2 files-

1-index.html(inside WebContent)

2-A.java(inside pacage=’ab’)

1-index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="first?name=mr.Java&email=a@a.com">Click here</a>
</body>
</html>

2-A.java(servlet)

package ab;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;
@WebServlet("/first")
public class A extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String s1=request.getParameter("name");
String s2=request.getParameter("email");

PrintWriter out=response.getWriter();
out.println(s1);
out.println(s2);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}

}

4- hidden form field-
Step1- create input box with type=hidden
Step2- assign it’s value
Step3- get value of input box on next servlet.

Example 10- Wep app get data from hidden input box on next servlet.

output-

Project Structure-

2 files-

1-index.html(inside WebContent)

2-A.java(inside pacage=’ab’)

1-index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="first">
<input type="text" name="a">
</br>
<input type="password" name="b">
<input type="hidden" name="c" value="Surprise">
<input type="submit">
</body>
</html>

2-A.java(servlet)

package ab;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;
@WebServlet("/first")
public class A extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String s1=request.getParameter("a");
String s2=request.getParameter("b");
String s3=request.getParameter("c");

PrintWriter out=response.getWriter();
out.println(s1);
out.println(s2);
out.println(s3);

}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}

}