![]() |
VOOZH | about |
URL rewriting is a session tracking technique in Java Servlet where data such as a username or session ID is appended to the URL. Since HTTP is a stateless protocol, URL rewriting helps the server identify the same client across multiple requests, especially when cookies are disabled.
In web applications, the server often needs to identify the same user during multiple requests. For example, after login, the server should remember the user's information until logout. Since HTTP is stateless, URL rewriting is used to pass user-related information from one servlet to another through the URL.
Syntax:
out.print("<a href='SecondServlet?uname=" + n + "'>visit</a>");
In the above statement:
The generated URL looks like:
http://localhost:8080/ProjectName/SecondServlet?uname=Ravi
In Java Servlet, annotations are used to configure servlets without creating a web.xml file. The @WebServlet annotation maps a URL pattern directly to the servlet class, making configuration simpler and easier to manage.
Syntax:
@WebServlet("/ServletName")
Note :Generally we write web.xml file for request dispatcher but in this example we use annotation so their is no need of creating web.xml file.
First, create an HTML page that accepts the username from the user and sends the request to FirstServlet.
The browser displays a simple HTML form containing a text field to enter the username and a submit button to send the request to the servlet.
👁 ImageNow create a servlet that receives the username and appends it to the URL using URL rewriting.
After submitting the form, the browser displays a welcome message along with a hyperlink, and the URL changes to include the username as a query parameter.
👁 ImageNext, create another servlet that reads the value passed through the URL.
Output:
👁 ImageProgram flow
👁 ImageExplanation: When you deploy your project in eclipse the first page which is loaded in the HTML form whose form action is first servlet so the control will go to servlet1. In this case, we name servlet1 as FirstServlet where the username is printed. In FirstServlet we provide url where we transfer the control to servlet2 using url rewriting. In our case we name servlet2 as SecondServlet.