[Spring Boot] Web development - parameter passing

Parameter passing

Parameter passing is the basic content of web development. Front-end pages and back-end services judge the executed business logic through request and returned parameters. Therefore, parameter passing and receiving are the most basic but very important functions in web development. Spring Boot supports a variety of parameter receiving methods. By providing annotations to help limit the type of request, receive parameters in different formats, etc., we will introduce them through examples.

1.@PathVariable

In web applications, the most commonly used parameter passing method is URL parameter passing, that is, putting parameters in the requested URL. For example, the personal homepages of different users on Weibo should correspond to different URLs: http://weibo.com/user/1, http://weibo.com/user/2. It is impossible for us to define a @RequestMapping annotation method for each user to map URL requests. For URLs with the same pattern, the same rule can be used for processing.

1.1 Define URL variables

The @RequestMapping annotation uses {} to declare URL variables.
For example @RequestMapping("/user/{username}"). Among them, {username} is the defined variable rule, and username is the name of the variable. This URL route can match any of the following URL requests:

/user/tianmaying
/user/ricky
/user/tmy1234

After defining the variable rules in @RequestMapping, the @PathVariable annotation provided by Spring Boot helps us obtain the variable parameters defined in the URL. Examples are as follows:

	@RequestMapping("/user/{username}")
    @ResponseBody
    public String userProfile(@PathVariable String username) {
    
    
      return "user:" + username;
    }

In the above example, Spring Boot will automatically pass the variable defined in the URL to the username parameter of the userProfile method (assignment with the same name). For example, when the HTTP request is /users/lxml, the value lxml of the URL variable username will be assigned to the function parameter username, and the returned data is user:lxml.

It should be noted that by default, the variable parameter cannot contain the URL separator "/", that is to say, the URL route defined above cannot match /users/lxml/zhang, even if lxml/zhang is an existing username.

1.2 Define multiple URL variables

The example of passing a single variable was introduced above, but what about multiple variables? Similarly, @RequestMapping supports defining routes that contain multiple URL variables, examples are as follows:

	@RequestMapping("/user/{username}/blog/{blogId}")
    @ResponseBody
    public String getuserBlog(@PathVariable String username, @PathVariable String blogId) {
    
    
      return "user:" + username + "blog" + blogId;
    }

In the example above

@RequestMapping("/user/{username}/blog/{blogId}") passes in two parameters {username} and {blogId}, and then uses @PathVariable to map the corresponding variable parameters.

In the case of multi-variable parameters, Spring Boot can automatically assign the corresponding function parameter value according to the variable name, or explicitly declare the specific URL variable name in @PathVariable.

By default, the parameters of the @PathVariable annotation support automatic conversion of some basic data types, such as int, long, date, string, etc. Spring Boot can convert according to the specific value of the URL variable and the data type of the function parameter. For example, /user/lxml/blog/1 will assign the value of "lxml" to username, and 1 to the variable blogId of type int.

1.3 Matching regular expressions

Although @RequestMapping routing supports URL variables, it is often necessary to define and restrict URL variables more precisely, for example, the username only contains lowercase letters, numbers, and underscores:

/user/fpc是一个合法的URL
/user/#不是一个合法的URL

In this case, simply defining the {username} variable cannot meet the requirements. It doesn't matter, the @RequestMapping annotation also supports regular expression matching, which can be controlled more precisely by defining regular expressions. The definition syntax is {variable name: regular expression}, and the sample code is as follows:

	@RequestMapping("/user/{username:[a-zA-Z0-9_]+}/blog/{blogId}")
    @ResponseBody
    public String getuserBlog(@PathVariable String username, @PathVariable String blogId) {
    
    
      return "user:" + username + "blog" + blogId;
    }

In the above example, [a-zA-Z0-9_]+ regular expression is used to limit the username parameter value to only contain lowercase letters, uppercase letters, numbers, and underscores. After the URL variable rules are set in this way, illegal URLs will not be processed, and 404Not Found will be returned directly.

2. Use the Bean object to receive parameters

For form submission with many parameters, Spring Boot can create a JavaBean object to receive form parameters passed in by HTTP. It should be noted that the JavaBean object must contain a default constructor, and at the same time, the property field that needs to be set must have a setter method.

2.1 Add Bean Entity Class

First, add the entity class corresponding to the form, the specific code is as follows:

public class Student {
    
    
    private String fristName;
    private String lastName;
    //省略set和get
}

