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表达式就能获得到。



posted @ 2018-08-27 15:35  星朝  阅读(6314)  评论(0编辑  收藏  举报