Summary of Four Ways of SpringMVC Receiving Parameters Passed by Front End

  • 2021-12-04 09:59:35
  • OfStack

Directory SpringMVC can receive parameters passed by front end in 4 ways @ RequestParam get annotations @ PathVariable get annotations SpringMVC, which can receive parameters SpringMVC without setting any annotations, or can be automatically packaged into objects @ RequestBody for receiving arrays or automatic encapsulation of complex objects SpringMVC (can enter without passing parameters) SpringMVC can't receive parameter reason code list passed by front end

Four Ways for SpringMVC to Receive Parameters Passed by Front End

@ RequestParam notes @ PathVariable notes Automatic Parameter Analysis of SpringMVC @ RequestBody annotation for SpringMVC

@ RequestParam get annotations


get/post  url =>"xx/user?id=1"    action =>
public String User( @RequestParams(name="id") Long id ){
}

Parameters defined by @ RequestParam are automatically resolved to the type defined by the method.


@RequestParams(name="id") Long id ) (Adopted postman Simulation post Request) 

@ PathVariable get annotations


get/post  url =>"xx/user/1"    action =>public String User( @PathVariable(name="id") Long id){}

@ PathVariable must specify the corresponding type through regularity. Only when url is specified as a number, the method parameter is defined as a number type without reporting an error. For example: (url can be restricted by other regularities, and only the qualified url will be mapped to the corresponding action, otherwise the corresponding action will not be found)


  @RequestMapping("/user/{id:\\d}")
  public String User( @PathVariable(name="id") Long id){}

SpringMVC, you can receive parameters without setting any comments

For example


@GetMapping("/category")
   public String category( Long id) {
    System.out.println(id);
    return "post/category";
}

It can be accessed through/category or through/category? id=1 Access

SpringMVC, which can also be automatically wrapped into objects

url/category? title = Test or/category can access the target resource


    @GetMapping("/category")
    public String category( MPost post ) {
        System.out.println(post.getTitle());
        return "post/category";
    }

@ RequestBody is used to receive arrays or complex objects

(Parameters must be placed in requestbody, and placed in url will not be resolved, even if the request mode is post)


url  => /category  requestbody =>{"id":1}
    @PostMapping("/category")
    public String category( @RequestBody Post post ) {
        System.out.println(post.getTitle());
        return "post/category";
    }

For an array of objects, change the method parameter to @ RequestBody List < Post > post will do

Direct typing/category will not find the corresponding action

Automatic encapsulation of SpringMVC (can be entered without parameter transmission)

@RequestParam (Must pass, but can be manually set to false) @PathVariable (Only regular expressions that match the settings are allowed to enter, and cannot be empty)

By comparison, it is mainly to provide stricter restrictions for url, so as to prevent 1 other url from entering the action.

Provides a complex way to accept parameters @ RequestBody, but the parameters must be placed in @ RequestBody

What needs to be noted for PathVariable is that the parameters contain special characters, which may lead to incomplete parameters.

For various request modes, it is necessary to authenticate the current user under 1 and encrypt url. (Particularly critical data)

Reason why SpringMVC did not receive parameters passed by the front end

When learning SpringMvc, I encountered a problem. Backstage 1 could not directly receive the parameters passed by the foreground, which delayed for a long time and finally found the reason. Write a blog to record this pit, break down--_ _-

Code list

Use SpringMvc to accept the parameters passed by the foreground is very simple, as long as the parameter name and the name in the foreground form can be 1, I get an example of a file upload, so look at my foreground page


<body>
<!-- enctype="multipart/form-data" Added when the file is uploaded, the encoding type, and its value defaults to application/x-www-form-urlencoded -->
<form action="testFileUpload" method="post" enctype="multipart/form-data">
File: <input type="file" name="file" />
Desc: <input type="text" name="desc" />
<input type="submit" value="Submit" />
</form>
<br><br>
<a  href="emps" rel="external nofollow" >List All Employees</a>
</body>

The following is the controller of SpringMvc


@Controller
public class springMVCTest { 
 @RequestMapping("/testFileUpload")
 public String testFileUpload(@RequestParam("desc") String desc, 
   @RequestParam("file") MultipartFile file) throws IOException {
  System.out.println("desc: " + desc);
  System.out.println("originalFilename: " + file.getOriginalFilename());
  System.out.println("inputStream: " + file.getInputStream());  
  return "success";
 }
}

This is followed by the web. xml file


<!--  Configure DispatcherServlet -->
 <!-- SpringMvc Will be based on servlet-name Configure, find /WEB-INF/dispatcher-servlet.xml Load as a configuration file Web In engineering  -->
 <servlet>
  <servlet-name>springDispatcherServlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:springmvc.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>springDispatcherServlet</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>

** Then the configuration file for SpringMvc **


@RequestParams(name="id") Long id ) (Adopted postman Simulation post Request) 
0

After that, the pit came. Because it was a file upload, it was necessary to add multipartResolver to the configuration file of Spring MVC. If you add it, you will add it, so I added the following 1 code:


@RequestParams(name="id") Long id ) (Adopted postman Simulation post Request) 
1

Then the pit appeared, and it was found that id was written incorrectly, id= "multipartResolver", and the modified code was:


@RequestParams(name="id") Long id ) (Adopted postman Simulation post Request) 
2

Related articles: