简体   繁体   中英

Jersey Viewable with Json

The JAX-RS implementation Jersey supports MVC style web applications through the Viewable class, which is a container for a template name and a model object. It is used like this:

@GET
@Template
@Produces({MediaType.TEXT_HTML})
public Viewable get() {
    JsonObject response = null;
    try{
        response = service.getDetails(id);
        }
    catch(Exception ex) {
        log.error("failed to get details", ex);
        throw ex;
    }
    return new Viewable("/test", response);
}

this is right way to send the json from Viewable? Is there a way to set a json object explicitly?

A few things: I don't have any experience using Viewable in particular, but I am familiar with JAX-RS and can probably throw a couple of pointers your way.

Exception Handlers

JAX-RS defines a feature for mapping exceptions to responses. This functionality is nice for removing those exception blocks from your resource code. Check out the Jersey docs on this topic for a tutorial on how to register these. A quick summary is: 1) implement ExceptionMapper and 2) register the class as a Provider.

For starters, I recommend creating a simple suite that maps to common HTTP codes . For example:

  • NotFoundException - returns a 404 response and is used when a single entity is requested but not found.
  • InvalidInputException - returns a 422 response and is used when a request does not pass validation (like trying to save an phone number in an email field).
  • BadRequestException - usually the framework will handle these situations for you, but if not, a Bad Request is one that is not formatted properly. So if a required header is missing, or if a client tries to save a collection when only a single entity is allowed.
  • Exception * - There is a star here because an unexpected exception is usually due to a server error, so 500 is an appropriate default response. A reason you may want to create a global uncaught exception handler is to prevent the stacktrace from being returned in the response body. That can be bad for security reasons.

View and Model

You should not need the @Template annotation if you are using the Viewable object. Also, Viewable is expecting a template as the first argument and a model (map) as the second argument. The model should have keys that match variables in your JSP. Right now your method will look for a file called test.jsp in the root of whatever your template config is set to in web.xml. If you take all of that into consideration, your method could look something like this:

@GET
@Produces(MediaType.TEXT_HTML)
public Viewable getMobileReport() {
    return new Viewable("/test", service.getMobileReport(id));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM