SpringMVC從Controller跳轉到另一個Controller


1、springmvc框架中,請求道了一個controller,那么瀏覽器地址欄會顯示這個controller的請求路徑,然后頁面會跳轉到controller指定的jsp視圖。

2、后台從一個controller跳轉到另外一個controller(不帶參數的重定向):

方式一:使用ModelAndView
    return new ModelAndView("redirect:/index");


   
   
  
  
          
  1. @RequestMapping(value = "/loginSubmit")
  2. public ModelAndView loginSubmit(String loginName,String passwd,HttpServletRequest request,Model model) {
  3. try {
  4. User user = loginService.loginSubmit(loginName,passwd);
  5. if (user == null) {
  6. return new ModelAndView( "login");
  7. } else {
  8. request.getSession().setAttribute(Constants.SESSION_USER, user);
  9. //request.setAttribute("user", user);
  10. model.addAttribute( "user", user);
  11. //response.sendRedirect(request.getContextPath()+"/login/login");
  12. <span style= "white-space:pre"> </span> //return new ModelAndView("index");
  13. return new ModelAndView( "redirect:/index");
  14. }
  15. } catch (Exception e) {
  16. logger.error(e.getMessage());
  17. return new ModelAndView( "error/error");
  18. }
  19. }

   
   
  
  
          
  1. @RequestMapping(value = "/index")
  2. public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
  3. logger.info( "首頁登陸跳轉。。。");
  4. return new ModelAndView( "index");
  5. }
這樣經過了第二個controller,瀏覽器地址欄變成了http://ip:8080/iis/index ,頁面跳轉到了index.jsp


方式二:返回String
          return "redirect:/ toList "; 
其它方式:其它方式還有很多,這里不再做介紹了,比如說response等等。


3、帶參數的跳轉:

方式一:自己手動拼接url
          new ModelAndView("redirect:/toList?param1="+value1+"&m2="+value2);
          這樣有個弊端,就是傳中文可能會有亂碼問題。


方式二:用RedirectAttributes,這個是發現的一個比較好用的一個類,這里用它的addAttribute方法,這個實際上重定向過去以后你看url,是它自動給你拼了你的url。
          使用方法:
           attr.addAttribute("param", value);
          return "redirect:/namespace/toController";
          這樣在toController這個方法中就可以通過獲得參數的方式獲得這個參數,再傳遞到頁面。過去的url還是和方式一一樣的。



4、帶參數不拼接url頁面也能拿到值(重點是這個)


   
   
  
  
          
  1. @RequestMapping( "/save")
  2. public String save(@ModelAttribute("form") Bean form,RedirectAttributes attr)
  3. throws Exception {
  4. String code = service.save(form);
  5. if(code.equals( "000")){
  6. attr.addFlashAttribute( "name", form.getName());
  7. attr.addFlashAttribute( "success", "添加成功!");
  8. return "redirect:/index";
  9. } else{
  10. attr.addAttribute( "projectName", form.getProjectName());
  11. attr.addAttribute( "enviroment", form.getEnviroment());
  12. attr.addFlashAttribute( "msg", "添加出錯!錯誤碼為:"+rsp.getCode().getCode()+ ",錯誤為:"+rsp.getCode().getName());
  13. return "redirect:/maintenance/toAddConfigCenter";
  14. }
  15. }
  16. @RequestMapping( "/index")
  17. public String save(@ModelAttribute("form") Bean form,RedirectAttributes attr)
  18. throws Exception {
  19. return "redirect:/main/list";
  20. }

頁面取值不用我說了吧,直接用el表達式就能獲得到。




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM