[SSM-SpringMVC] 04-Detailed explanation of @RequestMapping annotations, super detailed, used with @RequestParam and @PathVariable annotations

@RequestMapping annotation

@RequestMappingIs a processing request for the address to the processor controller function annotation method of mapping rules, the annotations maps HTTP requests to the processing method of the MVC controller and REST controller , it can be used on a class or method . The annotation on the class means that all methods in the class that respond to requests use this address as the parent path (module path).

Six basic attributes

Attribute name description
value(path) Specify the actual access address of the request, the default @RequestMapping("url")value url is the value of value. The specified address can be a URI Template pattern.
method Specify the method type of the request, mainly including GET, POST, DELETE, PUT, etc.;
params Specify that certain parameter values ​​must be included in the request, and include it to allow the method to process the request.
headers The specified request must contain certain specified header values, so that the method can process the request by including it.
consumes Specify the type of data returned after processing the request, such as application/json, text/html, etc.
produces Specify the type of content to be returned, and return if and only if the specified type is included in the (Accept) type in the request header;

Use of @RequestMapping annotation

1. @RequestMappingAdd to the class (name the address for the module)

Access to all methods under this class requires an address prefix /test+ the path/value of the specific method to access

@Controller
@RequestMapping("test")
public class RequestMappingController {
    
    }

2. @RequestMappingWrite on the method

2.1 Write the string value directly value// path, call the current project address/module/ testMappingaccess,
	@RequestMapping("testMapping")
    public String testMapping(){
    
    
    	return "requestmappingsuccess";//视图解析器前后缀拼接返回页面地址
	}
//或者下面方法都行
@RequestMapping(value = "testMapping")
@RequestMapping(path = "testMapping")


2.2 Configure multiple link mappings
//通过 /test1 /test2 /test3 和/testurl/下的所有子模块 都能访问
@RequestMapping({
    
    "/test1","/test2","/test3","testurl/*"})
@RequestMapping(value = {
    
    "/test1","/test2","/test3",,"testurl/*"})
@RequestMapping(path = {
    
    "/test1","/test2","/test3",,"testurl/*"})

2.2 methodUse of attributes

methodIf it is not set, any attribute can be accessed . If it is set, only the request method of the set submission method can be accessed.

Value in 4:

  • RequestMethod.GET
  • RequestMethod.POST
  • RequestMethod.PUT
  • RequestMethod.DELETE

If the method value is set, only the request method of setting the value can be supported, and other request methods are not supported.就会报405错误 – Method Not Allowed

//设置只支持post请求
@RequestMapping(path="testMethod",method = {
    
    RequestMethod.POST})
//设置只接收get请求
@RequestMapping(path="testMethod",method = {
    
    RequestMethod.GET})

2.3 paramProperties

  Specify that certain parameter values ​​must be included in the request, and include it to allow the method to process the request.

//请求中必须要有参数username(页面中的name值),且参数值要为striveday才执行该方法
@RequestMapping(value="/testParam", params="username = strivedaay")
//请求中必须要有参数username(页面中的name值),且参数值不为striveday才执行该方法
@RequestMapping(value="/testParam", params="username != strivedaay")

2.4 headersProperties

  The scope of the specified request must contain certain specified header values, which can be included to allow the method to process the request.

    @RequestMapping(value="testHeaders",headers={
    
    "context-type=text/plain","context-type=text/html"})
    public String testHeaders(){
    
    }

For the above access, if context-type=text/plain,context-type=text/htmlthese two attributes are not included in the request header , then the method cannot be accessed and a 404 error is reported.


2.5 consumesattributes

  consumesSpecify the type of data returned after processing the request, for example application/json, text/htmletc.

//设置处理请求之后返回值为json数据类型
@RequestMapping(value = "testConsumes",consumes="application/json")
public String testConsumes(@RequestBody User user, Model model) {
    
    }   

2.6 producesProperties

  producesUsed to specify the type of content returned, and only if the specified type is included in the (Accept) type in the request header

//设置请求之后返回数据是json数据类型,且request的请求头中的要有(包含)该类型,才能返回
@RequestMapping(value = "testProduces ",consumes="application/json")
public String testProduces(@RequestBody User user, Model model) {
    
    } 

2.7 Cooperating with @RequestParamsetting request parameters【***】

  Using @RequestParam, you can bind HTTP request parameters to the parameters of the method in the controller, and realize that the parameters of the page incoming parameters (the value of name) and the formal parameter names of the method receiving parameter list are inconsistent, and parameter binding (assignment) can also be performed

@RequestParamAnnotations have three attributes

  • value : The value in the annotation must be consistent with the parameter name passed in the page.
  • required : The default value is true, which means that the parameter must be given a value. If this value is not given, a 400 page will appear.
  • defaultValue = "striveday": If the parameter is given, get it; if no parameter is given, the default is striveday.
  • [Tips 1] @RequestParamBy default, parameters must be specified, and the specified parameters can be selected by setting required = false, so that the method can be accessed without the @RequestParamspecified valueparameters in the request .
  • [Tips 2] defaultValueThe value that can be set , so that even if the requested valueparameter does not have a value, a default value will be set by defaultValue, and this method can also be accessed.
  • [Tips 1] All the data transmitted from the page to the background is of String type, and the obtained request.getParameter()data type is also String data type, but Spring will automatically convert between String and the eight basic data types.
  • [Tips 2] Error 400 (HTTP Status 400): Refers to the wrong request. The parameters provided by the url and the method specified received are inconsistent, the number type and number are inconsistent, the parameter name name is inconsistent, etc

For example, when a parameter username = strivedayis passed @RequestParam()to the page , it can be specified by annotation , and the method parameter name can be assigned if it is inconsistent with the request parameter name passed from the page.

//通过@RequestParam让页面传入的参数username赋值给方法参数列表的name
@RequestMapping("testRequestParam")
    public String getUsername(@RequestParam("username") String name){
    
    
    	System.out.println("username = " + name);
 }
2.8 Cooperate with @PathVariable, realize the processing of dynamic URL【***】

@RequestParamAnd the @PathVariabledifference: It
  @RequestMappingis a request parameter value used to process the request URL address to the processor controller function method mapping rule
  @PathVariableis the binding of the template variable part in the request URI to the method parameter of the processor function processing method, used to match the URL Rules and patterns of the path.

	//testPathVariable/{urlValue} 其中urlValue是占位符
	//以前的url是  /testPathVariable?urlvalue=值  现在变成了/testPathVariable/值
 	@RequestMapping(value = "/testPathVariable/{urlValue}", method = RequestMethod.GET)
    public String getUrlValue (@PathVariable("urlValue") String username){
    
    
    	System.out.println("urlValue = " + username);
        return username; 
      }

The above method access localhost:8080/testPathVariable/参数值, regardless of the parameter value, will access the method, but different parameter values ​​will be assigned to the hamster username of the method. For example, both your visit localhost:8080/testPathVariable/strivedayand visit localhost:8080/testPathVariable/studywill visit the method getUrlValue, but their assignments are usernamedifferent, and the output results are divided into urlValue = strivedayandurlValue = study

Guess you like

Origin blog.csdn.net/qq_40542534/article/details/109072582