In URL rewriting, we append a token or identifier to the URL of subsequent Servlet or subsequent resource. we will send parameter name/value pairs using the subsequent format:
url?name1=value1&name2=value2&??
A name and a worth 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 are going to be passed to the server. From a Servlet, we will use the getParameter() method to get a parameter value.
In this example, we're maintaining the state of the person using the link. For this purpose, we're appending the identity of the consumer withinside the question string and getting the price from the question string in some other page.
Index.html
<form action="servlet1"> Name:<input type="text" name="userName"/><br/> <input type="submit" value="go"/> </form>
First Servlet.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); //appending the username in the query string out.print("+n+"" data-mce-href="servlet2?uname="+n+"">visit"); 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(); //getting value from the query string 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>
download this example (developed using Myeclipse IDE)
download this example (developed using Eclipse IDE)
download this example (developed using Netbeans IDE)