Java programs resist xss attacks

Principle: All data requested by the front end is escaped and then stored in the database

Import the hutool-all package

<!--Data escape to prevent xss attacks-->        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.2</version>
        </dependency>

2.config XssHttpServletRequestWrapper

/**
*@ description escape the data requested by request to prevent XSS attack
*Home. PHP? Mod = Space &amp; uid = 365491 2021 / 7 / 4 10:05 am
*/
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
     public XssHttpServletRequestWrapper(HttpServletRequest request) {
         super(request);
    }
    /**
     *  Override the getparameter method, escape with htmlutil, and then return
     */
    @ Override
     public String getParameter(String name) {
         String value= super.getParameter(name);
         if(!StrUtil.hasEmpty(value)){
             value=HtmlUtil.filter(value);
        }
         return value;
    }
    /**
     *  Override the getparametervalues method,
     *  Traverse each value, escape with htmlutil, and then return
     */
    @ Override
     public String[] getParameterValues(String name) {
         String[] values= super.getParameterValues(name);
         if(values!=null){
             for (int i=0;i<values.length;i++){
                 String value=values[i];
                 if(!StrUtil.hasEmpty(value)){
                     value=HtmlUtil.filter(value);
                }
                 values[i]=value;
            }
        }
         return values;
    }
    /**
     *  Override the getparametermap method,
     *  Get all K-V key value pairs and receive them with LinkedHashMap,
     *  Key remains unchanged, value is escaped with htmlutil, and then returned
     */
    @ Override
     public Map<String, String[]> getParameterMap() {
         Map<String, String[]> parameters = super.getParameterMap();
         LinkedHashMap<String, String[]> map=new LinkedHashMap();
         if(parameters!=null){
             for (String key:parameters.keySet()){
                 String[] values=parameters.get(key);
                 for (int i = 0; i < values.length; i++) {
                     String value = values[i];
                     if (!StrUtil.hasEmpty(value)) {
                         value = HtmlUtil.filter(value);
                    }
                     values[i] = value;
                }
                 map.put(key,values);
            }
        }
         return map;
    }
    /**
     *  Override the getheader method, escape with htmlutil, and then return
     */
    @ Override
     public String getHeader(String name) {
         String value= super.getHeader(name);
         if (!StrUtil.hasEmpty(value)) {
             value = HtmlUtil.filter(value);
        }
         return value;
    }
    @ Override
     public ServletInputStream getInputStream() throws IOException {
        /**
         *  Get the data stream and splice it through StringBuffer,
         *  Read to the line and use StringBuffer because multiple threads will request at the same time. Ensure the safety of threads
         */
         InputStream in= super.getInputStream();
         InputStreamReader reader=new InputStreamReader(in, Charset.forName("UTF-8"));
         BufferedReader buffer=new BufferedReader(reader);
         StringBuffer body=new StringBuffer();
         String line=buffer.readLine();
         while(line!=null){
             body.append(line);
             line=buffer.readLine();
        }
         buffer.close();
         reader.close();
         in.close();
        /**
         *  Transfer the obtained map and save it to another map
         */
         Map<String,Object> map=JSONUtil.parseObj(body.toString());
         Map<String,Object> result=new LinkedHashMap<>();
         for(String key:map.keySet()){
             Object val=map.get(key);
             if(val instanceof String){
                 if(!StrUtil.hasEmpty(val.toString())){
                     result.put(key,HtmlUtil.filter(val.toString()));
                }
            } else {
                 result.put(key,val);
            }
        }
         String json=JSONUtil.toJsonStr(result);
         ByteArrayInputStream bain=new ByteArrayInputStream(json.getBytes());
        // For anonymous internal classes, you only need to override the read method and create the escaped value as a servletinputstream object
         return new ServletInputStream() {
            @ Override
             public int read() throws IOException {
                 return bain.read();
            }
            @ Override
             public boolean isFinished() {
                 return false;
            }
            @ Override
             public boolean isReady() {
                 return false;
            }
            @ Override
             public void setReadListener(ReadListener readListener) {
            }
        };
    }
}

