指定请求路径
- value: 指定接收的路径
- method: 接收什么请求(get repost…)
- params: 对参数的限制
- headers: 浏览器的请求头
@RequestMapping(value={"/add","/add2","/add3"},
method = RequestMethod.GET, // 接收的请求方法
params = {"!name","address=beijing","age!=22"}, // 参数不能含有name,必须有address=beijing且age!=22
headers = {"User-Agent=Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)"})
public String testA(Model model, User user){
return "success";
}
作用
- 设置默认值
- 定义映射规则
参数
- name: 浏览器中的key
- defaultValue: 默认值
- required: 参数是否必须传
//http://localhost:8080/springMvc_01/testB?i=&name
@RequestMapping(value = "testB")
public String testB(Model model, @RequestParam(defaultValue = "0") int i, @RequestParam(required = false, defaultValue = "没有值", name = "name") String userName){
model.addAttribute("message", i + userName);
return "success";
}
获取请求头信息
@RequestMapping("testC")
public String test(Model model, @RequestHeader(name = "cache-control") String cacheControl){
// 向前端传回数据, request域
model.addAttribute("message", "请求被成功响应");
System.out.println(cacheControl);
//最终到视图解析器中加上前缀和后缀
return "success";
}
获取cookie
@RequestMapping("/add03")
public String addPerson03(Model model,@CookieValue(name = "JSESSIONID") String cookie){
System.out.println("cookie="+cookie);
model.addAttribute("message","访问成功");
return "success";
}
返回 jackson对象,需要导入依赖 jackson-databind
@RequestMapping("/getPersonById")
@ResponseBody
public User getPersonById(){
User user = new User();
user.setName("wy");
user.setAge(12);
return user;
}
接收前端传过来的json对象
注意:
- 前端必须传来的是json格式的字符串
- 必须发送post请求
@RequestMapping("/add04")
@ResponseBody
public String addPerson04(@RequestBody User user){
System.out.println(user);
return "success";
}
@ModelAttribute(name = "msg")
public String modelA(){
System.out.println("访问了modelaaa方法");
return "aaa";
}
加在参数上,可以接收地址栏上的参数
@RequestMapping("/add05")
public String addPerson05(Model model,@ModelAttribute("aaa") String data){
// data为地址栏中属性为aaa的值
System.out.println(data);
model.addAttribute("message","访问成功");
return "success";
}
取出请求中占位符对应的参数
@RequestMapping("/deletePersonById/{id}/{page}")
public String deletePersonById(Model model,@PathVariable("id") int id,@PathVariable("page") String page){
System.out.println("id="+id);
model.addAttribute("message","删除成功");
return page;
}
加在类上,指定哪些属性名,或者哪些属性值会被加入到session中
value: 属性名称,以name, age为key 的会被加入到session中
type:哪些数据类型的属性值会被加入到session中
@SessionAttributes(value = {"name","age"},types = {Date.class})