文章目录
1. 直接把请求参数写在方法的形参中 2. 封装一个bean直接来接收 3. 原生的HttpServletRequest接收 4. @PathVariable获取rest风格路径参数 5. @RequestParam绑定请求参数到方法形参 6. @RequestBody绑定请求参数到方法形参 7. @RequestHeader 8. @CookieValue
1. 直接把请求参数写在方法的形参中
@RequestMapping ( "/fun1" )
public Book fun1 ( String name, Long id) {
log. info ( "{} {}" , id, name) ;
Book book= new Book ( id, name) ;
return book;
}
2. 封装一个bean直接来接收
@RequestMapping ( "/fun2" )
public Book fun2 ( Book book) {
log. info ( "book={}" , book) ;
return book;
}
3. 原生的HttpServletRequest接收
同时适用get、post方法 是整个请求,可以获取到所有的数据 可以和其他的注解配合适用 HttpServletRequest、HttpServletResponse都是内置对象,可以使用
@RequestMapping ( "/fun3" )
public Book fun3 ( HttpServletRequest request) {
log. info ( "{} {}" , request. getParameter ( "id" ) , request. getParameter ( "name" ) ) ;
return new Book ( Long . parseLong ( request. getParameter ( "id" ) ) , request. getParameter ( "name" ) ) ;
}
Map < String , String [ ] > map = request. getParameterMap ( ) ;
String pathInfo = request. getPathInfo ( ) ;
ServletInputStream inputStream = request. getInputStream ( ) ;
4. @PathVariable获取rest风格路径参数
@RequestMapping ( "/fun4/{id}/{name}" )
public Book fun4 ( @PathVariable long id, @PathVariable String name) {
log. info ( "{} {}" , id, name) ;
Book book= new Book ( id, name) ;
return book;
}
5. @RequestParam绑定请求参数到方法形参
@RequestMapping ( "/fun6" )
public Book fun6 ( @RequestParam ( "name" ) String name,
@RequestParam ( "id" ) Long id) {
log. info ( "{} {}" , id, name) ;
Book book= new Book ( id, name) ;
return book;
}
当请求参数username或者password不存在时会有异常发生, 可以通过设置属性required= false 解决
@RequestParam ( value= "username" , required= false )
6. @RequestBody绑定请求参数到方法形参
只能Post方法 参数必须Json字符串 Body只能有一个
@RequestMapping ( "/fun7" )
public Book fun7 ( @RequestBody Book book) {
log. info ( "book={}" , book) ;
return book;
}
7. @RequestHeader
RequestHeader主要用来获取请求当中的请求头
@RequestMapping ( "/geteHeader" )
public void getHeader ( @RequestHeader ( "user-id" ) String userId) {
}
@RequestMapping ( "/geteHeader" )
public void getHeader ( @RequestHeader Map < String , String > headers) {
}
@RequestMapping ( "/geteHeader" )
public void getHeader ( @RequestHeader HttpHeaders headers) {
}
8. @CookieValue
使用@CookieValue注解来获得指定的 Cookie 的值。
@GetMapping ( "park/getCookie" )
public String getCookieValue ( @CookieValue ( "jid" ) String jId) {
System . out. println ( jId) ;
return "success" ;
}