I'm using Jersey 1.19, Java 1.6, and Tomcat 5.5.28 (which is Servlet 2.4).
The code is similar to this example:
package com.mkyong.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.mkyong.Track;
@Path("/json/metallica")
public class JSONService {
@GET
@Path("/get")
@Produces(MediaType.APPLICATION_JSON)
public Track getTrackInJSON(@Context HttpServletRequest request) {
if (request.getRequestedSessionId() == null ||
request.getSession(false) == null) {
// return to caller with an HTTP 404 error
// code goes here
}
else {
Track track = new Track();
track.setTitle("Enter Sandman");
track.setSinger("Metallica");
return track;
}
}
}
The class returns JSON and that's what the caller is expecting. But if I wanted to perform some validation like a bad or non-existent session and return an HTTP 404 error instead, how is this done?
Thank you for any help.
You can use HttpServletResponse
to set status code.
...
@Path("/json/metallica")
public class JSONService {
@GET
@Path("/get")
@Produces(MediaType.APPLICATION_JSON)
public Track getTrackInJSON(@Context HttpServletRequest request, HttpServletResponse response) {
if (request.getRequestedSessionId() == null ||
request.getSession(false) == null) {
response.setStatus(404);
// code goes here
}
else {
Track track = new Track();
track.setTitle("Enter Sandman");
track.setSinger("Metallica");
return track;
}
}
}
Since you're using JAX-RS, my preferred approach is to throw an exception and have an exception mapper catch it and return a response with desired response code.
So your resource class would be:
@GET
@Path("/get")
@Produces(MediaType.APPLICATION_JSON)
public Track getTrackInJSON(@Context HttpServletRequest request) {
if (request.getRequestedSessionId() == null ||
request.getSession(false) == null) {
throw new IllegalStateException("NOT_FOUND");
}
}
And then create an exception mapper class:
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@Provider
public class IllegalStateExceptionMapper implements ExceptionMapper<IllegalStateException> {
@Override
public Response toResponse(final IllegalStateException exception) {
if ("NOT_FOUND".equals(exception.getMessage()) {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
}
You can throw your own exception instead of a generic IllegalStateException, but the gist is the same.
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.