7.2.3-处理方法签名详细介绍
使用@RequestParam绑定请求参数值
@RequestParam有三个参数:
value 参数名
required 是否为必需的,默认为true,表示请求中必须包含此参数,如果不存在就抛出异常
defaultValue 默认参数名,极少情况使用该参数,也不推荐使用该参数
示例:
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.ui.ModelMap;
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(@RequestParam("user") String user,ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework! sasuke!!!!"+user);
return "hello";
}
}
在URL末尾加上user参数:http://localhost:8080/Spring_MVC/hello?user=naruto
结果为
如果URL中不加user参数,由于未设置required参数,默认为true,所以会抛出异常
在绑定参数的过程中Spring会自动完成参数类型转换,如下Controller
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.ui.ModelMap;
@Controller
@RequestMapping("/World")
public class WorldController {
@RequestMapping(method=RequestMethod.GET)
public String doController(@RequestParam("userID") int userID,ModelMap model){ //此处userID是int类型的
String world= "i have a dream and i make it beautiful"+userID*2;
model.addAttribute("world",world);
return "World";
}
}
访问URL:http://localhost:8080/Spring_MVC/World?userID=2
结果
使用@CookieValue绑定请求中的Cookie值
它和@RequestParam有三个相同的参数
Cookie中有什么值还不太了解
使用@RequestHeader绑定请求报文头中的值
同样于@RequestParam有三个相同的参数值
使用命令/表单对象绑定请求参数值
命令/表单对象不需要实现任何接口,仅是一个拥有若干属性的POJO。SpringMVC会按请求参数名和命令/表单对象属性名进行匹配,自动会该对象填充属性值。
示例:
UserController.java
@RequestMapping("/User")
public class UserController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(User user,ModelMap model) { //这里注意,user并需要用标注,Spring会自动填充
String message="Hello Spring MVC Framework! "+user.getUserID()+" "+user.getUserName();
model.addAttribute("message", message);
return "hello";
}
}
User.java
user应该是个POJO类,所以每个属性都要有setter和getter方法
public class User {
private int userID;
private String userName;
public int getUserID() {
return userID;
}
public void setUserID(int userID) {
this.userID = userID;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
URL:http://localhost:8080/Spring_MVC/User?userID=1&userName=MrRaindrop
结果:
使用ServletAPI对象作为入参
使用方法如下:
同时使用HttpServletRequest和HttpServletResponse作为入参
@RequestMapping(value="/servlet1")
public void handlerServlet1(HttpServletRequest request,HttpServletResponse responsee){
String userName=WebUtils.findParameterValue(request,"userName");
response.addCookie(new Cookie("userName",userName));
}
也可以仅使用HttpServletRequest或者HttpServeltResponse作为入参;使用HttpSession作为入参;即使用HttpServeltRequest又使用基本类型的入参