@RequestMapping对应的@RequestParam,@RequestHeader与@CookieValue
程序员文章站
2022-06-16 08:55:45
...
一个请求包含了一个请求的网址+请求头+请求体。可以利用@RequestMapping注解解析请求网址如何解析到请求头和请求体呢?
@RequestParam注解用于解析请求参数
<form action="helloworld" method="post">
<input type="text" name="username">
<input type="password" name ="password">
<input type="submit" value="POST">
</form>
@Controller
public class Distributor {
@RequestMapping(value = "/helloworld", method = RequestMethod.POST)
public String distribute2Success2(@RequestParam(value="username") String username, @RequestParam(value="password") String password) {
System.out.println(username);
System.out.println(password);
return "success";
}
}
这样就可以解析出请求参数;但是如果请求参数为空就会报错
有三个参数,value为参数名,required为是否是必须的参数,默认为true
defaultValue默认值
@RequestParam(value="username", required=false, defaultValue = "xiaoming") String username
@RequestHeader用于解析请求头的数据
@Controller
public class Distributor {
@RequestMapping(value = "/helloworld", method = RequestMethod.POST)
public String distribute2Success2(@RequestHeader(value="Host",required=false,defaultValue="hahaha") String host) {
System.out.println(host);
return "success";
}
}
程序执行打印localhost:8080
@CookieValue 注解解析Cookie对象的值
这里有个JSESSIONID的值,我们解析该值
@Controller
public class Distributor {
@RequestMapping(value = "/helloworld", method = RequestMethod.POST)
public String distribute2Success2(@CookieValue(value="JSESSIONID",required=false,defaultValue="hahaha") String sessionId) {
System.out.println(sessionId);
return "success";
}
}