时间:2022-04-11 10:46:25 | 栏目:JAVA代码 | 点击:次
SpringMVC是目前主流的Web MVC框架之一。
本文所讲的部分内容跟SpringMVC的视图机制有关,SpringMVC的视图机制请参考楼主的另一篇博客:
RedirectView这个视图是跟重定向相关的,也是重定向问题的核心,我们来看看这个类的源码。
路径构造完毕之后使用reponse进行sendRedirect操作。
@Controller
@RequestMapping(value = “/redirect”)
public class TestRedirectController {
@RequestMapping("/test1")
public ModelAndView test1() {
view.setViewName("redirect:index");
return view;
}
@RequestMapping("/test2")
public ModelAndView test2() {
view.setViewName("redirect:login");
return view;
}
@RequestMapping("/test3")
public ModelAndView test3(ModelAndView view) {
view.setViewName("redirect:/index");
return view;
}
@RequestMapping("/test4")
public ModelAndView test4(ModelAndView view) {
view.setView(new RedirectView("/index", false));
return view;
}
@RequestMapping("/test5")
public ModelAndView test5(ModelAndView view) {
view.setView(new RedirectView("index", false));
return view;
}
@RequestMapping("/test6/{id}")
public ModelAndView test6(ModelAndView view, @PathVariable("id") int id) {
view.setViewName("redirect:/index{id}");
view.addObject(“test”, “test”);
return view;
}
@RequestMapping("/test7/{id}")
public ModelAndView test7(ModelAndView view, @PathVariable("id") int id) {
RedirectView redirectView = new RedirectView("/index{id}");
redirectView.setExpandUriTemplateVariables(false);
redirectView.setExposeModelAttributes(false);
view.setView(redirectView);
view.addObject("test", "test");
return view;
}
先看test1方法,返回值 “redirect:index” , 那么会使用重定向。
SpringMVC找视图名”redirect:index”的时候,本文使用的ViewResolver是FreeMarkerViewResolver。
FreeMarkerViewResolver解析视图名的话,最调用父类之一的UrlBasedViewResolver中的createView方法。
通过构造方法发现,这个RedirectView使用相对路径,兼容Http1.0,不暴露路径变量。
test1方法:
nice,验证了我们的想法。
test2方法同理:
test3方法:
test4方法:
test5方法:
test6方法:
test7方法:
简单了分析了RedirectView视图,并分析了该视图的渲染源码,并分析了重定向中的路径问题,参数问题,路径变量问题等常用的问题。
源码真是最好的文档,了解了视图机制之后,再回过头来看看RedirectView视图,So easy。
最后感觉RedirectView的相对路径属性怪怪的,不使用相对路径,”/” 开头的直接就是服务器根路径, 不带 “/” 开头的,又是相对路径, 有点蛋疼。