ServletResponse 请求重定向

public class Response1 extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("曾到此一游 Response1 ");

req.setAttribute("key1", "value1");

/**
* 请求重定向的第一种方案(不推荐)
*/
// 设置响应状态码302 ,表示重定向,(已搬迁)
resp.setStatus(302);
// 设置响应头,说明 新的地址在哪里
resp.setHeader("Location", "http://localhost:8080/07_servlet/response2");
resp.setHeader("Location", "http://localhost:8080");

//resp.sendRedirect("http://localhost:8080");

//String contextPath = req.getContextPath();
//resp.sendRedirect("http://localhost:8080" + contextPath);//

/**
* 请求重定向和第二种方案(推荐使用
*/
resp.sendRedirect("http://localhost:8080");
//如果是在同一台服务器上,也可以使用相对路径
//resp.sendRedirect("/07_servlet/response2");
}
}
posted @ 2020-12-12 11:42  water-droplet  阅读(207)  评论(0)    收藏  举报