之前一直对forward和redirect有点疑问,现在练习一下加深点记忆,理解理解,forward是一次请求,在一个request范围内,而redirect是二次请求
实例:
@Controller public class ForwardController { @RequestMapping("/makeDataForward2.html") public String makeDataResponse(Model model,HttpServletRequest request) { //在model和request中保存属性 model.addAttribute("modelData", "model data"); //得到完整路径 System.out.println("request.getRequestURL()"+request.getRequestURL()); //得到除去ip地址的路径 System.out.println("request.getRequestURI()"+request.getRequestURI()); request.setAttribute("requestData", "reuqest data"); //正常响应 return "success"; } //请求转发 @RequestMapping("/makeDataForward.html") public String makeDateForward(Model model,HttpServletRequest request) { //在model和request中保存属性 model.addAttribute("modelData", "model data"); request.setAttribute("requestData", "reuqest data"); //请求转发过去后值也传递过去了 return "forward:toSuccessPage.html"; } @RequestMapping("/makeDataRedirect.html") public String makeDataRedirect(Model model, HttpServletRequest request) { //在model和request中保存属性 model.addAttribute("modelData", "model data"); request.setAttribute("requestData", "reuqest data"); //重定向 return "redirect:toSuccessPage2.html"; } @RequestMapping("/toSuccessPage.html") public String toSuccessPage() { return "success"; } @RequestMapping("/toSuccessPage2.html") public String toSuccessPage2(@ModelAttribute("modelData") String modelData) { //@ModelAttribute("modelData") //可以获取重定向传递过来的页面的model值,这样在前端就可以获取了 //如果没有这个参数,页面就获取不到值 return "success"; } @RequestMapping("/toSuccessPage3.html") //RedirectAttributes可以向url传递参数,包括中文 public String toSuccessPage3(RedirectAttributes redirectAttributes) { redirectAttributes.addAttribute("param", "王"); return "redirect:/WEB-INF/jsp/success.jsp?method=号"; } }
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> model中数据:${modelData} <br/> <br/> request中数据:${requestData } <br/> </body> </html>
原文地址:https://www.cnblogs.com/ya-qiang/p/9393147.html
时间: 2024-10-19 05:19:17