Springboot several ways to get URL request parameters

Source: Internet
Author: User

Original address: http://www.cnblogs.com/xiaoxi/p/5695783.html

1, directly the parameter of the form is written in the parameters of the controller corresponding method, applicable to the Get method submission, not for post mode submission.

    /**     * 1. Write the parameters of the form directly in the parameter of the controller corresponding method      * @param username     * @param password *     @return *    * * Requestmapping ("/adduser1") public    String addUser1 (String username,string password) {        System.out.println (" Username is: "+username);        SYSTEM.OUT.PRINTLN ("Password is:" +password);        return "Demo/index";    }

URL form: The arguments submitted by http://localhost/SSMDemo/demo/addUser1?username=lixiaoxi&password=111111 need to match the name of the incoming parameter in the Controller method.

2, through the HttpServletRequest receive, the post way and get way can.

    /**     * 2, receive through HttpServletRequest      * @param request     * @return     *    /@RequestMapping ("/adduser2")    Public String AddUser2 (HttpServletRequest request) {        string Username=request.getparameter ("username");        String password=request.getparameter ("password");        System.out.println ("username is:" +username);        SYSTEM.OUT.PRINTLN ("Password is:" +password);        return "Demo/index";    }

3, through a bean to receive, post and get the method can be.
(1) Create a bean corresponding to the parameters in the form

Package Demo.model;public class Usermodel {        private String username;    private String password;    Public String GetUserName () {        return username;    }    public void Setusername (String username) {        this.username = username;    }    Public String GetPassword () {        return password;    }    public void SetPassword (String password) {        this.password = password;    }    }

(2) Use this bean to encapsulate the received parameters

    /**     * 3, through a bean to receive      * @param user     * @return     *    /@RequestMapping ("/adduser3")    public String AddUser3 (Usermodel user) {        System.out.println ("username is:" +user.getusername ());        SYSTEM.OUT.PRINTLN ("Password is:" +user.getpassword ());        return "Demo/index";    }

4. Get the parameters in the path by @pathvariable

    /**     * 4, get the parameters in the path through @pathvariable      * @param username     * @param password     *     @return    * * Requestmapping (value= "/adduser4/{username}/{password}", Method=requestmethod.get)
public string addUser4 (@PathVariable string username, @PathVariable string password) { System.out.println (" Username is: "+username); SYSTEM.OUT.PRINTLN ("Password is:" +password); return "Demo/index"; }

For example, when accessing the http://localhost/SSMDemo/demo/addUser4/lixiaoxi/111111 path, the template variables {username} and {password} in the URL are automatically Bind to a parameter with the same name through @pathvariable annotations, that is, Username=lixiaoxi, password=111111 after the entry.
5. Use @modelattribute annotations to get the form form data for the POST request
The JSP forms are as follows:

<form action = "<%=request.getcontextpath ()%>/demo/adduser5" method= "POST" >      user name:&nbsp;< Input type= "text" name= "username"/><br/>     secret &nbsp;&nbsp; code: &nbsp;<input type= "Password" Name= "Password"/><br/>     <input type= "Submit" value= "Submit"/>      

The Java controller is as follows:

    /**     * 5, use the @modelattribute annotation to get the form form data for the POST request      * @param user     * @return *    /@RequestMapping ( Value= "/adduser5", method=requestmethod.post) public    String AddUser5 (@ModelAttribute ("user") Usermodel user) {        System.out.println ("username is:" +user.getusername ());        SYSTEM.OUT.PRINTLN ("Password is:" +user.getpassword ());        return "Demo/index";    }

6. Binding request parameters to method @requestparam with annotations

An exception occurs when the request parameter username does not exist and can be resolved by setting the property Required=false, for example: @RequestParam (value= "username", Required=false)

    /**     * 6, with annotations @requestparam binding request parameters to the method into the parameter      * @param username     * @param password     * @return    * * Requestmapping (value= "/adduser6", method=requestmethod.get) public    String AddUser6 (@RequestParam ("username") String username, @RequestParam ("password") string password) {        System.out.println ("username is:" +username);        SYSTEM.OUT.PRINTLN ("Password is:" +password);        return "Demo/index";    }

Springboot Common Annotations @pathvaribale/@RequestParam/@GetMapping Introduction

This post describes several annotations @pathvaribale/@RequestParam/@GetMapping that deal with the parameters in the URL.

Among them, the functions of the annotations are:

@PathVaribale get the data in the URL

@RequestParam get the value of the request parameter

@GetMapping combination annotations, is an abbreviation for @requestmapping (method = Requestmethod.get)

@PathVaribale get the data in the URL

Look at an example, if we need to get the ID value in URL=LOCALHOST:8080/HELLO/ID, the implementation code is as follows:

@RestControllerpublic class HelloController {    @RequestMapping(value="/hello/{id}",method= RequestMethod.GET)    public String sayHello(@PathVariable("id") Integer id){ return "id:"+id; }}

Similarly, if we need to have more than one parameter in the URL to get, then the code below will do it.

@RestControllerpublic class HelloController {    @RequestMapping(value="/hello/{id}/{name}",method= RequestMethod.GET)    public String sayHello(@PathVariable("id") Integer id,@PathVariable("name") String name){ return "id:"+id+" name:"+name; }}

Above, the precondition for getting the parameters in the URL by @pathvariable annotations is what happens when we know the format of the URL.

Only by knowing the format of the URL can we get the value of the corresponding position in the same format on the specified method.

In general, the format of the URL is: localhost:8080/hello?id=98, in this case how to get its ID value, which requires the help of @requestparam to complete the

@RequestParam get the value of the request parameter

Look directly at an example, as follows

@RestControllerpublic class HelloController {    @RequestMapping(value="/hello",method= RequestMethod.GET)    public String sayHello(@RequestParam("id") Integer id){ return "id:"+id; }}

Enter the address in the browser: localhost:8080/hello?id=1000, you can see the following results:

When we enter the address in the browser: Localhost:8080/hello?id, which does not enter the specific value of the ID, the result returned is null. The specific test results are as follows:

However, when we enter the address in the browser: Localhost:8080/hello, which does not enter the ID parameter, the following error is reported:

@RequestParam annotations provide us with a solution that allows users to use default values when they do not enter an ID, as follows:

@RestControllerpublic class HelloController {    @RequestMapping(value="/hello",method= RequestMethod.GET)    //required=false 表示url中可以不穿入id参数,此时就使用默认参数 public String sayHello(@RequestParam(value="id",required = false,defaultValue = "1") Integer id){ return "id:"+id; }}

The test results are as follows;

If you have more than one parameter in the URL, that is, a URL similar to Localhost:8080/hello?id=98&&name=wojiushimogui, you can do the same. The specific code is as follows:

/** * Created by wuranghao on 2017/4/7. */@RestControllerpublic class HelloController { @RequestMapping(value="/hello",method= RequestMethod.GET) public String sayHello(@RequestParam("id") Integer id,@RequestParam("name") String name){ return "id:"+id+ " name:"+name; }}

