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表達式就能獲得到。