Home > Java > JavaBase > The use of 5 commonly used annotations in springmvc

The use of 5 commonly used annotations in springmvc

hzc
Release: 2020-07-01 17:25:30
Original
10932 people have browsed it

Five common annotations of springmvc: 1. @RequestMapping, which is an annotation used to process request address mapping; 2. @RequestParam, which is used to map the request parameter area data to the parameters of the function processing method; 3. @PathVariable, used to set request variables.

The use of 5 commonly used annotations in springmvc

@RequestMapping

is an annotation used to handle request address mapping
Applicable to classes and methods. Used on a class, it means that all methods in the class that respond to requests use this address as the parent path.

Attribute

value: Specifies the actual address of the request. The value can be an ordinary specific value, or it can be specified as a type of value containing a certain variable (URI Template Patterns with Path Variables)
can be specified as a type of value containing regular expressions (URI Template Patterns with Regular Expressions)
method: Specify the requested method type, GET, POST, PUT, DELETE, etc.
consumes: Specify the submission content type (Content-Type) for processing the request, such as application/json, text/html
produces: Specify the returned content type, only When the (Accept) type in the request header contains the specified type, it will return
params: The specified request must contain certain parameter values ​​before the method can process it
headers: The specified request must contain certain specified header values ​​in order for this method to process the request

  1.处理get请求: @RequestMapping(value = "index",method = RequestMethod.GET)
  2.springboot错误处理(使用app客户端返回json格式,使用浏览器返回html错误页)
   @RequestMapping(produces = "text/html")
  3.方法仅处理request Content-Type为“application/json”类型的请求
   @RequestMapping(value = "/pets", consumes="application/json")
  4.仅处理请求中包含了名为“myParam”,值为“myValue”的请求
   @RequestMapping(value = "/pets/{petId}", params="myParam=myValue") 
  5.仅处理request的header中包含了指定“Refer”请求头和对应值为“http://www.rxy.com/”的请求
   @RequestMapping(value = "/pets", headers="Referer=http://www.rxy.com/")
Copy after login

@RequestParam

is used to map the request parameter area data to the function processing method
Applicable to the parameters: method parameters

Attributes

value/name: Both attributes refer to the parameter name, that is, the request parameter name of the input parameter ( Usually form name attribute)
required: Whether it is required, the default is true, which means that the request must have corresponding parameters, otherwise an exception will be thrown
defaultValue: Default Value, indicating the default value if there is no parameter with the same name in the request. When setting this parameter, required is automatically set to false

  如果是原子类型,不管加没加注解,都必须有值,否则抛出异常,如果允许空值请使用包装类代替
  index(@RequestParam Integer num){}  表示该参数必须传递,值允许为空
  表示该参数非必须,如果不传则默认为0
  getPageData(@RequestParam(name="pageNum",defaultValue="0") String pageNo, String pageSize)
Copy after login

@PathVariable

is used to map template variables in the request URL Go to the parameters of the function processing method, that is, take out the variables in the uri template as parameters
Applicable: method parameters

Attributes

value: Specify the url template variable name, if the name is the same as the method parameter If the names are different, they need to be specified, otherwise they can be omitted.

    @RequestMapping("/index/{id}")
         public String index(@PathVariable("id") String sdf){
           System.out.println(sdf);
           return "index";
     }
Copy after login

@ResponseBody

This annotation is used to pass the appropriate to the object returned by the Controller method. After HttpMessageConverter is converted to the specified format, it is written to the body data area of ​​the Response object. By default, springmvc is returned in the form of json (Use jackson converter)
Applicable: method, when the data returned is not a page with html tags, but data in some other format (such as json, xml, etc.), use
to compare: @RequestBody Convert the HTTP request body to a suitable HttpMessageConverter object
@ResponseBody Return the content or object as the HTTP response body, and call the Adapter conversion object suitable for HttpMessageConverter, write Output stream

@RequestBody

1. This annotation is used to read the body part of the Request request, parse it using the system's default configured HttpMessageConverter, and then bind the corresponding data to the object to be returned. on the object
2. Then bind the object data returned by HttpMessageConverter to the parameters of the method in the controller
Applicable: method parameters, for the Content-Type of the request: application/json, application/xml must use this Note
For application/x-www-form-urlencoded, if the request method is put, it is required,
It is optional for POST/GET method (that is, it is not necessary, because @RequestParam, @ModelAttribute can also be processed)
For multipart/form-data, @RequestBody cannot handle data in this format
Attribute: required: Whether it is required, the default is true, indicating that the request must have corresponding parameters, otherwise an exception will be thrown
Example: Usually the front-end using this annotation sends an ajax request, then the request part is as follows:

         $.ajax({
           type: "POST",
           url:"/role/saveRole",
           contentType:"application/json",
           data: JSON.stringify(_self.form)...
Copy after login

Note: contentType cannot be omitted, data must be converted into a json string through stringify
Then the corresponding The method can be written like this:

@RequestMapping(value = "/saveRole",method = RequestMethod.POST)
public String saveRole(@RequestBody People requestJson) {}
Copy after login

If the front-end passes an array of objects, the backend can also use List to accept it directly. This is the most practical way to bind List data

@CookieValue

You can bind the cookie value in the Request header to the parameters of the method
Applicable to: method parameters

获取cookie中的JSESSIONID
public String index(@CookieValue("JSESSIONID") String cookie){}
Copy after login

@RequestHeader

You can bind the Request The value of the request header part is bound to the parameters of the method
Applicable to: method parameters

获取请求中Accept-Encoding值,返回gzip, deflate, br
public String index(@RequestHeader("Accept-Encoding") String host){return host;}
Copy after login

@ExceptionHandler

注解在方法上,表示该方法用于处理特定的异常,处理范围是当前类,如果想要全局捕获异常,需要使用@ControllerAdvice
当一个Controller中有多个HandleException注解出现时,那么异常被哪个方法捕捉呢?这就存在一个优先级的问题
ExceptionHandler的优先级是:在异常的体系结构中,哪个异常与目标方法抛出的异常血缘关系越紧密,就会被哪个捕捉到
属性:value: 需要处理的异常类型集合(Class)
在当前Controller有两个处理异常的方法,当访问/index时,页面显示: json data

package com.rxy.controller;

@Controller
public class HelloController {
    
    @ExceptionHandler({ ArithmeticException.class })
    @ResponseBody
    public String handleArithmeticException(Exception e) {
        e.printStackTrace();
        return "json data";
    }
    
    @ExceptionHandler({ IOException.class })
    public String handleIOException(Exception e) {
        e.printStackTrace();
        //返回错误页面
        return "error";
    }

    @RequestMapping("/index")
    public String index(){
        int i = 10 / 0;
        return "index";
    }

}
Copy after login

The above is the detailed content of The use of 5 commonly used annotations in springmvc. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template