0

在传递给 Controller 之前,我正在使用 Spring Delegating 代理过滤器在 Filter 类中进行一些验证。在验证失败时,我打算以 json 格式返回用户定义的“ErrorMessage”对象,从过滤器返回 json 的最佳方法是什么?可能吗?我尝试通过在输出中写入字符串来返回字符串,它工作正常,但我似乎无法弄清楚如何以 json 格式返回对象

代码片段:

application context xml -
<bean class="com.company.rest.ValidationFilter" id="validationFilter" />

ValidationFilter -

public class ValidationFilter implements Filter {
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
}

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    final HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    final String acceptHeader = httpServletRequest.getHeader("Accept");
    if (PAYLOAD_FORMATS.jsonp.getContentType().equalsIgnoreCase(acceptHeader)) {
        final OutputStream outputStream = httpServletResponse.getOutputStream();
        final GenericResponseWrapper wrapper = new GenericResponseWrapper(httpServletResponse);

    //Some validation
        if (ifValidationFails) {
            httpServletResponse.setStatus(400);
            httpServletResponse.addHeader("cause", "Required String parameter is not present.");   
            //Need to return this object in response
            final ExceptionWrapper exception = new ExceptionWrapper();
            exception.setErrorMessage("Required String parameter is not present");
            //Returning string works fine 
            outputStream.write(new String("Required String parameter is not present").getBytes());
        } else {
            chain.doFilter(request, wrapper);

            outputStream.write(new String("test" + "(").getBytes());
            outputStream.write(wrapper.getData());
            outputStream.write(new String(");").getBytes());
        }
        wrapper.setContentType("text/javascript;charset=UTF-8");
        outputStream.close();
    } else {
        chain.doFilter(request, response);
    }

}

@Override
public void destroy() {
}
}
4

1 回答 1

0

过滤器是相当低级的 Servlet API 的一部分——Spring MVC 建立在该标准之上。你没有得到 Spring 家伙为自动序列化 POJO 而编写的所有好东西。尽管我认为可以手动将必要的组件连接在一起。

我建议查看使用 Spring MVC 中的 @Valid 注释存在的声明性验证:http: //static.springsource.org/spring/docs/current/spring-framework-reference/html/validation.html#validation-beanvalidation

于 2013-01-25T23:32:49.383 回答