Recently, XSS injection has been solved. As the servlet version is 2.5 and does not support the HTTPOnly attribute, a tool class is used to implement the HTTPOnly function of cookies. The full category is as follows:
/**
* Cookie tool class, which solves the problem that the HTTPOnly attribute cannot be added before servlet3.0
*
* @ Author Zhang-long
* @ Createtime 2013-6-20
*/
Public class cookieutil {
/**
*
* @ Param response httpservletresponse type response
* @ Param COOKIE: set the HTTPOnly cookie object.
*/
Public static void addhttponlycookie (httpservletresponse response, cookie ){
// Determine whether the object exists null
If (checkobjisnull (response) | checkobjisnull (cookie )){
Return;
}
// Obtain the name, value, maximum survival time, path, domain, and security protocol information in the cookie in sequence.
String cookiename = cookie. getname ();
String cookievalue = cookie. getvalue ();
Int maxage = cookie. getmaxage ();
String Path = cookie. getpath ();
String domain = cookie. getdomain ();
Boolean issecure = cookie. getsecure ();
Stringbuffer strbuffercookie = new stringbuffer ();
Strbuffercookie. append (cookiename + "=" + cookievalue + ";");
If (maxage> = 0 ){
Strbuffercookie. append ("Max-age =" + Cookie. getmaxage () + ";");
}
If (! Checkobjisnull (domain )){
Strbuffercookie. append ("Domain =" + domain + ";");
}
If (! Checkobjisnull (PATH )){
Strbuffercookie. append ("Path =" + path + ";");
}
If (issecure ){
Strbuffercookie. append ("secure; HTTPOnly ;");
} Else {
Strbuffercookie. append ("HTTPOnly ;");
}
Response. addheader ("Set-cookie", strbuffercookie. tostring ());
}
Private Static Boolean checkobjisnull (Object OBJ ){
If (OBJ = NULL ){
Return true;
}
Return false;
}
}
Example:
Cookie cookie1 = new cookie ("N", "cookievalue1 ");
Cookie1.setmaxage (500 );
Cookie cookie2 = new cookie ("cookiename2", "cookievalue2 ");
Cookie cookie3 = new cookie ("cookiename3", "cookievalue3 ");
Cookie3.setsecure (true );
Cookie cookie4 = new cookie ("cookiename4", "cookievalue4 ");
Cookie4.setsecure (true );
Cookieutil. addhttponlycookie (response, cookie1 );
Cookieutil. addhttponlycookie (response, cookie2 );
Cookieutil. addhttponlycookie (response, cookie3 );
Cookieutil. addhttponlycookie (response, cookie4 );
In this example, the red part can be added only when the application uses the HTTPS protocol. Otherwise, the cookie will no longer be read!
After successful addition, view the cookie as follows: