How to Obtain Parameters in Jersey Restful Interface

  • 2021-09-11 20:15:18
  • OfStack

Origin

When I work, I use java to develop the server background and write Restful interface with Jersey. I found that there is an Post method that can't get parameters all the time. After checking for a long time, I found that the annotations for getting parameters are not quite correct. I wrote @ formparam as @ queryparam, and found that it is good to change this. By the way, I sorted out the functions of different parameters.

Brief introduction

Get the parameters of URI

Get the parameters of the Get request

Gets the parameters of type Post

Add parameter defaults

Get the Map parameter

1.@PathParam

When you use this annotation to get parameters, you can get the parameters that make rules in URI

For example:


// The path of this class is /user
@GET
@Path("{username"})
@Produces(MediaType.APPLICATION_JSON)
public User getUser(@PathParam("username") String userName) {
 ...}

When the browser requests

http://localhost:8080/user/jack

The value of username is jack. Note that username here does not mean that the value of key is username, and value is jack, but that/user/is followed by username, and username here is just a variable.

2.@QueryParam

This parameter is used to get the query parameter in Get request. The difference between this parameter and the previous one is that it is passed through URI? Symbol to achieve.

For example:


@GET
@Path("/user")
@Produces("text/plain")
public User getUser(@QueryParam("name") String name, @QueryParam("age") int age) { 
...}

When the request of url is

http://localhost:8080/user?name=cesar & age=21

At this time, the parameters obtained by the function are name=cesar and age=21;

3.@FormPara

As the name implies, it is to get data from the form requested by Post.


@POST
@Consumes("application/x-www-form-urlencoded")
publicvoid post(@FormParam("name") String name) { 
// Store the message
}

4. Default parameter value DefaultValue

You can use this annotation when you want a parameter to have a default value when the function gets it. It can be used as follows


@GET
@Path("/user")
@Produces("text/plain")
public User getUser(@QueryParam("name") String name, @DefaultValue("26") @QueryParam("age") int age) { 
...}

Then when the age parameter is requested, if age is not assigned, it defaults to 26.

5. Use the parameter @ Context of Map

In a large server, due to the changeable parameters, the adjustment of parameter structure is easy to encounter problems, so you can consider using @ Context for annotation. Examples are as follows:


@GET
public String get(@Context UriInfo ui) { 
 MultivaluedMap<String, String> queryParams = ui.getQueryParameters(); 
MultivaluedMap<String, String> pathParams = ui.getPathParameters();
}

From the example, we can see that Context is actually a collection of other parameters. As long as you master these parameters and the meaning they represent, you can skillfully operate Jersey!

Problems and Solutions of Multiple Parameters Passed into Restful Interface

Conclusions:

restful-style interfaces do not support multiple parameters

Note: This article refers to the case of serializing parameters through json

1. Front

1 MyParam class defined for testing


public class MyParam {
    private String str;
    private Integer integer;
    //  Omission  getter And setter ... 
    }

I am doing the test is using Chrome plug-in Advanced REST client, can simulate the browser to send a variety of requests, and custom header and body.

When testing, you need to use post mode and add it in http request header


accept: application/json
content-type: application/json

Then, in Body requested by htpp, enter parameters in json format, such as {"str": "bb", "integer": 3}.

The following are several forms of multi-parameter interfaces, as well as input parameters and parsing results.

2. Type 1: Two String parameters


@POST
@Path("demo")
public Result function(String param1, String param2) ; 

Parameters passed in:


{"param1":"bb","param2":"cc"}

Parsed parameters:

param1: "{"param1":"bb","param2":"cc"}"

param2: ""

In this style, the transmitted parameters will read inputStream in request body when reading, and then the two parameters will be parsed cyclically. When the first parameter is parsed, inputStream will be turned off, and when the second parameter reads inputStream again, it will be empty.

In this case, all the parameters passed in will be assigned to the first String object, and the second String will be an empty string after parsing.

3. Type 2: 1 object parameter, 1 String parameter

If the first parameter is an encapsulated object, the first object can be parsed, but the second parameter is not available.

In this case, no error will be reported, but there is no problem when parsing the first object, and what you get when parsing the second String is an empty string.


@POST
@Path("demo")
@Consumes({MediaType.JSON})
public Result function(MyParam myParam, String param);

Parameters passed in:


@GET
@Path("/user")
@Produces("text/plain")
public User getUser(@QueryParam("name") String name, @QueryParam("age") int age) { 
...}
0

Parsed parameters:

param1: The object myParam can be parsed correctly, and its two attributes can be assigned correctly.

param2: ""

4. Type 3: 1 String parameter, 1 object parameter

If the positions of the two parameters are exchanged, all the incoming parameters will be parsed to the first String, and when parsing the second object, an error will be reported because the obtained data is empty. As follows:


@GET
@Path("/user")
@Produces("text/plain")
public User getUser(@QueryParam("name") String name, @QueryParam("age") int age) { 
...}
1

Parameters passed in:


@GET
@Path("/user")
@Produces("text/plain")
public User getUser(@QueryParam("name") String name, @QueryParam("age") int age) { 
...}
2

Parsed parameters:

param1: "{"str":"helo","integer":2},"string":"test""

param2: Error reported

5. Solutions

To solve the problem of passing in multiple parameters, there are several ideas:

1. Encapsulate the object, encapsulate multiple parameters to be passed into one object and pass it in

2. Embed variables in the access path, use the @ PathVariable annotation, write "/demo/{1}/{2}" in the request path, and then replace the corresponding position in the request path with the parameters to wear. This is only applicable to wrapper classes, such as String.

3. Change the requested content type to use content-type: application/x-www-form-urlencoded, which is submitted using an form form and can pass in two parameters, to be combined with the @ FormParam annotation

6. About passing in parameters in form form

The definition form of interface needs to be modified


@POST
@Path("demo")
@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
public Result function(@FormParam(value="string1")String string1, @FormParam(value="string2")String string2);

When requested, the header parameter needs to be modified


@GET
@Path("/user")
@Produces("text/plain")
public User getUser(@QueryParam("name") String name, @QueryParam("age") int age) { 
...}
4

Request form form in Body


@GET
@Path("/user")
@Produces("text/plain")
public User getUser(@QueryParam("name") String name, @QueryParam("age") int age) { 
...}
5

You can then correctly resolve to the values of the two parameters

Parsed parameters:

string1: wo

string2: kan


Related articles: