简体   繁体   中英

JAX-RS WHERE to escape response body

I have rest services (about 100 endpoints), implemented with JAX-RS Jersey. All of them have the return type "application/json", which may contain some html and javascript code, for which I need to do escaping, eg, "<" should turn into &lt; . The escaping function is easy, and there are libs for that.

The trouble is, I can't find the point in the code where I should do the escaping. I created a response like this:

public Response response(int response, URI location, Object entity) {
    Response.ResponseBuilder builder =
            Response.status(response)
                    .location(location)
                    .entity(entity);
}

And, I created a filter like below:

@Provider
public class ResponseFilter implements ContainerResponseFilter {

@Override
public void filter(ContainerRequestContext requestContext,
                   ContainerResponseContext responseContext)
    throws IOException
{
    Object entity = responseContext.getEntity();
}
}

Object entity can be of different classes. I believe, I need to know, when Jersey turns this object entity into a JSON String, so that I can escape that JSON string. However, all I have now is the Object entity , and I am not sure how to escape it.

I was thinking about doing entity.toString(), then escape that String and set it as entity. However, I am not sure Jersey uses toString() method to turn entity into JSON.

================ Example:

public class Person{
   private long id;
   private String name;
   private String description;
}

Actual response:

{"id": 1234, 
        "name": "John Doe",
        "description": "<script> Some javascript code </script>"}

Expected response:

{"id": 1234, 
    "name": "John Doe",
    "description": "&lt;script&gt; Some javascript code &lt;/script&lt;"}

Your object turns to JSON at the very end, (eg after all your filters passed) So you have some options:

do escaping in each particular class getter (or setter) for fields you need to escape.

     public class Person{
       private long id;
       private String name;
       private String description;

       public String getDescription()
       {
         return doEscape(description);
       }
    }

or you can introduce your own Annotation to the field and process your entity fields accordingly in your filter... or do sometning else... There are many ways...

Main point there is that JSON parser at the end cares only about JSON specific escapes. For String it is only " character.

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