The test results in the browser are as follows:

@GetMapping Combo Annotations

@GetMapping is a combination annotation, an abbreviation for @requestmapping (method = Requestmethod.get). This annotation maps an HTTP get to a specific processing method.

That is, you can use @getmapping (value = "/hello") instead of @requestmapping (value= "/hello", method= requestmethod.get). That allows us to streamline the code.

Example

@RestControllerpublic class HelloController {    //@RequestMapping(value="/hello",method= RequestMethod.GET)    @GetMapping(value = "/hello") //required=false 表示url中可以不穿入id参数,此时就使用默认参数 public String sayHello(@RequestParam(value="id",required = false,defaultValue = "1") Integer id){ return "id:"+id; }}
Summary

This blog post describes a few commonly used to get the parameters in the URL ha, relatively simple.

The difference between spring Boot's @requestparam and @requestbody First, the problem description

Because the project is a front-end separation, the backend uses spring boot, which is made into microservices, exposing only the interface. Interface design style for the restful style, in the GET request, the background receive parameter annotation is requestbody error, in the POST request, the background receives the parameter annotation is Requestparam will also error.

Second, the cause of the problem

Since spring's requestparam annotations receive parameters from Requestheader, which is the request header, which is in the URL, the format is xxx?username=123&password= 456, while the requestbody annotation receives the parameter from the Requestbody, which is the request body.

Third, the solution

Therefore, in summary, if a GET request, the background receive parameter annotation should be requestparam, if it is a POST request, the background receive parameter annotation is requestbody. Attached are two examples, as follows:

GET Request

POST request

In addition, there is an application scenario, the interface specification for the resultful style, for example: If you want to get an ID under the question of the answer to the number of queries, then the background needs to dynamically get the parameters, the annotation is @pathvariable, and the value in requestmapping should be value= "/{id}/querynum", as follows:

Springboot several ways to get URL request parameters

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.