The above example defines the Student data entity class.

2.2 Add background method

Add the save() method in the StudentController controller to receive the data from the foreground. The sample code defining the save() method is as follows:

	@RequestMapping("/save")
    public String save(Student student) {
    
    
        String fristName = student.getFristName();
        String lastName = student.getLastName();
        return fristName +" "+ lastName;
    }

When submitting form data in the browser, Spring Boot will automatically convert the submitted form data into a Student object, and then pass it to the save() method.

3. @RequsetBody receives JSON data

@RequestBody mainly maps the JSON data object passed in from the front end to the entity object of the back end. For example, after the front end passes in data in JSON format, the @RequestBody annotation will automatically deserialize the JSON data into a Student object. When using it, you need to pay attention to the following two points:

1) The object attributes and types passed by the front end must correspond to those of the back end. For example, if the user attribute defined in the backend is "int id, String name", the frontend must use the same data type and field to define.

2) To use the JSON dataset for delivery, that is, set it to contentType: "application/json".

The following sample code demonstrates how to use @RequsetBody to receive JSON data:

    @PostMapping(path = "/save2")
    public String save2(@RequestBody Student student) {
    
    
        String fristName = student.getFristName();
        String lastName = student.getLastName();
        return fristName +" "+ lastName;
    }

The @PostMapping annotation contains the consumes parameter, which defaults to application/json, indicating that the frontend needs to pass in parameters in JSON format. In addition, Spring Boot will convert the data into corresponding data types according to the one-to-one correspondence of the names. For example, there are int or date types in the JSON data, and all strings are passed from the front desk, and Spring Boot will automatically convert them into data types in the entity class.

4.@ModelAttribute

We can place the @ModelAttribute annotation on a method in the controller (Controller). When a URL in this controller is requested, the annotated method will be called first and the result of the method will be used as an attribute of the public model, and then the processing method corresponding to the URL will be called, and the front-end page will obtain the returned data through the model.

The method marked with @ModelAttribute will be executed before the control execution method of each mapped URL in the Controller class. The method of use is shown in the sample code below:

    
    @ModelAttribute
    public void findUserById(@PathVariable("userId")Long userId, Model model) {
    
    
        model.addAttribute("user",userService.findUserById(userId));
    }
    @GetMapping("/user/{userId}")
    public String findUser(Model model) {
    
    
        System.out.println(model.containsAttribute("user"));
        return "success !";
    }

In the above example, when we request the interface /user/1, the findUserById() method will be called first, and the corresponding User object will be queried by userId in the method and placed in the Model. If you just add an object to the Model, the above code can be more refined:

 @ModelAttribute
    public User findUserById(@PathVariable("userId") Long userId) {
    
    
        return UserService.findUserById(userId);
    }

The User object returned by the above code will be automatically added to the Model, which is equivalent to manually calling the model.addAttribute(user) method.

Model passes parameters to the page through the addAttribute() method. The method modified by @ModelAttribute will be called before login, and it assigns the requested parameter value to the corresponding variable. Objects can be added to the Model in the method, provided that a parameter of the Model type is added to the method.

It should be noted that the method annotated by @ModelAttribute will be executed before each method of this controller is executed, so it should be used with caution when mapping multiple URLs to one controller.

5. ModelAndView object

ModelAndView is also a commonly used data return object in Spring MVC. When the controller finishes processing the request, it usually returns the ModelAndView object containing the view object and data to the foreground. It acts like the setAttribute() method of the request object.

The ModelAndView object has two functions:

1) Set the steering address (this is also the main difference between ModelAndView and ModelMap).
2) Pass the background data back to the foreground page.

ModelAndView is also very simple to use. In the controller, put the data required by the front page into the ModelAndView object, and then return the mv object. The following example demonstrates using the ModelAndView object to return data to the front page:

    @RequestMapping(value="/detail/{id}")
    public ModelAndView detail(@PathVariable Long id) {
    
    
        ModelAndView mv = new ModelAndView();
        User user = UserService.getUserById(id);
        // 设置user对象的username属性
        mv.addObject("user", "user");
        // 地址跳转,设置返回的视图名称
        mv.setViewName("detail");
        return mv;
    }

In the above example, the user data is obtained first, and then the data and the object are returned to the foreground detail page. This way Spring MVC will use the included view to render the model data.

Guess you like

Origin blog.csdn.net/weixin_45627039/article/details/131844205