1. 需求背景
需求:spring MVC框架controller间跳转,需重定向。有几种情况:不带参数跳转,带参数拼接url形式跳转,带参数不拼接参数跳转,页面也能显示。
2. 解决办法
需求有了肯定是解决办法了,一一解决,说明下spring的跳转方式很多很多,我这里只是说一些自我认为好用的,常用的,spring分装的一些类和方法。
(1)我在后台一个controller跳转到另一个controller,同时传递参数
方式一:使用ModelAndView
@RequestMapping("/list")
public ModelAndView list(Model model, @RequestParam Map<String, Object> paramMap,
@RequestParam Long adGroupId,
@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "5") int pageSize){
Map<String, Object> context = getRootMap();
StudentModel model = new StudentModel();
context.put("model", model);
return ModelAndView("stu/studentList", context);
}
ModelAndView有7个构造方法,在这里使用ModelAndView(viewName, model) 这个方法:
ModelAndView(viewName, model):
第一个参数:指定页面要跳转的view视图路径
第二个参数:指定了要项前台传递的参数,在前台可以这样取值 ${xxxx!}
也可以自己手动拼接,类似于redirect
方式二:返回String
@RequestMapping("/list")
public String list(Model model, @RequestParam Map<String, Object> paramMap,
@RequestParam Long adGroupId,
@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "5") int pageSize){
return "redirect:/toList?page="+page+"&pageSize="+pageSize;
}
注意:这种方式在传输汉字时,会出现接收方取值为空或乱码的问题,解决办法为:
java.net.URLEncoder.encode(String,"UTF-8");
String searchValue = "";
try{
searchValue =java.net.URLEncoder.encode(String.valueOf(paramMap.get("searchValue")),"UTF-8");
} catch (UnsupportedEncodingException e1){
// TODO Auto-generated catch block
e1.printStackTrace();
}
方式三:使用RedirectAttributes(要求:spring版本3.1及以上)
RedirectAttributes是Spring mvc 3.1版本之后出来的一个功能,专门用于重定向之后还能带参数跳转的,他有两种带参的方式:
第一种:
attr.addAttribute("param", value);
这种方式就相当于重定向之后,在url后面拼接参数,这样在重定向之后的页面或者控制器再去获取url后面的参数就可以了,但这个方式因为是在url后面添加参数的方式,所以暴露了参数,有风险,例:
@RequestMapping("/list")
public String list(Model model, @RequestParam Map<String, Object> paramMap,
@RequestParam Long adGroupId,
@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "5") int pageSize,
RedirectAttributes redirectAttributes){
redirectAttributes.addAttribute("page",page,);
redirectAttributes.addAttribute("pageSize",pageSize,);
return "redirect:/toLis";
}
第二种:
attr.addFlashAttribute("param", value);
这种方式也能达到重新向带参,而且能隐藏参数,其原理就是放到session中,session在跳到页面后马上移除对象。所以你刷新一下后这个值就会丢掉
@RequestMapping("/list")
public String list(Model model, @RequestParam Map<String, Object> paramMap,
@RequestParam Long adGroupId,
@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "5") int pageSize,
RedirectAttributes redirectAttributes){
redirectAttributes.addFlashAttribute("page", page);
redirectAttributes.addFlashAttribute("pageSize", pageSize);
return "redirect:/toLis";
}
;”进行字符格式转译
如果在使用RedirectAttributes时报以下错误:
java.lang.IllegalStateException: Argument [RedirectAttributes] is of type Model
解决方法:在spring-mvc.xml文件里加上这个标签:<mvc:annotation-driven />