servlet请求重定向
作者:互联网
请求重定向的第一种方案:
准备两个servlet程序
Response1
public class Response1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Hello Response1");
//设置响应状态码302,表示垂定向,(已搬迁)
resp.setStatus(302);
//设置响应头,说明新的地址在哪里
// resp.setHeader("location","http://localhost:8080/servlet/response2");
//可以访问工程以外的地址 ,但是不能访问WEB-INF里面的内容
resp.setHeader("location","http://www.baidu.com");
}
}
Response2
public class Response2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("response2' s result!");
}
}
xml配置
<servlet>
<servlet-name>Response1</servlet-name>
<servlet-class>com.example.servlet.Response1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Response1</servlet-name>
<url-pattern>/response1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Response2</servlet-name>
<servlet-class>com.example.servlet.Response2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Response2</servlet-name>
<url-pattern>/response2</url-pattern>
</servlet-mapping>
请求重定向的第二种方案:
public class Response1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Hello Response1");
//设置响应状态码302,表示垂定向,(已搬迁)
// resp.setStatus(302);
//设置响应头,说明新的地址在哪里
// resp.setHeader("location","http://localhost:8080/servlet/response2");
//可以访问工程以外的地址 ,但是不能访问WEB-INF里面的内容
// resp.setHeader("location","http://www.baidu.com");
//第二种方法
//直接写地址就可以 302是固定的不需要设置
resp.sendRedirect("http://www.baidu.com");
}
}
标签:http,重定向,Response1,resp,Response2,servlet,302,请求 来源: https://blog.csdn.net/weixin_51797050/article/details/119273801