In Web projects, XSS and SQL injection attacks are usually handled. There are two ways to solve this problem:
Escape illegal characters before data enters the database, and restore invalid characters during update and display.
Escape illegal characters during display
If the project is still in its infancy, we recommend that you use the <c: out> label of jstl to solve the problem of invalid characters. Of course, you still need to process Javascript by yourself. Write a method and execute the following escapeHTML () to parse the data obtained from the server.
Appendix: Javascript method:
String. prototype. escapeHTML = function (){
Return this. replace (// g ,'&'). replace (/>/g, '> '). replace (/</g, '<'). replace (/"/g ,'"');
}
If the project has been developed and you do not want to modify the page in batches, you can use the first method. In this case, you need to use Spring MVC's @ InitBinder and org. apache. commons. lang. propertyEditorSupport, org. apache. commons. lang. 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. escapeHtml (value );}
If (escapeJavaScript) {value = StringEscapeUtils. escapeJavaScript (value );}
If (escapeSQL) {value = StringEscapeUtils. escapeSql (value) ;}setvalue (value );}
}
@ Override
Public String getAsText () {Object value = getValue (); return value! = Null? Value. toString (): "";}
}
Www.2cto.com
When using StringEscapeUtils, you must note that the escapeHtml and escapeJavascript Methods convert Chinese characters to Unicode encoding. If you use the <c: out> label or EL expression to display the characters, they can be restored correctly, however, if a front-end component like Ext is used to display this part of content, it cannot be restored normally. This is why I gave up the first method and directly used the second method.
We have made an EscapeEditor above. We need to bind the Editor to the Controller of Spring to enable the server to automatically transfer special characters after receiving data.
Register @ InitBinder in @ Controller.
@ InitBinder
Public void initBinder (WebDataBinder binder ){
Binder. registerCustomEditor (String. class, new StringEscapeEditor (false, false, false ));
}
This method can be directly put into the abstract Controller class, so that each Controller instance can have this method. So far, the second method has been completed, but the restoration method has not yet. O (distinct _ distinct) O...