Springmvc中的return modelAndView和return "xxxx"的區別
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"><value>org.springframework.web.servlet.view.JstlView</value></property>
<property name="prefix"><value>/WEB-INF/jsp/</value ></property>
<property name="suffix"><value>.jsp</value></property>
</bean>
1. return modelAndView例子
@RequestMapping(value="/login", method=RequestMethod.GET)
public ModelAndView loginPage(HttpSession session) {
ModelAndView modelAndView = new ModelAndView("user/login");
return modelAndView; //訪問 WEB-INF/jsp/user/login.jsp檔案
}
2. return “redirect:/index.jsp”例子
@RequestMapping(value="/", method=RequestMethod.GET)
public String index(HttpSession session){
session.setAttribute("message", null);
return "redirect:/index.jsp"; 訪問根目錄下index.jsp檔案。redirect為直接url 訪問。
}
如果 return “redirect:”+”a”; //則返回當前控制器方法對應a.jsp頁面
如果 return “redirect:/nademo/user/”+”user”; //則會返回不同控制器方法對應user.jsp頁面. 注意:nademo/user為另一個控制器元件名,且前面必須加正斜槓
3. spring mvc 請求轉發和重定向
3.1 請求轉發
(1)返回ModelAndView :
@RequestMapping(value="/model",method=RequestMethod.GET)
public ModelAndView testForward(ModelAndView model,@RequestParam(value="id",defaultValue="1",required=false)Long id){
User u = getBaseService().get(User.class, id);
model.addObject("user", u);
//model.setViewName("forward:index.jsp");
return model;
}
如上程式碼,如果返回modelAndView 則可以如標註,新增forward即可,若想重定向,可把forward替換成redirect便可達到目的。
(2)返回字串
@RequestMapping(value="/forward",method=RequestMethod.GET)
public String testForward(){
return "forward:/index.action";
}
3.2 請求重定向
對於請求轉發可以分為:1.帶引數 2.不帶引數
(1)帶引數
@RequestMapping(value="/redirect",method=RequestMethod.GET)
public String testRedirect(RedirectAttributes attr){
attr.addAttribute("a", "a");
attr.addFlashAttribute("b", "b");
return "redirect:/index.action";
}
帶引數可使用RedirectAttributes引數進行傳遞:
注意:
1. 使用RedirectAttributes的addAttribute方法傳遞引數會跟隨在URL後面 ,如上程式碼即為http:/index.action?a=a
2. 使用addFlashAttribute不會跟隨在URL後面,會把該引數值暫時保存於session,待重定向url獲取該引數後從session中移除,這裡的redirect必須是方法對映路徑,jsp無效。你會發現redirect後的jsp頁面中b只會出現一次,重新整理後b再也不會出現了,這驗證了上面說的,b被訪問後就會從session中移除。對於重複提交可以使用此來完成。
另外,如果使用了RedirectAttributes作為引數,但是沒有進行redirect呢?這種情況下不會將RedirectAttributes引數傳遞過去,預設傳forward對應的model,官方的建議是:
p:ignoreDefaultModelOnRedirect="true" />
設定下RequestMappingHandlerAdapter 的ignoreDefaultModelOnRedirect屬性,這樣可以提高效率,避免不必要的檢索。
(2)無引數
@RequestMapping(value="/redirect",method=RequestMethod.GET)
public String testRedirect(){
return "redirect:/index.action";
}