我正在使用Jersey学习JAX-RS(又名JSR-311)。我已经成功地创建了一个根资源,并正在摆弄参数:

@Path("/hello")
public class HelloWorldResource {

    @GET
    @Produces("text/html")
    public String get(
        @QueryParam("name") String name,
        @QueryParam("birthDate") Date birthDate) {

         // Return a greeting with the name and age
    }
}

这工作得很好,并处理当前区域内Date(String)构造函数能理解的任何格式(如YYYY/mm/dd和mm/dd/YYYY)。但如果我提供的值无效或无法理解,就会得到404响应。

例如:

GET /hello?name=Mark&birthDate=X

404 Not Found

如何自定义此行为?也许是一个不同的响应代码(可能是“400个坏请求”)?记录一个错误怎么样?也许可以在自定义报头中添加问题的描述(“糟糕的日期格式”)以帮助排除故障?或者返回一个完整的带有详细信息的Error响应,以及一个5xx状态码?


当前回答

@QueryParam文档说

" The type T of the annotated parameter, field or property must either: 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)) 4) Have a registered implementation of javax.ws.rs.ext.ParamConverterProvider JAX-RS extension SPI that returns a javax.ws.rs.ext.ParamConverter instance capable of a "from string" conversion for the type. 5) Be List, Set or SortedSet, where T satisfies 2, 3 or 4 above. The resulting collection is read-only. "

如果你想控制String形式的查询参数不能转换为你的T类型时给用户的响应,你可以抛出WebApplicationException。Dropwizard附带以下*Param类,您可以根据需要使用。

布里帕拉姆,datparam, IntParam, LongParam, LocalDateParam, empidparam, UUIDParam。看到https://github.com/dropwizard/dropwizard/tree/master/dropwizard-jersey/src/main/java/io/dropwizard/jersey/params

如果你需要Joda DateTime,只需使用Dropwizard DateTimeParam。

如果上面的列表不适合您的需要,那么可以通过扩展AbstractParam来定义您自己的列表。重写解析方法。如果需要控制错误响应体,请重写错误方法。

Coda Hale关于这方面的好文章在http://codahale.com/what-makes-jersey-interesting-parameter-classes/

import io.dropwizard.jersey.params.AbstractParam;

import java.util.Date;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

public class DateParam extends AbstractParam<Date> {

    public DateParam(String input) {
        super(input);
    }

    @Override
    protected Date parse(String input) throws Exception {
        return new Date(input);
    }

    @Override
    protected Response error(String input, Exception e) {
        // customize response body if you like here by specifying entity
        return Response.status(Status.BAD_REQUEST).build();
    }
}

Date(String arg)构造函数已弃用。如果你使用Java 8,我会使用Java 8日期类。否则建议使用joda date时间。

其他回答

这实际上是正确的行为。Jersey将尝试为您的输入找到一个处理程序,并将尝试从提供的输入构造一个对象。在这种情况下,它将尝试使用提供给构造函数的值X创建一个新的Date对象。由于这是一个无效日期,按照惯例Jersey将返回404。

您可以重写并将出生日期作为字符串,然后尝试解析,如果您没有得到想要的结果,您可以通过任何异常映射机制(有几种)自由抛出任何您想要的异常。

有几种方法可以使用JAX-RS定制错误处理行为。这里有三个更简单的方法。

第一种方法是创建一个扩展WebApplicationException的Exception类。

例子:

public class NotAuthorizedException extends WebApplicationException {
     public NotAuthorizedException(String message) {
         super(Response.status(Response.Status.UNAUTHORIZED)
             .entity(message).type(MediaType.TEXT_PLAIN).build());
     }
}

要抛出这个新创建的异常,只需:

@Path("accounts/{accountId}/")
    public Item getItem(@PathParam("accountId") String accountId) {
       // An unauthorized user tries to enter
       throw new NotAuthorizedException("You Don't Have Permission");
}

注意,您不需要在throws子句中声明异常,因为WebApplicationException是一个运行时异常。这将向客户端返回401响应。

第二种更简单的方法是直接在代码中构造WebApplicationException的实例。只要您不需要实现自己的应用程序异常,这种方法就可以工作。

例子:

@Path("accounts/{accountId}/")
public Item getItem(@PathParam("accountId") String accountId) {
   // An unauthorized user tries to enter
   throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}

这段代码也向客户端返回401。

当然,这只是一个简单的例子。如果需要,您可以使异常更加复杂,并且您可以生成任何您需要的http响应代码。

另一种方法是用一个小的包装器类来包装一个现有的异常(可能是ObjectNotFoundException),该类实现了用@Provider注释注释的ExceptionMapper接口。这告诉JAX-RS运行时,如果引发包装异常,则返回ExceptionMapper中定义的响应代码。

我太喜欢StaxMan可能会实现QueryParam作为一个字符串,然后处理转换,重新抛出必要的。

如果特定于区域设置的行为是期望和预期的行为,您将使用以下命令返回400 BAD REQUEST错误:

抛出新的WebApplicationException(Response.Status.BAD_REQUEST);

有关更多选项,请参阅JavaDoc中的javax.ws.rs.core.Response.Status。

@Provider
public class BadURIExceptionMapper implements ExceptionMapper<NotFoundException> {

public Response toResponse(NotFoundException exception){

    return Response.status(Response.Status.NOT_FOUND).
    entity(new ErrorResponse(exception.getClass().toString(),
                exception.getMessage()) ).
    build();
}
}

创建类之上。这将处理404 (NotFoundException),在toResponse方法中,您可以给出自定义响应。类似地,还有ParamException等,你需要映射它们来提供定制的响应。

Jersey在解组参数失败时抛出com.sun.jersey.api.ParamException异常,因此一个解决方案是创建一个ExceptionMapper来处理这些类型的异常:

@Provider
public class ParamExceptionMapper implements ExceptionMapper<ParamException> {
    @Override
    public Response toResponse(ParamException exception) {
        return Response.status(Status.BAD_REQUEST).entity(exception.getParameterName() + " incorrect type").build();
    }
}