HttpServletResponse实现重定向
一个web资源收到客户端请求后,通知a客户访问另一个web资源,这个过程叫重定向
常见场景:用户登录
使用resp.sendRedirect请求跳转至指定的页面
public class RedirectServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // resp.sendRedirect(req.getContextPath()+"/image"); // resp.setHeader("Location","image"); // resp.setStatus(302); resp.sendRedirect("image"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
image界面是实现验证码
测试request请求
public class RequestTest extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("进入RequestTest请求"); //处理请求 String username = req.getParameter("username"); String password = req.getParameter("password"); System.out.println(username+","+password); resp.sendRedirect("success.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
在初始界面进入index.jsp
<html> <body> <h2>Hello World!</h2> <%--提交的路径是项目的路径--%> <form action="${pageContext.request.contextPath}/login" method="get"> 用户名:<input type="text" name="username"> 密码:<input type="text" name="pwd"> <input type="submit"> </form> <%@page contentType="text/html;" pageEncoding="UTF-8"%> </body> </html>
提交后跳到request的login下,使用重定向进入success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1> 欢迎进入 </h1> </body> </html>
servlet定义
<servlet> <servlet-name>image</servlet-name> <servlet-class>com.gu.servlet.ImageServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>image</servlet-name> <url-pattern>/image</url-pattern> </servlet-mapping> <servlet> <servlet-name>RedirectServlet</servlet-name> <servlet-class>com.gu.servlet.RedirectServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>RedirectServlet</servlet-name> <url-pattern>/red</url-pattern> </servlet-mapping> <servlet> <servlet-name>request</servlet-name> <servlet-class>com.gu.servlet.RequestTest</servlet-class> </servlet> <servlet-mapping> <servlet-name>request</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping>
标签:day101,重定向,ServletException,resp,req,HttpServletResponse,Override,image From: https://www.cnblogs.com/GUGUZIZI/p/17239330.html