1. 跳转和重定向
spring mvc底层其实就是一个servlet,因此在spring mvc中也存在转发和重定向的概念。对于转发的页面,可以是在WEB-INF目录下的页面;而重定向的页面,是不能在WEB-INF目录下的。因为重定向相当于用户再次发出一次请求,而用户是不能直接访问WEB-INF目录下的资源的。
2. 返回值为 Sting 的跳转和重定向
创建跳转的controller:
@Controller
public class ForwardController {
@RequestMapping("/forward")
public String test(){
return "forward:/WEB-INF/jsp/forward.jsp";
}
}
创建跳转的jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h2>hello forward</h2>
</body>
</html>
创建重定向的controller:
@Controller
public class RedirectController {
@RequestMapping("/redirect")
public String test(Model model){
//重定向的数据只能是基本数据类型
model.addAttribute("String","helle redirect");
return "redirect:/jsp/redirect.jsp";
}
}
创建重定向的jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<!-- 注意获取参数和以前不同 -->
${param.String}
</body>
</html>
3. 返回void的重定向和转发
转发:
request.getRequestDispatcher("/jsp/result.jsp").forward(request, response);
重定向:
response.sendRedirect(request.getContextPath()+"/jsp/result.jsp");