Session management using url rewriting in servlet

This tutorial shows how applications uses session management using url rewriting in servlet with simple example

URL rewriting in Servlet

Session management can be achieved by URL rewriting if cookies are disabled in a browser by the client.

In URL rewriting, a token(parameter) is added at the end of the URL. The token consist of name/value pair separated by an equal(=) sign.

When the user clicks the hyperlink, the parameter name/value pairs will be passed to the server. From a Servlet, we can use getParameter() method to obtain a parameter value.

Servlet URL Rewriting example

Try this below login page with invalid username or password to see how url rewriting works

index.jsp

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String st=request.getParameter("status");
if(st==null)
{
   st="";
}
%>

<p style="color: red;"> <%=st %></p>

<h1>Simple Url rewritting example</h1>

<form action="RegisterController" method="post">
   Username: <input type="text" name="uname"> <br>
   Password: <input type="password" name="pass"> <br>
   <input type="submit" value="Login">
</form>
</body>
</html>

Servlet Registration Controller 

package com.candidjava;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class RegisterController
 */
@WebServlet("/RegisterController")
public class RegisterController extends HttpServlet
{

   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
   {
      String un=request.getParameter("uname");
      String pw=request.getParameter("pass");

      if(un.equals("candid")&&pw.equals("123456"))
      {
         response.sendRedirect("home.jsp");
      }
      else
      {
         response.sendRedirect("index.jsp?status=invalid username or password");
      }
   }
}

home.jsp

<%@ 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>Insert title here</title>
</head>
<body>

Try login with invalid username to learn how url rewritting works

</body>
</html>

 

Output Screenshot

 

Download Source Code

Servlet url rewriting war

Servlet url rewriting zip

 

Leave a Reply

Your email address will not be published. Required fields are marked *