English Original: Top 7 Features in Tomcat 7:the New and the improved
Tomcat's 7 introduces many new features and enhancements to existing features. Many articles list the new features of Tomcat 7, but most do not explain them in detail, or point out their shortcomings, or provide code examples. This article will clearly describe and comment on the seven most salient features and new features in Tomcat 7, rather than just listing new features. This article also provides examples of code to make it easier for you to get a better understanding of it.
This article is divided into two parts, namely "Tomcat 7 new features" and "Tomcat 7 enhanced features".
new features of TOMCAT 7
1 use random numbers to prevent cross-site scripting attacks.
2 changed the mechanism of Jessionid in security authentication to prevent the session attack.
3 Detection and prevention of memory leaks
4 Use aliases outside the war file to store static content.
Enhancements to TOMCAT 7
5 to Servlet 3.0,jsp 2.2 and Jsp-el 2. 2 of support
6 easier to embed Tomcat into the app, like JBoss
7 Asynchronous logging
According to the manager of the Mark Thomas,tomcat 7 Committee, the most notable three features of Tomcat 7 are servlet 3.0, memory leak detection and enhanced security features.
The Tomcat 7 Example program contains the project files of Eclipse and the build files of ant to facilitate the construction of the war file. One of the Eclipse engineering files has an example code that describes some of the new features of Tomcat 7.
Let's start with the introduction.
New features of TOMCAT 7
1, use random number to prevent cross-site request forgery attack.
Wikipedia defines a cross site request forgery attack (FORGERY,CSRF) as: "A malicious attack that affects web applications. CSRF allows users to be forced to execute malicious code when they enter a trustworthy Web page.
The classic way to prevent CSRF attacks is to use random numbers, defined in Wikipedia as "using random or pseudo-random numbers embedded in the authentication protocol to ensure that the old cannot be exploited in later replay attacks." ”
There is a servlet filter in Tomcat 7 that stores random numbers in a seesion session after each request is processed by the user. This random number must be used as a parameter in each request. The servlet filter then checks whether the random number in the request is the same as the random number stored in the user session. If they are the same, the request is judged from the specified Web site. If they are different, the request is considered to be issued from another site and will be rejected.
This servlet filter is very simple, and here is the excerpt from the Tomcat source code Csrfpreventionfilter document:
Java code
- Public class Csrfpreventionfilter extends Filterbase {
- Public void DoFilter (ServletRequest request, servletresponse response,
- Filterchain chain) throws IOException, servletexception {
- String previousnonce = Req.getparameter (Constants.csrf_nonce_request_param);
- String expectednonce = (string) req.getsession (true). getattribute (Constants.csrf_nonce_session_attr_name);
- if (expectednonce! = null &&!expectednonce.equals (previousnonce)) {
- Res.senderror (Httpservletresponse.sc_forbidden);
- Return
- }
- String newnonce = Generatenonce ();
- Req.getsession (True). SetAttribute (Constants.csrf_nonce_session_attr_name, newnonce);
So each URL address has a random number extracted from the user session, and the following is an example of the JSTL used:
In the past, Jstl constructs a link in this way:
< c:url var= "url" value= "/show" >
< C:param name= "id" value= "0"/>
</c:url >
< a href= "${show}" >Show</a >
And now you can do this:
< c:url var= "url" value= "/show" >
< C:param name= "id" value= "0"/>
< C:param name= "Org.apache.catalina.filters.CSRF_NONCE" value= "${session.org.apache.catalina.filters.csrf_ NONCE} "/>
</c:url >
A specific example can be found in the Tomcat 7 example of the demo, this filter can be configured in Web. XML, after configuration, all accesses such as http://localhost:8080/tomcat7demo/csrf/must take parameters, A 403 Forbidden error will occur without the argument.
Of course, the disadvantage of this approach is that all links must carry this random number.
2, changed the security certification in the Jessionid mechanism to prevent the session attack.
Session hijacking attacks are usually the following:
1 A malicious attacker accesses a webpage first, because the cookie is stored in the browser as a jsession ID, and even if the attacker does not log in, he can forge an address with a jsession ID and send it to the victim, such as
Http://example.com/login?JESSIONID=qwerty)
2 Victims Click this link with Jsessionid, which prompts you to enter the verification information and then log into the system.
3 The attacker now uses the Jsessionid link to log into the system as the victim's identity.
It is easy for an attacker to add jsessionid to the URL and send it through a malicious form, and for a more detailed description of the session hijacking attack, refer to the Acros Security Organization's white paper "Session fixation Vulnerability in web-based applications ".
The TOMCAT 7 solution to this is a patch that changed the Jsessionid after validation. This patch is primarily used in Tomcat 7, but is also available in Tomcat 5 and 6, but only slightly different.
According to Mark Thomas, after applying the patch for Tomcat 7:
Tomcat security no longer becomes vulnerable by default because the session has changed after validation
• If the user changes the default settings (for example, the application cannot handle the changed session ID), the risk is minimized because in servlet 3, you can disable session tracking in the URL.
In Tomcat 5 and Tomcat 6, after applying a patch:
• Prevents session hijacking attacks, as it allows Tomcat to change the session ID after verification.
• If the application cannot handle the changed session ID, you can reduce the risk by writing a custom filter to check the Request.isrequestedsessionidfromurl () and its returned results.
All of these changes were made by tomcat behind the scenes, and developers didn't have to bother.
3. Detection and prevention of memory leaks
Developers often encounter Pemgen errors when deploying their written programs to production environments: OutOfMemoryError. This is caused by a memory leak. Usually the developer solves the problem by increasing the size of the PermGen memory or restarting Tomcat.
TOMCAT 7 contains a new feature that solves some of the PermGen memory leaks by removing the reference objects that cannot be garbage collected. This feature is very handy for programmers deploying applications in their development environment, as programmers can deploy new war files in the development environment in order to save time by not restarting Tomcat. In a production environment, the best advice is to stop Tomcat, then clear the directory file under work and redeploy the app.
Of course, memory leak detection and prevention of this feature is not perfect now, or there are situations where Tomcat cannot detect memory leaks and fixes, so the best way for a production environment is to stop Tomcat, then clear the directory files under work and redeploy the app.
The Mark Thomas Parsing application or library program will trigger a memory leak in the following scenarios:
Registration of JDBC drivers
• Some log frames
• Saved objects in threadlocals without deleting them
• Thread was started but not stopped
Where there are memory leaks in the Java API include:
1. Using the Javax.imageio API (Google WEB Toolkit will be used)
2. Using Java.beans.Introspector.flushCaches ()
3. Using the XML parser
4. Using RMI Remote method calls
5. Reading resources from the Jar file
4. Use aliases outside the war file to store static content
Web applications require static resource files such as Css,javascript and video files, image files, and so on. They are usually packaged in a war file, which increases the size of the war file and causes a lot of repetitive loading of static resources. A good solution is to use the Apache HTTP server to manage these static file resources, here is an Apache httpd.conf file configuration excerpt:
< Directory "/home/avneet/temp/static" >
Order Allow,deny
Allow from all
</directory >
Alias/static "/home/avneet/temp/static"
The above settings allow access to the resources placed under/home/avneet/temp/static when accessing http://localhost/static.
Allows Tomcat to parse the absolute path by using the new aliases property, indicating the location of the static file resource, either by using Classloader.getresourceasstream ('/static/... ') or by embedding it in the link. The following is an example of a configuration in context.xml:
< XML version= "1.0" encoding= "UTF-8"? >
< Context path= "/tomcat7demo" aliases= "/static=/home/avneet/temp/static" >
</context >
Suppose/home/avneet/temp/static This folder has a picture bg.png, if the war file is deployed in Tomcat7demo name, you can access this image in the following three ways
1 Direct Access
Http://localhost:8080/tomcat7demo/static/bg.png
2 Access:< img src= "/tomcat7demo/static/bg.png"/> in HTML link
3 Access via Java code: Bytearrayinputstream Bais = (bytearrayinputstream) getservletcontext (). getResourceAsStream ("/static/ Bg.png ");
The advantage of using aliases is that it can be used in place of Apache's httpd.conf settings and can be accessed within the scope of the servlet container and does not require Apache.
Enhanced features of TOMCAT 7
5, to servlet 3.0,jsp 2.2 and Jsp-el 2. 2 of Support
The enhanced features of Servlet 3 are:
• Annotations annotations can be used in Pojo or filter filters (no more setting in Web. xml)
• The Web. Xml chunking can be managed. That is, users can write multiple XML files and eventually assemble them in web. NET, which greatly reduces the complexity of Web. XML to enhance readability. For example, each of Struts.jar and Spring-mvc.jar can have a web-fragment.xml. Developers no longer need to configure them in Web. XML, the jar files in Web-fragment.xml are loaded automatically, and Struts/spring-mvc Servlets and filters are automatically assembled.
• Asynchronous processing of Web requests----This feature is already in Tomcat 6 and is now normalized in the servlet 3 standard in Tomcat 7, enabling Web applications that use asynchronous I/O to be ported to different web containers. Asynchronous processing uses non-blocking I/O, and each HTTP connection does not require a corresponding thread. Fewer threads can provide services for more connections. This is useful for scenarios that require long-time calculations to return results, such as generating reports, Web Servce calls, and so on.
• Secure Enhancement---Servlet 3.0 now uses SSL to enhance the tracking of session sessions instead of the original cookie and URL rewriting.
6. More easily embed Tomcat into the app
Tomcat 7 can now be embedded in the application and can be set and started dynamically through the program. Many configurations, like in Catalina_home/conf/server.xml, can now be set dynamically with the program. Before Tomcat 7, Tomcat 6 provided an embedded class that would be easy to configure with Tomcat. In Tomcat 7, however, this class has been deprecated. This new Tomcat 7 class, uses several default configuration elements, and provides an easier and simpler way to embed Tomcat.
Here are some of the related properties and configurations in Catalina_home/conf/server.xml:
< Server >
< Service >
< Connector port= "8080 >
< Engine >
< Host appbase= "/home/avneet/work/tomcat7demo/dist"/>
</engine >
</connector >
</service >
</server >
We can use the program to make dynamic settings:
Final String catalina_home = "/home/avneet/work/temp/tomcat7demo/";
Tomcat tomcat = new Tomcat ();
Tomcat.setbasedir (Catalina_home);
Tomcat.setport (8080);
Tomcat.addwebapp ("/tomcat7demo", Catalina_home + "/webapps/tomcat7demo.war");
Tomcat.start ();
System.out.println ("Started Tomcat");
Tomcat.getserver (). await (); Keeps Tomcat running until it's shut down
Webapp Tomcat7demo accessible at http://localhost:8080/tomcat7demo/
7. Asynchronous Logging
TOMCAT 7 now includes an asynchronous log recorder (Asyncfilehandler). Asyncfilehandler inherits the Filehandler class and can replace Filehandler. With Asyncfilehandler, you only need to replace the Filehandler with Asyncfilehandler in Catalina_home/conf/logging.properties. Note that asynchronous logs cannot work with LOG4.
When a log is sent to Asyncfilehandler, the log is added to the queue (Java.util.concurrent.LinkedBlockingDeque) and the information of the method call is returned immediately without waiting for I/O to write to disk. When the ClassLoader loads Asyncfilehandler, a separate thread is started, and the thread reads the log information from the queue and writes it to the disk
The benefit of this approach is that logging requests and processing do not appear to be slow if I/O is slow (for example, if the log is to be kept on a remote device).
Asyncfilehandler uses the principle of relationship between producers and consumers to store log information in a queue. The queue default size is 10000. To prevent queue overflow, the default is to discard the last information. The default queue size and overflow settings can be set through the startup parameters.
Sample Program for Tomcat 7
The TOMCAT 7 example has two Servlets, one that demonstrates how to use random numbers to prevent CSRF attacks, and another that describes the use of aliases. Update Web/meta-inf/context.xml and point out that the absolute path of the picture will run smoothly.
Run build.xml with Ant to deploy them to Tomcat 7, accessed using the following two addresses:
http://localhost:8080/tomcat7demo/csrf/
http://localhost:8080/tomcat7demo/alias/
Seven more features of Tomcat 7