实现重定向
B一个web资源收到客户端A请求后,B他会通知A客户端去访问另外一个web资源C,这个过程叫重定向
常见场景:
●用户登录
void sendRedirect(String var1) throws IOException;
代码实现:
RedirectServlet:
package com.allen.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class RedirectServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.sendRedirect("/response_war_exploded/img"); //重定向 } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
web.xml:
<servlet> <servlet-name>RedirectServlet</servlet-name> <servlet-class>com.allen.servlet.RedirectServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>RedirectServlet</servlet-name> <url-pattern>/redirect</url-pattern> </servlet-mapping>
启动测试:
访问:http://localhost:8080/response_war_exploded/redirect
重定向到:http://localhost:8080/response_war_exploded/img,url地址栏发生变化。