在传递给 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() {
}
}