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