请求转发时会共享request变量,但请求跳转时不共享该变量。
通过request.sendRedirect()实现重定向。
通过request.getRequestDispatcher().forward()实现请求转发。
通过request.getRequestDispatcher().include()实现请求包含。
请求重定向测试代码如下:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String url = request.getRequestURL().toString();
System.out.println("=============================");
System.out.println(url);
String uname = request.getParameter("login");
System.out.println("----------->"+uname);
if(uname.equals("baidu")){
response.sendRedirect("http://www.baidu.com");
}else{
response.sendRedirect("http://www.126.com");
}
}
通过输入内容判断如果输入baidu则跳转到百度首页,否则跳转到126首页。
转发测试代码如下:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String URL = this.getServletContext().getInitParameter("url");
String Redurl = request.getParameter("url");
System.out.println("--->"+ Redurl);
System.out.println("------------->"+ URL);
PrintWriter out = response.getWriter();
if(Redurl.equals("baidu")){
//response.sendRedirect("http://www.baidu.com");
request.getRequestDispatcher("/success.html").forward(request, response);
}else{
//response.sendRedirect("http://www.126.com");
request.getRequestDispatcher("/false.html").forward(request, response);
}
out.print(this.getClass());
out.println(", using the GET method");
out.println("please url:"+ URL);
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
通过request.getRequestDispatcher().include()实现转发包含,将指定页加到本页。
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String URL = this.getServletContext().getInitParameter("url");
String Redurl = request.getParameter("url");
System.out.println("--->"+ Redurl);
System.out.println("------------->"+ URL);
PrintWriter out = response.getWriter();
if(Redurl.equals("baidu")){
//response.sendRedirect("http://www.baidu.com");
//request.getRequestDispatcher("/success.html").forward(request, response);
request.getRequestDispatcher("/success.html").include(request, response);
}else{
//response.sendRedirect("http://www.126.com");
//request.getRequestDispatcher("/false.html").forward(request, response);
request.getRequestDispatcher("/false.html").include(request, response);
}
out.print(this.getClass());
out.println(", using the GET method");
out.println("please url:"+ URL);
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
运行结果如图: