Development Suggestions for J2EE data verification

Source: Internet
Author: User

Preface: non-original.

Input data verification: although data verification at the "client" layer can be provided for your convenience, servlet must be used for verification at the server layer. Client Authentication is inherently insecure because these verifications can be easily bypassed, for example, by Disabling javascript. A good design usually requires a web application framework to provide server-side Utility Routines to verify the following:
[1] required fields;
[2] field data type (by default, all http request parameters are strings ");
[3] field length;
[4] field range;
[5] field options;
[6] field mode;
[7] cookie value;
[8] http response.

A good practice is to use the above routine as a static method in the authenticator Utility Class. The following section describes an example of the validator class.
[1] required fields
Java code
// Java example to validate required fields public class validator {... public static boolean validaterequired (string value) {boolean isfieldvalid = false; if (value! = Null & amp; value. trim (). length ()> 0) {isfieldvalid = true;} return isfieldvalid ;}...}... string fieldvalue = request. getparameter ("fieldname"); if (validator. validaterequired (f ieldvalue) {// fieldvalue is valid, continue processing request ...}

[2] The field data type and input parameters in the input web application are not good. For example, all http request parameters or cookie values are of the "string" type ". The developer is responsible for verifying whether the input data type is correct. Use the java basic Wrapper class to check whether the field value can be safely converted to the required basic data type.
Example of how to verify the numeric field (int type:
Java code
// Java example to validate that a f ield is an int number public class validator {... public static boolean validateint (string value) {boolean isfieldvalid = false; try {integer. parseint (value); isfieldvalid = true;} catch (exception e) {isfieldvalid = false;} return isfieldvalid ;}...}... // check if the http request parameter is of type int string f ieldvalue = request. getparameter ("f ieldname"); if (validator. validateint (f ieldvalue) {// f ieldvalue is valid, continue processing request ...}

A good practice is to convert all http Request Parameters to their respective data types. For example, the developer should store the "integervalue" of the request parameter in the request property and use it as shown in the following example:
Java code
// Example to convert the http request parameter to a primitive wrapper data type // and store this value in a request attribute for further processing string f ieldvalue = request. getparameter ("f ieldname"); if (validator. validateint (f ieldvalue) {// convert f ieldvalue to an integer integervalue = integer. getinteger (f ieldvalue); // store integervalue in a request attribute request. setattribute ("f ieldname", integervalue );}... // use the request attribute for further processing integer integervalue = (integer) request. getattribute ("f ieldname ");...

Main java data types to be processed by the application:
Byte
Short
Integer
Long
Float
Double
Date

[3] The Field Length "always" ensures that the input parameters (http request parameters or cookie values) have a minimum length and/or maximum length limit.
The following example verifies that the length of the username field is between 8 and 20 characters:
Java code
// Example to validate the f ield length public class validator {... public static boolean validatelength (string value, int minlength, int maxlength) {string validatedvalue = value; if (! Validaterequired (value) {validatedvalue = "";} return (validatedvalue. length ()> = minlength & amp; validatedvalue. length () <= maxlength );}...}... string username = request. getparameter ("username"); if (validator. validaterequired (username) {if (validator. validatelength (username, 8, 20) {// username is valid, continue further processing ...}}

[4] field range
Always make sure that the input parameters are within the scope defined by the functional requirements.
The following example verifies whether the input numberofchoices is between 10 and 20:
Java code
// Example to validate the f ield range public class validator {... public static boolean validaterange (int value, int min, int max) {return (value >=min & amp; value <= max );}...}... string f ieldvalue = request. getparameter ("numberofchoices"); if (validator. validaterequired (f ieldvalue) {if (validator. validateint (f ieldvalue) {int numberofchoices = integer. parseint (f ieldvalue); if (validator. validaterange (numberofchoices, 10, 20) {// numberofchoices is valid, continue processing request ...}}}

[5] field options web applications usually display a set of options available to users (for example, using the select html Tag ), however, server-side verification cannot be performed to ensure that the selected value is one of the allowed options. Remember that malicious users can easily modify any option value. The selected user value is always verified for the allowed options defined by the functional requirements.
The following example shows how to select an Option List:
Java code
// Example to validate user selection against a list of options public class validator {... public static boolean validateoption (object [] options, object value) {boolean isvalidvalue = false; try {list = arrays. aslist (options); if (list! = Null) {isvalidvalue = list. contains (value) ;}} catch (exception e) {} return isvalidvalue ;}...}... // allowed options string [] options = {"option1", "option2", "option3 "); // verify that the user selection is one of the allowed options string userselection = request. getparameter ("userselection"); if (validator. validateoption (options, userselection) {// valid user selection, continue processing request ...}

[6] field mode
Always check whether the user input matches the pattern defined by the function requirement. For example, if the username field should only allow alphanumeric characters and are case-insensitive, use the following regular expression: ^ [a-za-z0-9] * $.
Example of performing regular expression Verification:
Java code
// Example to validate that a given value matches a specif ied pattern // using the java 1.4 regular expression package import java. util. regex. pattern; import java. util. regexe. matcher; public class validator {... public static boolean matchpattern (string value, string expression) {boolean match = false; if (validaterequired (expression) {match = pattern. matches (expression, value);} return match ;}...}... // verify that the username request parameter is alphanumeric string username = request. getparameter ("username"); if (validator. matchpattern (username, "^ [a-za-z0-9] * $") {// username is valid, continue processing request ...}

[7] the cookie value uses the javax. servlet. http. cookie object to verify the cookie value. The same verification rules that apply to cookie values (as described above) depend on application requirements (such as verification required values, verification length, and so on ).
Example of verifying the required cookie value:
Java code
// Example to validate a required cookie value // first retrieve all available cookies submitted in the http request cookie [] cookies = request. getcookies (); if (cookies! = Null) {// f ind the "user" cookie for (int I = 0; I <cookies. length; ++ I) {if (cookies [I]. getname (). equals ("user") {// validate the cookie value if (validator. validaterequired (cookies [I]. getvalue () {// valid cookie value, continue processing request ...}}}}

[8] http Response
[8-1] filter user input to protect applications from cross-site scripting attacks. Convert sensitive characters into their corresponding character entities to clear html. These are html sensitive characters: <> "'%;) (& amp; +.
The following example filters a specified string by converting a sensitive character to its corresponding character entity:
Java code
// Example to f ilter sensitive data to prevent cross-site scripting public class validator {... public static string f ilter (string value) {if (value = null) {return null;} stringbuf fer result = new stringbuf fer (value. length (); for (int I = 0; I <value. length (); ++ I) {switch (value. charat (I) {case' <': result. append ("& amp; lt;"); break; case '>': result. append ("& amp; gt;"); break; case '"': result. append ("& amp; quot;"); break; case '\ '': result. append ("& amp; #39;"); break; case '%': result. append ("& amp; #37;"); break; case ';': result. append ("& amp; #59;"); break; case '(': result. append ("& amp; #40;"); break; case ')': result. append ("& amp; #41;"); break; case '& amp;': result. append ("& amp;"); break; case '+': result. append ("& amp; #43;"); break; default: result. append (value. charat (I); break;} return result ;}...}... // filter the http response using validator. filter printwriter out = response. getwriter (); // set output response out. write (validator. filter (response); out. close ();

Java servlet api 2.3 introduces a filter that supports interception and conversion of http requests or responses.
The following example uses validator. f ilter to clear the response with the servlet filter:
Java code
// Example to f ilter all sensitive characters in the http response using a java filter. // this example is for registration purposes since it will f ilter all content in the response, including html tags! Public class sensitivecharsfilter implements filter {... public void dofilter (servletrequest request, servletresponse response, filterchain chain) throws ioexception, servletexception {printwriter out = response. getwriter (); responsewrapper wrapper = new responsewrapper (httpservletresponse) response); chain. dofilter (request, wrapper); chararraywriter caw = new chararraywriter (); caw. write (validator. f ilter (wrapper. tostring (); response. setcontenttype ("text/html"); response. setcontentlength (caw. tostring (). length (); out. write (caw. tostring (); out. close ();}... public class charresponsewrapper extends httpservletresponsewrapper {private chararraywriter output; public string tostring () {return output. tostring ();} public charresponsewrapper (httpservletresponse response) {super (response); output = new chararraywriter ();} public printwriter getwriter () {return new printwriter (output );}}}

[8-2] protect cookies
When storing sensitive data in cookies, make sure that you use cookies. setsecure (Boolean flag) sets the cookie security flag in the http Response to instruct the browser to send the cookie using the security protocol (such as https or ssl.
Example of protecting "user" cookies:
Java code
// Example to secure a cookie, I. e. instruct the browser to // send the cookie using a secure protocol cookie = new cookie ("user", "sensitive"); cookie. setsecure (true); response. addcookie (cookie );


The full text is over. If you have any questions, please leave a message for discussion.

Author's "Technical Summary"
 

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.