SpringMVC从Controller跳转到另一个Controller

1、springmvc框架中,请求道了一个controller,那么浏览器地址栏会显示这个controller的请求路径,然后页面会跳转到controller指定的jsp视图。

2、后台从一个controller跳转到另外一个controller(不带参数的重定向):

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

	@RequestMapping(value = "/loginSubmit")
	public ModelAndView loginSubmit(String loginName,String passwd,HttpServletRequest request,Model model) {
		try {
			User user = loginService.loginSubmit(loginName,passwd);
			if (user == null) {
				return new ModelAndView("login");
			} else {
				request.getSession().setAttribute(Constants.SESSION_USER, user);
				//request.setAttribute("user", user);
				model.addAttribute("user", user);
				//response.sendRedirect(request.getContextPath()+"/login/login");
<span style="white-space:pre">				</span>//return new ModelAndView("index");
				return new ModelAndView("redirect:/index");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			return  new ModelAndView("error/error");
		}
	}
	@RequestMapping(value = "/index")
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
		logger.info("首页登陆跳转。。。");
		return new ModelAndView("index");
	}
这样经过了第二个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页面也能拿到值(重点是这个)

 @RequestMapping("/save")
  public String save(@ModelAttribute("form") Bean form,RedirectAttributes attr)
           throws Exception {

    String code =  service.save(form);
    if(code.equals("000")){
      attr.addFlashAttribute("name", form.getName());  
      attr.addFlashAttribute("success", "添加成功!");
      return "redirect:/index";
    }else{
      attr.addAttribute("projectName", form.getProjectName());  
      attr.addAttribute("enviroment", form.getEnviroment());  
      attr.addFlashAttribute("msg", "添加出错!错误码为:"+rsp.getCode().getCode()+",错误为:"+rsp.getCode().getName());
      return "redirect:/maintenance/toAddConfigCenter";
    }
  }

@RequestMapping("/index")
    
  public String save(@ModelAttribute("form") Bean form,RedirectAttributes attr)
           throws Exception {
      return "redirect:/main/list";
  }

页面取值不用我说了吧,直接用el表达式就能获得到。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赶路人儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值