在servlet中实现页面跳转

客户端跳转
// 使用response对象的sendRedirect实现客户端跳转

// servlet的doGet方法
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException {
PrintWriter out
= res.getWriter();
out.println(
"Hello world!");
res.sendRedirect(
"test.do"); // servlet实现跳转(客户端跳转)
}
客户端跳转不能像目标页面传递参数(如果使用该方法非要向目标页面传递参数的话,可以可以使用session对象将参数值记录,在此不详细记录)
服务器端跳转
  // 使用RequestDispatcher接口实现服务器端跳转,且向目标页面传递参数

public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException,
IOException{
PrintWriter out
= resp.getWriter();

/*
* 在servlet中实现服务器端跳转,并向跳转页面传递参数
*/

req.setAttribute(
"name", "haiyun"); // 为request对象添加参数
RequestDispatcher dispatcher = req.getRequestDispatcher("test-04.jsp"); // 使用req对象获取RequestDispatcher对象
dispatcher.forward(req, resp); // 使用RequestDispatcher对象在服务器端向目的路径跳转
}
原文地址:https://www.cnblogs.com/yunfour/p/1958675.html