title: Spring Interceptor prehandle method and httpservletresponse
body: <p>I have to implement interceptor for my localresourcereader controller methods.I am validating filepath provided in request parameter. if file exist then prehandle() returns true else I want to return customised error message bean (error code and error message). You can return HttpServletResponse object if preHandle() return false but there is no method available to set response body as object. response.getOutputStream().write(byte[]) is very low level and does not give correct json response even if I set content type as application/json.</p>
  
  <pre><code>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;
      }
  }
  </code></pre>