springboot, springmvc 예방 xss 공격 사용자 정의 WebBindingInitializer 구현 클래스

2993 단어 자바
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

/**
 *         :
 * 
 * 		          
 * 
 */
@Configuration
public class MyWebBindingInitializer implements WebBindingInitializer {
	
	private static final WebBindingInitializer webBindingInitializer = new MyWebBindingInitializer();

	@Override
	public void initBinder(WebDataBinder binder, WebRequest request) {
		binder.registerCustomEditor(String.class, new StringEscapeEditor(true, true, false));
	}
	
	
	@Autowired
	public void getWebBindingInitializer(RequestMappingHandlerAdapter requestMappingHandlerAdapter){
		requestMappingHandlerAdapter.setWebBindingInitializer(webBindingInitializer);
	}

}
import java.beans.PropertyEditorSupport;

import org.apache.commons.lang3.StringEscapeUtils;

public class StringEscapeEditor extends PropertyEditorSupport {

	private boolean escapeHTML;
	private boolean escapeJavaScript;
	private boolean escapeSQL;

	public StringEscapeEditor() {
		super();
	}

	public StringEscapeEditor(boolean escapeHTML, boolean escapeJavaScript, boolean escapeSQL) {
		super();
		this.escapeHTML = escapeHTML;
		this.escapeJavaScript = escapeJavaScript;
		this.escapeSQL = escapeSQL;
	}

	@Override
	public void setAsText(String text) {
		if (text == null) {
			setValue(null);
		} else {
			String value = text;
			if (escapeHTML) {
				value = StringEscapeUtils.escapeHtml3(value);
			}
			if (escapeJavaScript) {
				value = this.escapeScript(value);
			}
			if (escapeSQL) {
				value = this.escapeSql(value);
			}
			setValue(value);
		}
	}

	@Override
	public String getAsText() {
		Object value = getValue();
		return value != null ? value.toString() : "";
	}
	
	/**
	 *   SQL      
	 * @param value
	 * @return
	 */
	public String escapeSql(String value) {
		return value.replaceAll("('.+--)|(--)|(\\|)|(%7C)", "");
	}
	
	/**
	 *   js  
	 * @param value
	 * @return
	 */
	public String escapeScript(String value){
		value = value.replace("script", "\\script").replace("/script", "\\/script");
		return value;
	}
}

springmvc 프레임 워 크 라면:
springMVC - servlet. xml 파일 에 설정 하고 제거 해 야 합 니 다.
@Configuration

주해
springMVC - servlet 설정:

	  
          
          
              
          
    

좋은 웹페이지 즐겨찾기