介绍
本文介绍 通过request、response对象跳转页面
通过 request 转发页面
Controller
@RequestMapping("/query")
public void query(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("username","李雷");
request.getRequestDispatcher("/result.jsp").forward(request,response);
}
注意: 这种方式,视图解析器 不起作用,所以要写 完整的页面路径
jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${username}
<%=request.getAttribute("username")%>
</body>
</html>
通过 response 重定向页面
例子1
@RequestMapping("/query2")
public void query2(HttpServletResponse response) throws IOException {
response.sendRedirect("http://www.baidu.com");
}
例子2
例子2
@RequestMapping("/query4")
public void query4(HttpServletRequest request,HttpServletResponse response) throws IOException {
response.sendRedirect(request.getContextPath()+"/result.jsp");
}
注意: 重定向 的路径,要加上 上下文,最终表示 http://ip:port/context/result.jsp