7.重定向与转发
7.1SpringMVC结果跳转方式
页面 : 视图解析器前缀 + viewName + 视图解析器后缀
例如 : /WEB-INF/jsp/ + hello + .jsp
7.2 重定向与转发
1.使用request与response
@Controller
public class TestController{
//模板URL ,会直接通过 / 的形式绑定a与b
@GetMapping("test/{a}/{b}")
public String test(HttpServletRequest request,HttpServletResponse response,@PathVariable int a,@PathVariable String b, Model model) throws IOException {
//封装数据
String res = a+b;
model.addAttribute("msg",res);
response.sendRedirect("/jsp/hello.jsp"); //通过response转发
return "hello";
}
}
2.通过视图解析器
@Controller
public class TestController{
//模板URL ,会直接通过 / 的形式绑定a与b
@GetMapping("test/{a}/{b}")
public String test(@PathVariable int a,@PathVariable String b, Model model) {
//封装数据
String res = a+b;
model.addAttribute("msg",res);
return "hello"; //直接通过视图解析器转发
}
}
3.SpringMVC方式,无需视图解析器(把配置文件中的视图解析器注释掉)
-
使用全限定名(默认转发)
@Controller public class TestController{ //模板URL ,会直接通过 / 的形式绑定a与b @GetMapping("test/{a}/{b}") public String test(@PathVariable int a,@PathVariable String b, Model model) throws IOException { //封装数据 String res = a+b; model.addAttribute("msg",res); return "/WEB-INF/jsp/hello.jsp"; //直接返回全限定名,DispatcherServlet仍然可以找到资源 } } //全限定名默认是转发方式
-
使用forward、redirect 显示表明
@Controller public class TestController{ //模板URL ,会直接通过 / 的形式绑定a与b @GetMapping("test") public String test(Model model) throws IOException { //封装数据 model.addAttribute("msg","hello"); return "redirect:/index.jsp"; //redirect:重定向 } }
4.使用视图解析器时显示表明转发或重定向
默认转发
@Controller
public class TestController{
//模板URL ,会直接通过 / 的形式绑定a与b
@GetMapping("test")
public String test(Model model) throws IOException {
//封装数据
model.addAttribute("msg","hello");
return "redirect:index.jsp"; //指明重定向
}
}
注意
只要使用了forward或redirect ,就不会走视图解析器 ,因此写中间的名字是不会被找到的,只能写全限定名