Spring Interceptor预处理方法和httpservlet响应

时间:2015-09-17 18:08:14

标签: spring spring-mvc spring-boot interceptor

我必须为我的localresourcereader控制器方法实现拦截器。我正在验证请求参数中提供的文件路径。如果文件存在,那么prehandle()返回true否则我想返回自定义的错误消息bean(错误代码和错误消息)。如果preHandle()返回false但是没有可用于将响应主体设置为对象的方法,则可以返回HttpServletResponse对象。 response.getOutputStream()。write(byte [])是非常低级别的,即使我将内容类型设置为application / json,也不会给出正确的json响应。

public class FileInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request,
    HttpServletResponse response, Object handler) throws Exception {

        System.out.println("Validate file path");
        String filePath = request.getParameter("filePath");

        if(!StringUtils.hasText(filePath)){
            setMandatoryParameterMissingException(response);
            return false;
        }

        File file = new File(filePath);
        if(!file.exists()){
            setFileNotFoundResponse(response);
        }
        return file.exists();
    }

    private void setMandatoryParameterMissingException(HttpServletResponse response) throws IOException {
        response.setContentType("application/json");
        ErrorBean errorBean = new ErrorBean("E100","filePath is mandatory parameter");
        response.getOutputStream().write(serialize(errorBean));
    }

    private void setFileNotFoundResponse(HttpServletResponse response) throws IOException {
        response.setContentType("application/json");
        ErrorBean errorBean = new ErrorBean("E101","File Not Found");
        response.getOutputStream().write(serialize(errorBean));
    }

    private byte[] serialize(Object obj) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ObjectOutputStream os = new ObjectOutputStream(out);
        os.writeObject(obj);
        byte[] array =  out.toByteArray();
        out.close();
        os.close();
        return array;
    }
}

0 个答案:

没有答案