Jersey(1.19.1) - Extracting Request Parameters

Parameters of a resource method may be annotated with parameter-based annotations to extract information from a request. A previous example presented the use @PathParam to extract a path parameter from the path component of the request URL that matched the path declared in @Path.

@QueryParam is used to extract query parameters from the Query component of the request URL. The following example is an extract from the sparklines sample:

@Path("smooth")
@GET
public Response smooth(
    @DefaultValue("2") @QueryParam("step") int step,
    @DefaultValue("true") @QueryParam("min-m") boolean hasMin,
    @DefaultValue("true") @QueryParam("max-m") boolean hasMax,
    @DefaultValue("true") @QueryParam("last-m") boolean hasLast,
    @DefaultValue("blue") @QueryParam("min-color") ColorParam minColor,
    @DefaultValue("green") @QueryParam("max-color") ColorParam maxColor,
    @DefaultValue("red") @QueryParam("last-color") ColorParam lastColor
    ) { ... }

If a query parameter "step" exists in the query component of the request URI then the "step" value will be will extracted and parsed as a 32 bit signed integer and assigned to the step method parameter. If "step" does not exist then a default value of 2, as declared in the @DefaultValue annotation, will be assigned to the step method parameter. If the "step" value cannot be parsed as a 32 bit signed integer then a HTTP 404 (Not Found) response is returned. User defined Java types such as ColorParam may be used, which as implemented as follows:

public class ColorParam extends Color {
    public ColorParam(String s) {
        super(getRGB(s));
    }

    private static int getRGB(String s) {
        if (s.charAt(0) == ‘#‘) {
            try {
                Color c = Color.decode("0x" + s.substring(1));
                return c.getRGB();
            } catch (NumberFormatException e) {
                throw new WebApplicationException(400);
            }
        } else {
            try {
                Field f = Color.class.getField(s);
                return ((Color)f.get(null)).getRGB();
            } catch (Exception e) {
                throw new WebApplicationException(400);
            }
        }
    }
}

In general the Java type of the method parameter may:

  1. Be a primitive type;
  2. Have a constructor that accepts a single String argument;
  3. Have a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String)); or
  4. Be List<T>Set<T> or SortedSet<T>, where T satisfies 2 or 3 above. The resulting collection is read-only.

Sometimes parameters may contain more than one value for the same name. If this is the case then types in 4) may be used to obtain all values.

If the @DefaultValue is not used in conjunction with @QueryParam and the query parameter is not present in the request then value will be an empty collection for List, Set or SortedSet, null for other object types, and the Java-defined default for primitive types.

The @PathParam and the other parameter-based annotations, @MatrixParam, @HeaderParam, @CookieParam, @FormParam obey the same rules as @QueryParam. @MatrixParam extracts information from URL path segments. @HeaderParam extracts information from the HTTP headers. @CookieParam extracts information from the cookies declared in cookie related HTTP headers.

@FormParam is slightly special because it extracts information from a request representation that is of the MIME media type "application/x-www-form-urlencoded" and conforms to the encoding specified by HTML forms, as described here. This parameter is very useful for extracting information that is POSTed by HTML forms, for example the following extracts the form parameter named "name" from the POSTed form data:

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

If it is necessary to obtain a general map of parameter name to values then, for query and path parameters it is possible to do the following:

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

For header and cookie parameters the following:

@GET
public String get(@Context HttpHeaders hh) {
    MultivaluedMap<String, String> headerParams = hh.getRequestHeaders();
    Map<String, Cookie> pathParams = hh.getCookies();
}

In general @Context can be used to obtain contextual Java types related to the request or response. For form parameters it is possible to do the following:

@POST
@Consumes("application/x-www-form-urlencoded")
public void post(MultivaluedMap<String, String> formParams) {
    // Store the message
}
时间: 2024-10-27 11:03:28

Jersey(1.19.1) - Extracting Request Parameters的相关文章

Jersey(1.19.1) - Rules of Injection

Previous sections have presented examples of annotated types, mostly annotated method parameters but also annotated fields of a class, for the injection of values onto those types. This section presents the rules of injection of values on annotated t

More than the maximum number of request parameters

前些时间,我们的的一个管理系统出现了点问题,原本运行的好好的功能,业务方突然讲不行了,那个应用已经运行了好多年了,并且对应的代码最近谁也没改动过,好奇怪的问题,为了解决此问题,我们查看了日志,发现请求的参数压根没有传到后台控制器之中,奇怪了!明明前端传递了好多参数过来了呀!线上系统比较重要,又需要马上使用必须赶紧解决呀! 提交请求时的页面反应,如下所示: 于是我们想在本地模拟同样的操作,可气的是本地压根没任何问题,好头疼,对于这样的问题确实是最令人头疼的,同样的代码一边运行不了,一边屁事没有,后

Parameter Passing / Request Parameters in JSF 2.0 (转)

This Blog is a compilation of various methods of passing Request Parameters in JSF (2.0 +) (1)  f:viewParam One of the features added in JSF 2.0 is "View Parameters"; Simply speaking it allows adding "Query string" or "Request Par

Jersey(1.19.1) - Representations and Java Types

Previous sections on @Produces and @Consumes referred to MIME media types of representations and showed resource methods that consume and produce the Java type String for a number of different media types. However, String is just one of many Java typ

Jersey(1.19.1) - Ease of use and reusing JAX-RS artifacts

Since a resource is represented as a Java type it makes it easy to configure, pass around and inject in ways that is not so intuitive or possible with other client-side APIs. The Jersey Client API reuses many aspects of the JAX-RS and the Jersey impl

Jersey(1.19.1) - Hello World, Get started with Jersey using the embedded Grizzly server

Maven Dependencies The following Maven dependencies need to be added to the pom: <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-server</artifactId> <version>1.19.1</version> </dependency>

Jersey(1.19.1) - Hello World

1. Maven Dependency <properties> <jersey.version>1.19.1</jersey.version> </properties> <dependencies> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-core</artifactId> <versi

Jersey(1.19.1) - Life-cycle of Root Resource Classes

By default the life-cycle of root resource classes is per-request, namely that a new instance of a root resource class is created every time the request URI path matches the root resource. This makes for a very natural programming model where constru

Jersey(1.19.1) - Deploying a RESTful Web Service

JAX-RS provides a deployment agnostic abstract class Application for declaring root resource and provider classes, and root resource and provider singleton instances. A Web service may extend this class to declare root resource and provider classes.