Servlet URL Rewriting

This is another approach to maintain the session of a user. In this mechanism, when a client make a request then some extra information is appended in the URL of that request.

This extra information uniquely identifies a user and it may be a path info, parameter attribute etc. Unlike cookies, URL Rewriting will also work when cookies are disabled in our browser.

Example of URL Rewriting

Let’s see an example of URL Rewriting.

Welcome.jsp

<html>
<body>
<center>
<h1>Welcome to Tutorial and Example</h1>
</center>
</body>
</html>

DemoURLRewriting.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/serv")
public class DemoURLRewriting extends HttpServlet {
protected void doGet(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
String path = req.getContextPath();
String addURL = res.encodeURL(path + "/Welcome.jsp");
pw.println("<html>");
pw.println("<head>");
pw.println("<title>TutorialandExample</title>");
pw.println("</head>");
pw.println("<body><center>");
pw.println("<h1>URL Rewriting Demo</h1>");
pw.println("<h3>For next page - <a href=\"" + addURL
+ "\"> Click Here</a></h3>");
pw.println("</center></body>");
pw.println("</html>");
}
}
Output: