Special character escape
Because WEB applications need to be federated to multiple languages, each containing some special characters, for dynamic or tabbed languages, a problem that we often encounter when we need to dynamically construct the content of a language is the escape of special characters. The following are some of the special character types that Web developers most frequently need to escape: HTML special characters; JavaScript special characters; SQL special characters;
If you do not escape these special characters, you will not only be able to break the document structure, but can also raise potential security issues. Spring provides an escape operation tool class for HTML and JavaScript special characters, respectively, Htmlutils and Javascriptutils. HTML Special character escape
<,>,& characters in HTML have special meanings, they are reserved words in the HTML language and therefore cannot be used directly. When using these characters, you should use their escape sequences: &:& ":" <:< >:>
Because HTML pages are a text-structured document in itself, it is highly likely that the entire HTML document will be corrupted if it is exported directly to the Web page with HTML-specific characters. Therefore, it is generally necessary to escape processing of dynamic data, using escape sequences to represent HTML special characters. The following JSP pages dynamically output some variables to an HTML page: Listing 1. No HTML special character escape processing Web page
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "%>
<%!
String userName = "</td><tr></table>";
String address = "\" type=\ "button";
%>
<table border= "1" >
<tr>
<td> name:</td><td><%=username%>< /td>①
</tr>
<tr>
<td> age:</td><td>28</td>
</tr>
</table>
<input value= "<%=address%>" type= "text"/>②
At ① and ②, we output variables directly to an HTML Web page without any escape processing, because these variables might contain some special HTML characters that could disrupt the structure of the entire HTML document. We can understand this problem from a specific output of the above JSP page:
<table border= "1" >
<tr>
<td> Name: </td><td></td><tr></table ></td>
① destroyed <table> structure
</tr>
<tr>
<td> Age: </TD><TD >28</td>
</tr>
</table>
<input value= "" type= "button" type= "text"/ >
② would have been an input box component cynical as a button component
The HTML page after the fusion of dynamic Data has become unrecognizable, first of all, the <table> structure of ① is truncated by the UserName variable containing the HTML special character, resulting in the subsequent <table> code becoming invalid content; second, ② < Input> is replaced by Dynamic data as a component of the button type (type= "button"). To avoid this problem, we need to escape processing of dynamic data that might break the structure of the HTML document. Spring provides us with a simple and applicable HTML Special Word Escape tool class, which is htmlutils. Below, we use a simple example to understand the specific usage of htmlutils: Listing 2. Htmpescapeexample
package Com.baobaotao.escape import org.springframework.web.util.HtmlUtils; public class Htmpescapeexample {pub
Lic static void Main (string[] args) {String specialstr = "<div id=\" testdiv\ ">test1;test2</div>"; String str1 = Htmlutils.htmlescape (SPECIALSTR);
① convert to HTML escape character representation System.out.println (STR1); String str2 = Htmlutils.htmlescapedecimal (SPECIALSTR);
② Convert to Data escape representation System.out.println (STR2); String STR3 = Htmlutils.htmlescapehex (SPECIALSTR);
③ converts to hexadecimal data escape representation System.out.println (STR3);
④ System.out.println (Htmlutils.htmlunescape (STR1)) in the face of the escaped string in reverse operation;
System.out.println (Htmlutils.htmlunescape (str2));
System.out.println (Htmlutils.htmlunescape (STR3)); }
}
HTML can represent HTML special characters not only with common escape sequences, but also with numeric sequences prefixed with # to represent HTML special characters, which are the same in the final display. Htmlutils provides three escape methods: Method Description static string Htmlescape (string input) escape HTML special words as an HTML universal escape sequence; static string Htmlescapedeci Mal (string input) escape the HTML special Word as a decimal data escape sequence with a #, and a static string Htmlescapehex (string input) escape the HTML special Word as a hexadecimal data escape sequence with a #;
In addition, Htmlutils provides a way to restore an escaped content: Htmlunescape (String input), which restores the contents of the above three escape sequences. Run the above code and you'll see the following output:
Str1:<div id="testdiv">test1;test2</div>
str2:& #60;d IV id=& #34;testdiv& #34;& #62;test1;test2& #60;/div& the #62;
str3:& #x3c;d IV id=& #x22;testdiv& #x22;& #x3e;test1;test2& #x3c;/div& the #x3e;
<div id= "Testdiv" >test1;test2</div>
<div id= "Testdiv" >test1;test2</div>
<div Id= "Testdiv" >test1;test2</div>
As long as you use Htmlutils to escape the UserName and address of code Listing 1, the resulting HTML page will not be compromised. JavaScript Special character escape
JavaScript also has some characters that require special handling, and if you embed them directly into JavaScript code, the JavaScript program structure will be corrupted or even be embedded in malicious programs. The special JavaScript characters that need to be escaped are listed below: ': \ ' ': \ ' \: \ * * * * * * paper: \f: \ n column break: \ t enter: \ r rollback character: \b
We demonstrate how dynamic variables can be corrupted by JavaScript programs with a specific example. Let's say we have a JavaScript array variable whose element value is provided through a Java list object, and here is the JSP snippet that completes the operation: Listing 3. Jstest.jsp: JavaScript special characters are not processed
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "%>
<jsp:directive.page import=" java.util.* "/>
<%
List textlist = new ArrayList ();
Textlist.add ("\"; alert (); j=\ "");
%>
<script>
var txtlist = new Array ();
<% for (int i = 0; i < textlist.size (); i++) {%>
txtlist[<%=i%>] = "<%=textlist.get (i)%>";
① does not handle variables that may contain special JavaScript characters
<%}%>
</script>
When the client invokes this JSP page, it will get the following HTML output page:
<script>
var txtlist = new Array ();
Txtlist[0] = ""; alert (); j= ""; ① originally wanted to accept a string that was implanted with a JavaScript code
</script>
Because Java variables containing JavaScript special characters are merged directly into JavaScript code, we would have expected ① to be an ordinary string, but the result would be a JavaScript code, and the page would pop up with an alert window. Imagine what happens if the string in the bold section is "", while (true) alert (), j= "".
Therefore, if JavaScript code in a Web page needs to be dynamically generated by stitching Java variables, it is generally necessary to escape the contents of the variable, which can be done through Spring's javascriptutils. Below, we use Javascriptutils to transform the above code:
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "%>
<jsp:directive.page import=" java.util.* "/> <jsp:directive.page"
Org.springframework.web.util.JavaScriptUtils "/>
<%
List textlist = new ArrayList ();
Textlist.add ("\"; alert (); j=\ "");
%>
<script>
var txtlist = new Array ();
<% for (int i = 0; i < textlist.size (); i++) {%>
① to escape processing before outputting dynamic content
txtlist[<%=i%>] = <%=j Avascriptutils.javascriptescape ("" +textlist.get (i))%> ";
<%}%>
</script>
By escaping processing, the JavaScript code for the resulting web page output of this JSP page does not have a problem:
<script>
var txtlist = new Array ();
Txtlist[0] = "\"; alert (); J=\ "";
The ① bold part is just a plain string, not a JavaScript statement
</script>
SQL Special character escape
It should be said that you don't have disastrous consequences if you don't have special characters for HTML or JavaScript, but if you don't process the special characters in a variable when you dynamically construct SQL statements, you can cause serious security problems such as program vulnerabilities, data theft, data destruction, and so on. There is a large number of articles on SQL injection in the network, interested readers can search the relevant data for in-depth study.
Although the consequences of SQL injection are serious, it is possible to avoid this problem as long as the variables of dynamically constructed SQL statements are escape handled in a special word. Take a look at a classic example of a security breach:
SELECT COUNT (userId) from
t_user
WHERE username= ' "+username+" ' and password = ' "+password+ ';
The above SQL statement determines whether the user provides the correct logon information based on the number of results returned. If the UserName variable is merged directly into the SQL statement without special word escape processing, the hacker can set the UserName to "1" or "1" = ' 1 "Bypassing the user name/password check straight Access to the system.
So unless necessary, it is generally recommended that you construct dynamic SQL statements by PreparedStatement parameter bindings, as this avoids potential security problems with SQL injection. However, it is often difficult to avoid the way of constructing dynamic SQL statements by stitching strings in the application. To prevent others from using special SQL characters to destroy SQL's statement structure or to embed malicious actions, special characters must be escaped before a variable is spliced into an SQL statement. Spring does not provide the appropriate tool class, and you can pass the stringescapeutils of the Jakarta Commons Lang generic class package (Spring/lib/jakarta-commons/commons-lang.jar) Complete this work: Listing 4. Sqlescapeexample
Package com.baobaotao.escape;
Import Org.apache.commons.lang.StringEscapeUtils;
public class Sqlescapeexample {public
static void Main (string[] args) {
String userName = ' 1 ' or ' 1 ' = ' 1 ';
String password = "123456";
UserName = Stringescapeutils.escapesql (userName);
Password = stringescapeutils.escapesql (password);
String sql = "Select COUNT (userId) from T_user WHERE username= '"
+ userName + "' and password = '" + Password + "'";
SYSTEM.OUT.PRINTLN (SQL);
}
In fact, Stringescapeutils not only provides the function of SQL special word escape processing, but also provides methods of escaping and restoring HTML, XML, JavaScript, Java special characters. If you don't mind introducing the Jakarta Commons lang package, we recommend that you use the Stringescapeutils tool class to do the work of special word escape processing.
Back to the first method enter the parameter detection Tool class
Web applications need to be checked for legitimacy after accepting form submissions, and requests will be dismissed if the form data is not valid. Similarly, when we write the method of a class, we often need to check the validation of the method entry, and if the argument does not meet the requirement, the method rejects the post-processing by throwing an exception. For example: There is a way to get an input stream based on the filename: InputStream getData (String file), in order for the method to execute successfully, you must ensure that the file entry parameter cannot be null or whitespace characters, otherwise no subsequent processing is necessary. In this case, the writer of the method usually writes a section of code that detects the incoming parameter in front of the method body, as follows:
Public InputStream getData (String file) {
if (file = = NULL | | | file.length () = = 0| | File.replaceall ("\\s", ""). Length () = = 0) {
throw new IllegalArgumentException ("file into parameter is not a valid filename address");
}
..
}
Code similar to the above instrumentation method is very common, but it is not a good idea to use the method of manually writing detection logic in each of these methods. Read spring source, and you'll find that spring uses a Org.springframework.util.Assert generic class to accomplish this task.
Assert translation is Chinese as "assertion", and the reader who has used JUnit is familiar with this concept, it determines that one actual running value is the same as expected, otherwise throws an exception. Spring's detection of method parameters borrows this concept by providing an Assert class that has many methods of asserting the method's parameters by rule, and satisfies most of the requirements of the method's incoming parameter detection. These assertion methods throw illegalargumentexception when the parameter does not satisfy the requirement. Next, let's take a look at the common assertion method in the Assert class: Assertion method Description Notnull (Object object) throws an exception when object is not null Notnull (object, String message) method allows you to customize exception information through the message. The opposite method of the Notnull () method assertion rule is the IsNull (object)/isnull (Object object, String message), which requires that the argument must be null; IsTrue (Boolean expression)/IsTrue (Boolean expression, String message) when expression is not true to throw an exception; Notempty (Collection Collection)/note Mpty (Collection Collection, String message) throws an exception when the collection does not contain an element. Notempty (map map)/notempty (map map, string message) and Notempty (object[] array, string message)/Notempty (object[) array , String message) to determine the parameters of both the Map and object[] types; haslength (string text)/Haslength (string text, string message) when text is n Throws an exception when the ull or length is 0; hasText (string text)/HasText (string text, string message) text cannot be null and must contain at least one character that is not a space, otherwise an exception is thrown; isinst Anceof (ClAss Clazz, Object obj)/isinstanceof (class type, object obj, String message) If obj cannot be properly styled for Clazz the class specified will throw an exception; isassignabl E (class Supertype, class subtype)/Isassignable (class Supertype, class subtype, String message) subtype must be able to match by type to Supert Ype, otherwise the exception will be thrown;
You can use the Assert assertion class to simplify the code that the method parameters detect, such as InputStream getData (String file) after the Assert assertion class is applied, its code can be simplified to the following form:
Public InputStream getData (String file) {
assert.hastext (filename, "file into parameter is not a valid address");
① using the Spring assertion class for method entry-parameter detection
...
}
It is obvious that the simplicity of the method has been improved by using Spring's Assert instead of the entry-parameter detection logic implemented by the encoding. Assert does not depend on the Spring container, you can boldly use this tool class in your own application.
Back to the first summary of the page
This article describes some of the commonly used spring tool classes, most of which are available in spring based applications and can be used in other applications.
For WEB applications, because there are a lot of associated scripting code, if the code through the way the string concatenation, the dynamic content of the special characters should be escaped processing, otherwise it may have unintended consequences. Spring provides htmlutils and Javascriptutils tool classes to avoid similar problems as long as the dynamic content is escaped by using a tool class before stitching. If you don't mind introducing a third-party package, the Stringescapeutils tool class in the Jakarta Commons lang generic class package may be more appropriate because it provides more comprehensive escape functionality.
Finally, we also introduce the Assert tool class for Spring, an Assert tool class that is a versatile tool class that uses object-oriented methods to resolve the problem of method entry detection, where you can use Assert to check methods in your application.