Spring-spring's excellent tool class inventory, part 2nd: Special character escape and method entry Detection Tool class

Source: Internet
Author: User
Tags assert button type object object sql injection javascript array

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 the special character types that Web developers most often face 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:

&:&amp;
:&quot;
<:&lt;
>:&gt;
Because HTML pages are themselves a text-structured document, it is highly likely that the entire HTML document will be corrupted if it is exported directly to a 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 Web 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 the structure of the <table>
</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


After merging dynamic data, HTML Web pages have been unrecognizable, first ① <table> structure is truncated by userName variables containing HTML special characters, resulting in the <table> code becoming invalid content, followed by ② <inpu T> 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 use 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=/" testdiv/">test1;test2</div>";
String str1 = Htmlutils.htmlescape (SPECIALSTR); ① conversion to HTML escape character representation
System.out.println (STR1);

String str2 = Htmlutils.htmlescapedecimal (SPECIALSTR); ② conversion to data escape representation
System.out.println (STR2);

String STR3 = Htmlutils.htmlescapehex (SPECIALSTR); ③ conversion to hexadecimal data escape representation
System.out.println (STR3);

④ the string behind the escape in reverse operation
System.out.println (Htmlutils.htmlunescape (str1));
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
The static string Htmlescape (string input) escape the HTML special Word as an HTML universal escape sequence;
The static string Htmlescapedecimal (string input) escape the HTML special Word as a decimal data escape sequence with a #;
The 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:&lt;div id=&quot;testdiv&quot;&gt;test1;test2&lt;/div&gt;
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:

' :/'
" :/"
/ ://
Walk Paper Change page:/F
Line Wrap:/n
Column breaks:/t
Carriage return:/R
Fallback character:/b

We demonstrate how dynamic variables can be corrupted by JavaScript programs with a specific example. Suppose 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 into 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 import= "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 prior to outputting dynamic content
TXTLIST[<%=I%>] = "<%=javascriptutils.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) To 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 top of the page

Method into 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 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) throws an exception when object is not NULL, 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) when expression is not true to throw an exception;
Notempty (Collection Collection)/Notempty (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 judge the incoming parameters of the MAP and object[] types, respectively;
Haslength (string text)/Haslength (string text, String message) throws an exception when text is null or length 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;
Isinstanceof (class Clazz, Object obj)/isinstanceof (class type, object obj, String message) If obj cannot be properly styled for Clazz the class specified will be thrown Out of the ordinary;
Isassignable (class Supertype, class subtype)/Isassignable (class Supertype, class subtype, String message) subtype must be able to press The type matches the supertype, otherwise an exception is 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 top of the page

Summary

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.

This article from Csdn Blog, reproduced please indicate the source: http://blog.csdn.net/oycn0755/archive/2008/01/15/2045305.aspx

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.