SpringMVC 跨站脚本攻击防护(防止XSS攻击)

SpringMVC 跨站脚本攻击防护(防止XSS攻击)

  1. 定义一个基础controller
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.multipart.MultipartFile;

/**
* Controller - 基类
*/
public class BaseController {
   @InitBinder
   protected void initBinder(WebDataBinder binder) {
       binder.registerCustomEditor(MultipartFile.class, new StringTrimmerEditor(true));
       binder.registerCustomEditor(String.class, new HtmEscapeEditor(true));
   }
}

HtmEscapeEditor

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.web.util.HtmlUtils;

/**
* HTML转义(防止XSS攻击)
*/
public class HtmEscapeEditor extends StringTrimmerEditor {

  public HtmEscapeEditor(boolean emptyAsNull) {
      super(emptyAsNull);
  }

  @Override
  public void setAsText(String text) {
      super.setAsText(text);
      String value = (String) getValue();
      if (StringUtils.isNotEmpty(value)) {
          setValue(HtmlUtils.htmlEscape(value));
      }
  }

}

2.让所有的controller类都继承BaseController.
3.所有的controller所提交的信息首先要进入BaseController.initBinder方法将输入信息进行转义。
4.使用HtmlUtils.htmlUnescape()方法可以进行解码

猜你喜欢

转载自blog.csdn.net/Michean/article/details/85620419