如何在解组JSON数据期间处理解析器异常?

Mon*_*oon 8 java parsing json jersey pojo

我在我的Web应用程序中使用Jersey.发送到服务器的数据是JSON格式,而后者在服务器端解组,获得的对象用于进一步处理.安全审计为这种方法带来了一些漏洞.

我的休息代码:

@POST
@Path("/registerManga")
@Produces(MediaType.APPLICATION_JSON)
public Response registerManga(MangaBean mBean){
    System.out.println(mBean);
    return Response.status(200).build();
}
Run Code Online (Sandbox Code Playgroud)

MangaBean:

public class MangaBean {
    public String title;
    public String author;

    @Override
    public String toString() {
        return "MangaBean [title=" + title + ", author=" + author + "]";
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }


}
Run Code Online (Sandbox Code Playgroud)

数据以以下格式发送:

["title":"Bleach","author":"kubo tite"]
Run Code Online (Sandbox Code Playgroud)

上面的数据被成功解组到一个对象中,我将其作为输出:

MangaBean [title=Bleach, author=kubo tite]
Run Code Online (Sandbox Code Playgroud)

但如果数据更改为:

["title":"<script>alert("123");</script>","author":"kubo tite"]
Run Code Online (Sandbox Code Playgroud)

发生500内部服务器错误并显示给用户:

javax.servlet.ServletException: org.codehaus.jackson.JsonParseException: Unexpected character ('1' (code 49)): was expecting comma to separate OBJECT entries
 at [Source: org.apache.catalina.connector.CoyoteInputStream@19bd1ca; line: 1, column: 28]
    com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:420)
    com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
    com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
Run Code Online (Sandbox Code Playgroud)

出现意外情况""会导致解析器出错.由于解组是在幕后完成的,我无法控制它,我无法处理被引发的异常.

我的问题是如何处理此异常并向用户返回正确的响应而不是堆栈跟踪.请指教.

Per*_*ion 17

注册一个异常映射器来处理JSON解析异常:

@Provider
class JSONParseExceptionMapper implements ExceptionMapper< JsonParseException > {
    @Override
    public Response toResponse(final JsonParseException jpe) {
        // Create and return an appropriate response here
        return Response.status(Status.BAD_REQUEST)
                .entity("Invalid data supplied for request").build();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我一生都无法在泽西岛 2.13 中使用它。啊。 (2认同)