如何将Java对象序列化为JSON并在servlet过滤器中将其返回? [英] How to serialize Java object into JSON and return it in servlet filter?

查看:200
本文介绍了如何将Java对象序列化为JSON并在servlet过滤器中将其返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个javax.servlet.Filter来检查是否允许客户端访问API REST资源.

I have this javax.servlet.Filter to check whether client is allowed to access API REST resource.

@Component
public class AuthorizationRequestFilter implements Filter {

    public static final String AUTHORIZATION_TOKEN = "X-Access-Token";

    @Autowired
    @Qualifier("loginService")
    private ILoginService loginService;

    private void throwUnauthorized(ServletResponse res) throws IOException {

        HttpServletResponse response = (HttpServletResponse) res;

        response.reset();
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);

    }

    private void throwForbidden(ServletResponse res) throws IOException {

        HttpServletResponse response = (HttpServletResponse) res;

        response.reset();
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        response.sendError(HttpServletResponse.SC_FORBIDDEN);

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;

        String accessToken = request.getHeader(AUTHORIZATION_TOKEN);

        if (StringUtils.isEmpty(accessToken)) {
            throwUnauthorized(res);
        } else {
            AccountLoginData account = loginService.find(accessToken);
            if (account == null) {
                throwForbidden(res);
            }
        }

        chain.doFilter(req, res);

    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

}

它可以工作,但是我想在这两个throw*()方法中使用适当的信息将其写入客户端JSON.在该应用程序的另一部分中,我使用这些响应消息对象来通知客户端发生了什么情况.

it works but I would like to in these two throw*() methods write to the client JSON with appropriate information. In another part of this application I use these response message objects to inform client what happened.

例如,当找不到记录时:

For example, when record has not been found:

public class NotFoundResponseMessage extends ResponseMessage {

    public NotFoundResponseMessage(String message) {
        super(HttpStatus.NOT_FOUND, 1, message);
    }

}

public class ResponseMessage {

    private int status;
    private int code;
    private String message;
    private String reason;

    public ResponseMessage(int status, int code, String message, String reason) {

        Assert.notNull(reason, "Reason must not be null.");
        Assert.isTrue(status > 0, "Status must not be empty.");

        this.status = status;
        this.code = code;
        this.message = message;
        this.reason = reason;

    }

}

我的问题

我想在我的javax.servlet.Filter授权/身份验证过滤器中返回带有序列化对象(UnauthorizedResponseMessageForbiddenResponseMessage)的JSON.我使用Spring Boot和Jackson库.

I would like to return JSON with serialized objects (UnauthorizedResponseMessage and ForbiddenResponseMessage) in my javax.servlet.Filter authorization / authentication filter. I use Spring Boot and Jackson library.

  1. 如何手动ResponseMessage序列化为其JSON表示形式?
  2. 如何在我的过滤器类中将此JSON写回到客户端?
  1. How can I manually serialize ResponseMessage into its JSON representation?
  2. How can I write out this JSON back to the client in my filter class?

private void throwUnauthorized(ServletResponse res) throws IOException {

    HttpServletResponse response = (HttpServletResponse) res;

    response.reset();
    response.setHeader("Content-Type", "application/json;charset=UTF-8");
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    response.getWriter().write("{\"foo\":\"boo\"}");

}

现在我可以写出JSON但返回HTTP 500,因为:

Now I can write out JSON but HTTP 500 is returned, because:

java.lang.IllegalStateException: getWriter() has already been called for this response
    at org.apache.catalina.connector.Response.getOutputStream(Response.java:544)

推荐答案

使用JacksonObject转换为JSON,以下是示例

Using Jackson convert Object to JSON, the following is an example

ObjectMapper mapper = new ObjectMapper();
String Json =  mapper.writeValueAsString(object);  

这篇关于如何将Java对象序列化为JSON并在servlet过滤器中将其返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