一、Controller接收网页参数
Controller对参数的接收是指 通过URL或表单获取到网页的请求参数。主要有如下几种方式:
1、通过Bean接收请求参数 2、通过处理方法的入参接收请求参数 3、通过HttpServletRequest接收请求参数 4、@PathVariable 路径参数 5、@RequestParam :URL 问好后面的参数。 6、@ModelAttribute
@RequestMapping("login")
public String login(String username,String password){
return "";
}
需要和Form表单中的name名字相同
<form class="form-signin" th:action="@{/login}">
<input type="email" name="username" class="form-control" placeholder="Email address" required autofocus>
<input type="password" name="password" class="form-control" placeholder="Password" required>
</form>
@Controller
@ResponseBody
public class LoginController {
@RequestMapping("login")
public String login(String username,String password){
if(username.equals("123@126.com"))
return "No No";
return "oK";
}
@RequestMapping("login2")
public String login2(HttpServletRequest httpServletRequest){
String username = httpServletRequest.getParameter("username");
String password = httpServletRequest.getParameter("password");
return "OK";
}
@RequestMapping("/login3/{username}/{password}")
public String login3(@PathVariable String username,@PathVariable String password){
return "OK";
}
// http://xxxx/login4?username=xx&password=xx
@RequestMapping("login4")
public String login4(@RequestParam(value="username") String username,
@RequestParam(value="password") String password){
return "OK";
}
}
二、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 传递的概念了。在客户浏览器的地址栏中显示的是其重定向的路径,客户可以观察到地址的变化。重定向行为是浏览器做了至少两次的访问请求。
@Controller
@RequestMapping("/index")
public class IndexController {
@RequestMapping("/login")
public String login() {
//转发到一个请求方法(同一个控制器类可以省略/index/)
return "forward:/index/isLogin";
}
@RequestMapping("/isLogin")
public String isLogin() {
//重定向到一个请求方法
return "redirect:/index/isRegister";
}
@RequestMapping("/isRegister")
public String isRegister() {
//转发到一个视图
return "register";
}
}