SSM转发与重定向(考虑数据共享)
1.mvc可以使用servlet API来实现重定向和转发(好处可以操作request带来的数据实现数据共享)
@RequestMapping("/ServletAPI3")
public void test3(HttpServletRequest req, HttpServletResponse rep) throws IOException, ServletException {
req.setAttribute("msg","YEAH");
req.getRequestDispatcher("/target").forward(req,rep);
return;
}
@RequestMapping("/target")
public String test4(Model model) {
return "hello";
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>controller</title>
</head>
<body>
${msg}
</body>
</html>
结果:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sbh0QYzg-1645347122215)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\image-20220220165017612.png)]
2.在不使用API的情况下,其实就是路径问题,故要注意视图解析器是否应该存在,如果有了视图解析器就不能直接写controller请求的路径。(不可以操作request带来的数据实现数据共享)
1.重定向
a.redirect:/t1
解析器无影响
b.redirect:t1.do
解析器无影响
2.转发
a."XXXX"
解析器有影响
b.forward:/index.jsp
解析器有影响
@RequestMapping("/t1")
public String control(Model model){
model.addAttribute("msg","AnnotationController");
return "hello";
}
@RequestMapping("/t2")
public String selectController(Model model){
List<Books> books = booksMapper.queryAllBook();
model.addAttribute("msg",books);
return "redirect:/t1";
}
@RequestMapping("/t3")
public String selectController1(Model model){
List<Books> books = booksMapper.queryAllBook();
model.addAttribute("msg",books);
// return "t1"; 需要注释掉视图解析器
return "forward:/t1";
}
@RequestMapping("/t4")
public String selectController2(Model model){
List<Books> books = booksMapper.queryAllBook();
model.addAttribute("msg",books);
return "redirect:t1.do";
}
@RequestMapping("/search")
public String searchController(Model model){
List<Books> books = booksMapper.queryAllBook();
model.addAttribute("msg",books);
return "redirect:/t1";
}
写在最后:
Session实现数据共享也可以~~