<strong><span style="font-size:14px;"></span></strong><pre name="code" class="java"><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 12px; background-color: rgb(255, 255, 255);"><span style="font-size:14px;"></span></strong><pre name="code" class="java" style="display: inline !important;">httpServletResponse.sendRedirect("/linkin/Linkin.jsp");转发:
httpServletRequest.getRequestDispatcher("/Linkin.jsp").forward(httpServletRequest, httpServletResponse);在jsp中,也经常用到转发。
<jsp:forward page="Linkin.jsp" />
forward和include方法接收的两个参数必须是传递给当前Servlet的service方法的那两个ServletRequest和ServletResponse对象,或者是对它们进行了包装的ServletRequestWrapper 或ServletResponseWrapper对象。
重定向过程:客户浏览器发送http请求----》web服务器接受后发送302状态码响应及对应新的location给客户浏览器--》客户浏览器发现是302响应,则自动再发送一个新的http请求,请求url是新的location地址----》服务器根据此请求寻找资源并发送给客户。在这里location可以重定向到任意URL,既然是浏览器重新发出了请求,则就没有什么request传递的概念了。在客户浏览器路径栏显示的是其重定向的路径,客户可以观察到地址的变化的。
package linkin; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author LinkinPark * @author 2015-7-8 * @Descri 转发 */ public class LinkinServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); String userName = req.getParameter("userName"); String passWord = req.getParameter("passWord"); req.setAttribute("userName", userName); req.getSession().setAttribute("passWord", passWord); req.getRequestDispatcher("/Linkin.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
package linkin; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author LinkinPark * @author 2015-7-8 * @Descri 重定向 */ public class LinkinServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); String userName = req.getParameter("userName"); String passWord = req.getParameter("passWord"); req.setAttribute("userName", userName); req.getSession().setAttribute("passWord", passWord); resp.sendRedirect("/linkin/Linkin1.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u011794238/article/details/46801761