URL Rewriting
In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource. We can send parameter name/value pairs using the following format:
url?name1=value1&name2=value2&??
A name and a value is separated using an equal = sign, a parameter name/value pair is separated from another parameter using the ampersand(&). 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.
Advantage of URL Rewriting
- It will always work whether cookie is disabled or not (browser independent).
- Extra form submission is not required on each pages.
Disadvantage of URL Rewriting
- It will work only with links.
- It can send Only textual information.
Example of using URL Rewriting
In this example, we are maintaning the state of the user using link. For this purpose, we are appending the name of the user in the query string and getting the value from the query string in another page.
index.html
- <form action="servlet1">
- Name:<input type="text" name="userName"/><br/>
- <input type="submit" value="go"/>
- </form>
FirstServlet.java
- import java.io.*;
- import javax.servlet.*;
- import javax.servlet.http.*;
-
-
- public class FirstServlet extends HttpServlet {
-
- public void doGet(HttpServletRequest request, HttpServletResponse response){
- try{
-
- response.setContentType("text/html");
- PrintWriter out = response.getWriter();
-
- String n=request.getParameter("userName");
- out.print("Welcome "+n);
-
-
- out.print("<a href='servlet2?uname="+n+"'>visit</a>");
-
- out.close();
-
- }catch(Exception e){System.out.println(e);}
- }
-
- }
SecondServlet.java
- import java.io.*;
- import javax.servlet.*;
- import javax.servlet.http.*;
-
- public class SecondServlet extends HttpServlet {
-
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- try{
-
- response.setContentType("text/html");
- PrintWriter out = response.getWriter();
-
-
- String n=request.getParameter("uname");
- out.print("Hello "+n);
-
- out.close();
-
- }catch(Exception e){System.out.println(e);}
- }
-
-
- }
web.xml
- <web-app>
-
- <servlet>
- <servlet-name>s1</servlet-name>
- <servlet-class>FirstServlet</servlet-class>
- </servlet>
-
- <servlet-mapping>
- <servlet-name>s1</servlet-name>
- <url-pattern>/servlet1</url-pattern>
- </servlet-mapping>
-
- <servlet>
- <servlet-name>s2</servlet-name>
- <servlet-class>SecondServlet</servlet-class>
- </servlet>
-
- <servlet-mapping>
- <servlet-name>s2</servlet-name>
- <url-pattern>/servlet2</url-pattern>
- </servlet-mapping>
-
- </web-app>
No comments:
Post a Comment