Spring's excellent tool class inventory, special character escape and method entry detection Tool classes

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

Keywords: spring's excellent tool class inventory, special character escape and method entry Detection Tool class

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. <!--START RESERVED for FUTURE use include files--><!--include Java Script Once we verify teams wants to use this And it would work on DBCS and Cyrillic characters--><!--end RESERVED for FUTURE use INCLUDE files-->

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: &:&amp; ":&quot; <:&lt; >:&gt;

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 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 <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

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=/" Testdi v/">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:&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: ':/' ':/'/://Paper WRAP:/F linefeed:/n Column break:/T 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 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%>] = <%= 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.

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.