Pritam Banerjee Pritam Banerjee - 1 year ago 183
Java Question

Is there a way to detect a preflight request in REST API Jersey?

Is there a way to know the preflight request headers in Java Jersey or is there a way to send different response to a preflight request?

Suppose I have the following code:

public JSONObject releaseClient(JSONObject clientAndUser, @Context HttpServletRequest request) throws JSONException{
int clientId = clientAndUser.getInt("id");
String userId = clientAndUser.getString("user");
JSONObject res = new JSONObject();

// Check if profile is locked by current user and if so release profile
if(clientLockService.unlockClient(clientId, userId)){
res.put("success", clientService.returnClientInfo(clientId));
} else {
// If not then set error message
res.put("error", "Profile is not locked by current user");
return res;

Now first the browser will send a preflight request. Is there a way where I can manipulate the response headers for a preflight request?

Answer Source

You can't do it in a resource method, unless you want to create a bunch of @OPTIONS methods, as the preflight is an OPTIONS request. Instead you should use a filter. You can see an example implementation here. It's not the greatest implementation, as it doesn't actually check for the preflight, it just sends the CORS headers for all request. If you look at the bottom of the post, it will link to a RESTEasy implementation of a filter to handle CORS. It is a much better implementation. You may want to study that one to get some ideas

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download