一、Controller接收网页参数

Controller对参数的接收是指 通过URL或表单获取到网页的请求参数。主要有如下几种方式:

1、通过Bean接收请求参数 2、通过处理方法的入参接收请求参数 3、通过HttpServletRequest接收请求参数 4、@PathVariable 路径参数 5、@RequestParam :URL 问好后面的参数。 6、@ModelAttribute

  1. @RequestMapping("login")
  2. public String login(String username,String password){
  3. return "";
  4. }

需要和Form表单中的name名字相同

  1. <form class="form-signin" th:action="@{/login}">
  2. <input type="email" name="username" class="form-control" placeholder="Email address" required autofocus>
  3. <input type="password" name="password" class="form-control" placeholder="Password" required>
  4. </form>
  1. @Controller
  2. @ResponseBody
  3. public class LoginController {
  4. @RequestMapping("login")
  5. public String login(String username,String password){
  6. if(username.equals("123@126.com"))
  7. return "No No";
  8. return "oK";
  9. }
  10. @RequestMapping("login2")
  11. public String login2(HttpServletRequest httpServletRequest){
  12. String username = httpServletRequest.getParameter("username");
  13. String password = httpServletRequest.getParameter("password");
  14. return "OK";
  15. }
  16. @RequestMapping("/login3/{username}/{password}")
  17. public String login3(@PathVariable String username,@PathVariable String password){
  18. return "OK";
  19. }
  20. // http://xxxx/login4?username=xx&password=xx
  21. @RequestMapping("login4")
  22. public String login4(@RequestParam(value="username") String username,
  23. @RequestParam(value="password") String password){
  24. return "OK";
  25. }
  26. }

二、Controller返回参数

一般可以返回如下类型的参数,常用的String(逻辑视图名称):

  • ModelAndView
  • Model
  • 包含模型属性的 Map
  • View
  • 代表逻辑视图名的 String
  • void
  • 其它任意Java类型

三、重定向与转发

转发是服务器行为,重定向是客户端行为。

1、转发过程 - forward

客户浏览器发送 http 请求,Web 服务器接受此请求,调用内部的一个方法在容器内部完成请求处理和转发动作,将目标资源发送给客户;在这里转发的路径必须是同一个 Web 容器下的 URL,其不能转向到其他的 Web 路径上,中间传递的是自己的容器内的 request。

2、重定向 - redirect

客户浏览器发送 http 请求,Web 服务器接受后发送 302 状态码响应及对应新的 location 给客户浏览器,客户浏览器发现是 302 响应,则自动再发送一个新的 http 请求,请求 URL 是新的 location 地址,服务器根据此请求寻找资源并发送给客户。

在这里 location 可以重定向到任意 URL,既然是浏览器重新发出了请求,那么就没有什么 request 传递的概念了。在客户浏览器的地址栏中显示的是其重定向的路径,客户可以观察到地址的变化。重定向行为是浏览器做了至少两次的访问请求

  1. @Controller
  2. @RequestMapping("/index")
  3. public class IndexController {
  4. @RequestMapping("/login")
  5. public String login() {
  6. //转发到一个请求方法(同一个控制器类可以省略/index/)
  7. return "forward:/index/isLogin";
  8. }
  9. @RequestMapping("/isLogin")
  10. public String isLogin() {
  11. //重定向到一个请求方法
  12. return "redirect:/index/isRegister";
  13. }
  14. @RequestMapping("/isRegister")
  15. public String isRegister() {
  16. //转发到一个视图
  17. return "register";
  18. }
  19. }

参考

Spring MVC重定向和转发
SpringMVC 参数传递和接收的几种方式