request.getRequestDispatcher(url).forward(request, response)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
*
* 获取高亮实时流程图
* */
@RequestMapping(value = "/getHighlightImg/{eventcode}", method = RequestMethod.GET)
public void getHighlightImg(@PathVariable String eventcode, HttpServletRequest request, HttpServletResponse response){
try {
request.getRequestDispatcher("/event/getHighlightImg/" + eventcode).forward(request, response);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

response.sendRedirect

不带参数

1
2
3
response.sendRedirect("/index");

response.sendRedirect("http://www.baidu.com");

带参数

1
2
//menuname : 系统管理,中文乱码,需要编码
response.sendRedirect(request.getContextPath() + "/initialMain.jspx?menuname=" + URLEncoder.encode(menuname, "UTF-8"));

ViewResolver 直接跳转

不带参数

1
2
3
4
@RequestMapping(value="/testredirect",method = { RequestMethod.POST, RequestMethod.GET })  
public String testredirect(HttpServletResponse response){
return "redirect:/index";
}

带参数

1
2
3
4
5
6
@RequestMapping("/testredirect")
public String testredirect(Model model, RedirectAttributes attr) {
attr.addAttribute("p1", "value1"); //使用 RedirectAttributes 的 addAttribute 方法传递参数会跟随在 URL 后面
attr.addFlashAttribute("p2", "value2"); //使用 addFlashAttribute 不会跟随在 URL 后面,会把该参数值暂时保存于 session,待重定向 url 获取该参数后从 session 中移除,这里的 redirect 必须是方法映射路径,jsp 无效
return "redirect:/user/users";
}

ModelAndView 重定向

不带参数

1
2
3
4
5
@RequestMapping(value="/restredirect",method = { RequestMethod.POST, RequestMethod.GET })  
public ModelAndView restredirect(String userName){
ModelAndView model = new ModelAndView("redirect:/main/index");
return model;
}

带参数

1
2
3
4
5
6
@RequestMapping(value="/toredirect",method = { RequestMethod.POST, RequestMethod.GET })  
public ModelAndView toredirect(String userName){
ModelAndView model = new ModelAndView("/main/index");
model.addObject("userName", userName); //把userName参数带入到controller的RedirectAttributes
return model;
}