1. 复杂参数
- Map
- Model
- ServletResponse
2. 转发与重定向
- 转发
- 由服务端完成;
- 地址栏不发生变化,显示的转发前的地址(针对浏览器);
- 只发生一次请求;
- 请求中携带的参数不会丢失;
- 重定向
- 服务端告诉浏览器或客户端重定向的地址,由客户端再次发起请求;
- 地址栏显示重新向后的地址(针对浏览器);
- 发生了两次请求;
- 第一次请求的参数不会带到重定向后的请求中;
2.2 方式一:forward 关键字
map,model 和 request 里的数据会被放入 request 域,相当于request.setAttribute()
@Controller
@RequestMapping("/api")
public class ForwardController {
@GetMapping("/forward")
public String forward(Map<String, Object> map, Model model,
HttpServletRequest request, HttpServletResponse response) throws Exception {
map.put("mapInfo", "hello");
model.addAttribute("modelInfo", "demo");
request.setAttribute("message", "this is test");
Cookie cookie = new Cookie("kie", "cookie001");
response.addCookie(cookie);
return "forward:/api/show";
}
@GetMapping("/show")
public Map<String, Object> show(@RequestAttribute(value = "name", required = false) String name,
HttpServletRequest request) {
Map<String, Object> map = new HashMap<>();
map.put("parameterMap", request.getParameterMap());
map.put("mapInfo", request.getAttribute("mapInfo"));
map.put("modelInfo", request.getAttribute("modelInfo"));
map.put("message", request.getAttribute("message"));
return map;
}
}
请求地址 http://localhost:8080/api/forward
2.3 方式二:Servlet API
请求转发是通过请求分配器( RequestDispatcher ) 直接将请求转发到了另一个 url 上。此时请求依旧在后端,还没有返回响应给前端
@RestController
public class ServletController {
@GetMapping("/params")
public void params(Map<String, Object> map, Model model,
HttpServletRequest request, HttpServletResponse response) throws Exception {
// ...
request.getRequestDispatcher("/show").forward(request,response);
}
}
经测试,转发后只能取到 HttpServletRequest 设置的值
3. 重定向
3.1 方式一:redirect 关键字
@Controller
@RequestMapping("/api")
public class ForwardController {
@GetMapping("/redirect")
public String redirect(HttpServletRequest request) throws Exception {
return "redirect:/api/play";
}
@GetMapping("/play")
public Map<String, Object> play(HttpServletRequest request) {
Map<String, Object> map = new HashMap<>();
return map;
}
}
请求地址 http://localhost:8080/api/redirect
3.2 方式二:Servlet API
@RestController
public class ServletController {
@GetMapping("/redirect")
public void redirect(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.getRequestDispatcher("/api/play").forward(request, response);
}
}
请求地址 http://localhost:8080/redirect
3. Map, Model 类型的参数
ModelAndViewContainer
网友评论