Not only does Spring provide a full-featured application development framework, but it also has a number of tool classes that you can use directly when you write a program, not only in spring applications but also in other applications, most of which can be detached from spring The frame is used. Knowing what handy tool classes are available in Spring and using them appropriately when you write them will help improve development efficiency and enhance code quality.
In this two-part article, we'll pick out the handy tools classes from a number of Spring tool classes. Part 1th describes the tool classes related to file resource operations and Web. The special character escape and method entry instrumentation tool classes are introduced in part 2nd.
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. 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"/>
② will originally be 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 {public static void main (string[] args) {String specialstr = "<div id=\" Te
Stdiv\ ">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. The Htmlutils provides three escape methods:
Method |
Description |
static string Htmlescape (String input) |
Escape HTML special character as HTML universal escape sequence; |
static string Htmlescapedecimal (String input) |
Escape the HTML special character as a decimal data escape sequence with #; |
static string Htmlescapehex (String input) |
Escape the HTML special character 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 by 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 methods in the Assert class:
Assertion Method |
Description |
Notnull (Object object) |
When an object is not NULL to throw an exception, the Notnull (object, String message) method allows you to customize the 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 incoming parameter must be null; |
IsTrue (Boolean expression)/IsTrue (Boolean expression, String message) |