Spring REST service: retrieving JSON from Request

后端 未结 11 575
甜味超标
甜味超标 2020-11-27 04:35

I am building a REST service on Spring 3.1. I am using @EnableWebMVC annotation for that. Since my service will only be accepting JSON requests, I would also like to dump th

11条回答
  •  有刺的猬
    2020-11-27 04:46

    You need to implement the requestWrapper as follows:

    public class DocVerificationRequestWrapper extends HttpServletRequestWrapper {
     private final String body;
     public DocVerificationRequestWrapper(HttpServletRequest request) throws IOException {
       super(request);
       StringBuilder stringBuilder = new StringBuilder();
       BufferedReader bufferedReader = null;
       try {
         InputStream inputStream = request.getInputStream();
         if (inputStream != null) {
           bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
           char[] charBuffer = new char[128];
           int bytesRead = -1;
           while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
             stringBuilder.append(charBuffer, 0, bytesRead);
           }
         } else {
           stringBuilder.append("");
         }
       } catch (IOException ex) {
           throw ex;
       } finally {
         if (bufferedReader != null) {
           try {
             bufferedReader.close();
           } catch (IOException ex) {
             throw ex;
           }
         }
       }
       body = stringBuilder.toString();
     }
    
     @Override
     public ServletInputStream getInputStream() throws IOException {
       final ByteArrayInputStream byteArrayInputStream = new     ByteArrayInputStream(body.getBytes());
       ServletInputStream servletInputStream = new ServletInputStream() {
         public int read() throws IOException {
           return byteArrayInputStream.read();
         }
    
        @Override
        public boolean isFinished() {
            // TODO Auto-generated method stub
            return false;
        }
    
        @Override
        public boolean isReady() {
            // TODO Auto-generated method stub
            return false;
        }
    
        @Override
        public void setReadListener(ReadListener listener) {
            // TODO Auto-generated method stub
    
        }
       };
       return servletInputStream;
     }
    
     @Override
     public BufferedReader getReader() throws IOException {
       return new BufferedReader(new InputStreamReader(this.getInputStream()));
     }
    
     public String getBody() {
       return this.body;
     }
    }
    

    and then inside the chain.doFilter method of filter class pass the requestWrapper object instead of the request object as follows:

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
    
        logger.info("checking token in filter");
        HttpServletRequest request = (HttpServletRequest) arg0;
    
        DocVerificationRequestWrapper myRequestWrapper = new DocVerificationRequestWrapper((HttpServletRequest) request);
    
        String body = myRequestWrapper.getBody();
        logger.info("body = "+body);
        Token token = null;
        try {
            JSONObject jsonObj = new JSONObject(body);
            JSONObject tokenObj = (JSONObject) jsonObj.get("token");
            Gson gson = new Gson();
            token = gson.fromJson(tokenObj.toString(), Token.class);
    
            if(null != token) {
                    if(userVerificationService==null){
                    ServletContext servletContext = request.getServletContext();
                    WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
                    userVerificationService = webApplicationContext.getBean(UserVerificationService.class);
                }
                    String verStatus = userVerificationService.verifyUser(token);
                    logger.info("verStatus = "+verStatus);
                    if(verStatus != null && verStatus.equalsIgnoreCase("success")) {
                        chain.doFilter(myRequestWrapper, response); //here replacing request with requestWrapper 
                    }else
                        logger.error("Invalid token");
            }else {
                    logger.error("token missing.");
            }
        } catch (JSONException e) {
                logger.error("exception in authetication filter " + e);
        }
    }
    

    Thus solving the IOStream closed exception.

提交回复
热议问题