使用 HttpServletResponse 对象,通过设置响应头的方式,实现页面跳转。
使用 HttpServletResponse 对象,通过设置响应头的方式,实现页面跳转。
使用 @WebServlet 注解的方式创建 Servlet。
运用 HttpServletResponse 对象,通过 setHeader 方法设置响应头 location,同时设置响应码为 302。
@WebServlet("/demo04")
public class ServletDemo extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
// 设置响应的内容类型和编码
response.setContentType("text/html;charset=utf-8");
// 跳转新页面
response.setHeader("location","http://www.haicoder.net");
// 设置响应码
response.setStatus(302);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
跳转后如下图:
以上案例使用 HttpServletResponse 对象,通过设置响应头 location ,并设置响应码为 302(注意:两个设置缺一不可,与 重定向 效果一样)。