3.deploy XssFilter

/**
*@ description escape the data requested by request to prevent XSS attack
*Home. PHP? Mod = Space &amp; uid = 365491 2021 / 7 / 4 10:05 am
*/
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
     public XssHttpServletRequestWrapper(HttpServletRequest request) {
         super(request);
    }
    /**
     *  Override the getparameter method, escape with htmlutil, and then return
     */
    @ Override
     public String getParameter(String name) {
         String value= super.getParameter(name);
         if(!StrUtil.hasEmpty(value)){
             value=HtmlUtil.filter(value);
        }
         return value;
    }
    /**
     *  Override the getparametervalues method,
     *  Traverse each value, escape with htmlutil, and then return
     */
    @ Override
     public String[] getParameterValues(String name) {
         String[] values= super.getParameterValues(name);
         if(values!=null){
             for (int i=0;i<values.length;i++){
                 String value=values[i];
                 if(!StrUtil.hasEmpty(value)){
                     value=HtmlUtil.filter(value);
                }
                 values[i]=value;
            }
        }
         return values;
    }
    /**
     *  Override the getparametermap method,
     *  Get all K-V key value pairs and receive them with LinkedHashMap,
     *  Key remains unchanged, value is escaped with htmlutil, and then returned
     */
    @ Override
     public Map<String, String[]> getParameterMap() {
         Map<String, String[]> parameters = super.getParameterMap();
         LinkedHashMap<String, String[]> map=new LinkedHashMap();
         if(parameters!=null){
             for (String key:parameters.keySet()){
                 String[] values=parameters.get(key);
                 for (int i = 0; i < values.length; i++) {
                     String value = values[i];
                     if (!StrUtil.hasEmpty(value)) {
                         value = HtmlUtil.filter(value);
                    }
                     values[i] = value;
                }
                 map.put(key,values);
            }
        }
         return map;
    }
    /**
     *  Override the getheader method, escape with htmlutil, and then return
     */
    @ Override
     public String getHeader(String name) {
         String value= super.getHeader(name);
         if (!StrUtil.hasEmpty(value)) {
             value = HtmlUtil.filter(value);
        }
         return value;
    }
    @ Override
     public ServletInputStream getInputStream() throws IOException {
        /**
         *  Get the data stream and splice it through StringBuffer,
         *  Read to the line and use StringBuffer because multiple threads will request at the same time. Ensure the safety of threads
         */
         InputStream in= super.getInputStream();
         InputStreamReader reader=new InputStreamReader(in, Charset.forName("UTF-8"));
         BufferedReader buffer=new BufferedReader(reader);
         StringBuffer body=new StringBuffer();
         String line=buffer.readLine();
         while(line!=null){
             body.append(line);
             line=buffer.readLine();
        }
         buffer.close();
         reader.close();
         in.close();
        /**
         *  Transfer the obtained map and save it to another map
         */
         Map<String,Object> map=JSONUtil.parseObj(body.toString());
         Map<String,Object> result=new LinkedHashMap<>();
         for(String key:map.keySet()){
             Object val=map.get(key);
             if(val instanceof String){
                 if(!StrUtil.hasEmpty(val.toString())){
                     result.put(key,HtmlUtil.filter(val.toString()));
                }
            } else {
                 result.put(key,val);
            }
        }
         String json=JSONUtil.toJsonStr(result);
         ByteArrayInputStream bain=new ByteArrayInputStream(json.getBytes());
        // For anonymous internal classes, you only need to override the read method and create the escaped value as a servletinputstream object
         return new ServletInputStream() {
            @ Override
             public int read() throws IOException {
                 return bain.read();
            }
            @ Override
             public boolean isFinished() {
                 return false;
            }
            @ Override
             public boolean isReady() {
                 return false;
            }
            @ Override
             public void setReadListener(ReadListener readListener) {
            }
        };
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *