視圖解析器
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
- forward:請求轉發(去前後綴)
- redirect:重定向.
基於返回mv對象
mv.setViewName("str");
- str=”forward : 路徑” 請求轉發到一個jsp中
- str=”forward : controller的映射” 請求轉發到一個controller方法中
- str=”redirect: 路徑” 請求轉發到一個非WEB-INF的jsp
常用:
- str=”redirect : controller的映射” 重定向到一個controller方法中
- str=”XXX” 根據前後綴,請求轉發到 前綴/XXX.後綴
1:請求轉發到jsp(默認的)
@RequestMapping("/method1")
public ModelAndView method1(HttpServletRequest req,ModelAndView mv) throws Exception{
//請求轉發到/WEB-INF/view/main.jsp
mv.setViewName("main"); //默認加入前後綴
return mv;
}
//訪問非視圖解析器的視圖時,用forward
@RequestMapping("/method3")
public ModelAndView method3(HttpServletRequest req,ModelAndView mv) throws Exception{
mv.setViewName("forward:WEB-INF/view/main.jsp"); //不添加前後綴
return mv;
}
2:請求轉發到controller(必須用forward)
@RequestMapping("/method4")
public ModelAndView method4(HttpServletRequest req,ModelAndView mv) throws Exception{
mv.setViewName("forward:method1");
return mv;
}
3:重定向到controller
@RequestMapping("/method5")
public ModelAndView method5(HttpServletRequest req,ModelAndView mv) throws Exception{
mv.setViewName("redirect:method3");
return mv;
}
4:重定向到jsp
@RequestMapping("/method5")
public ModelAndView method5(HttpServletRequest req,ModelAndView mv) throws Exception{
mv.setViewName("redirect:index.jsp");
return mv;
}
基於返回字符串
由於返回是字符串,所以mv的設置將沒有作用,要用req來傳送值
- str=”forward : 路徑” 請求轉發到一個jsp中
- str=”forward : controller的映射” 請求轉發到一個controller方法中
- str=”redirect: 路徑” 請求轉發到一個非WEB-INF的jsp
常用:
- str=”redirect : controller的映射” 重定向到一個controller方法中
- str=”XXX” 根據前後綴,請求轉發到 前綴/XXX.後綴
@RequestMapping("method1")
public String method1() throws Exception{
return "redirect:method2";
}
@RequestMapping("method2")
public String method2() throws Exception{
return "forward:WEB-INF/view/main.jsp";
}
轉自:https://blog.csdn.net/weixin_40315550/article/details/79141722