8-point discussion on optimizing JSP Servlet applications

Source: Internet
Author: User

Is your J2EE application running slowly? Can they withstand rising traffic volumes? This article describes how to develop high-performance and highly elastic JSP pages and Servlet performance optimization technologies. It means to build as fast as possible and adapt to the increasing number of users and their requests. In this article, I will lead you to learn the proven performance Adjustment Technology, which will greatly improve the performance of your Servlet and jsp pages, and thus improve the performance of J2EE. These technologies are used in the development phase, such as the design and coding phase. Other technologies are related to configuration.

Optimizing JSP Servlet Application Technology 1: caching data in the HttpServletinit () method

The server will call the Servlet init () method after creating the Servlet instance and before the Servlet processes any request. This method is called only once in the Servlet lifecycle. To improve performance, cache static data in init () or complete expensive operations to be completed during initialization. For example, a best practice is to use the JDBC connection pool that implements the javax. SQL. DataSource interface.

DataSource is obtained from the JNDI tree. Every time an SQL statement is called, it is very expensive to use JNDI to search for DataSource, which seriously affects the application performance. Servlet's init () method can be used to obtain DataSource and cache it for later reuse:

 
 
  1. publicclassControllerServletextendsHttpServlet  
  2. {  
  3. privatejavax.sql.DataSourcetestDS=null;  
  4.  
  5. publicvoidinit(ServletConfigconfig)throwsServletException  
  6. {  
  7. super.init(config);  
  8. Contextctx=null;  
  9. try  
  10. {  
  11. ctx=newInitialContext();  
  12. testDS=(javax.sql.DataSource)ctx.lookup("jdbc/testDS");  
  13. }  
  14. catch(NamingExceptionne)  
  15. {  
  16. ne.printStackTrace();  
  17. }  
  18. catch(Exceptione)  
  19. {  
  20. e.printStackTrace();  
  21. }  
  22. }  
  23.  
  24. publicjavax.sql.DataSourcegetTestDS()  
  25. {  
  26. returntestDS;  
  27. }  
  28. ...  
  29. ...  
  30. }  
  31.  

Optimize JSP Servlet Application Technology 2: Disable Automatic Servlet and Jsp Loading

After modifying Servlet/JSP, You have to restart the server. Because the automatic loading function reduces development time, this function is considered very useful in the development stage. However, it is very expensive in the running stage; Servlet/JSP causes poor performance due to unnecessary loading and increasing the load on the class loader. Similarly, this will cause a strange conflict between the classes loaded by a certain type of loader and the classes loaded by the current class loader. Therefore, in the runtime environment, disable the automatic loading function of Servlet/JSP for better performance.

Optimize JSP Servlet Application Technology 3: Control HttpSession

Many applications need a series of client requests, so they can be associated with each other. Because the HTTP protocol is stateless, Web-based applications need to maintain such a session state. To support applications that require State maintenance, the assumervlet technology provides APIs for managing sessions and allowing multiple mechanisms to implement sessions. The HttpSession object plays the role of the session, but the cost is required to use it. Whenever an HttpSession is used and overwritten, it is read by the Servlet. You can use the following technologies to improve performance:
Do not create the default HttpSession on the JSP page: by default, the JSP page creates an HttpSession. If you do not need HttpSession on the JSP page, to save performance overhead, use the following page command to avoid automatically creating an HttpSession object:
<%@ Pagesession = "false" %>

◆ Do not store large object graphs in HttpSession: If you store data as a large object graph in HttpSession, the application server will have to process the entire HttpSession object each time. This will force Java serialization and increase computing overhead. Due to the serialization overhead, as the data objects stored in the HttpSession object increase, the system throughput will decrease.

◆ Release HttpSession after use: When HttpSession is not used, use HttpSession. invalidate () to invalidate the sesion.

◆ Set timeout value: a Servlet engine has a default timeout value. If you do not delete a session or keep using it for a long time, the Servlet engine will delete the session from the memory. Due to the overhead of memory and garbage collection, the larger the Session Timeout value, the greater the impact on system elasticity and performance. Try to set the session Timeout value as low as possible.

Optimizing JSP Servlet Application Technology 4: Using gzip Compression

Compression is used to delete redundant information and describe your information with as little space as possible. Using gzipGNUzip) to compress a document can effectively reduce the time needed to download HTML files. The less information you have, the faster they are delivered. Therefore, if you compress the content produced by your web application, the faster it reaches the user and is displayed on the user screen. Not all browsers support gzip compression, but it is easy to check whether a browser supports it and send gzip compressed content to the browser. The following code snippet illustrates how to send compressed content.

 
 
  1. publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)  
  2. throwsIOException,ServletException  
  3. {  
  4.  
  5. OutputStreamout=null 
  6.  
  7. //ChecktheAccepting-EncodingheaderfromtheHTTPrequest.  
  8. //Iftheheaderincludesgzip,chooseGZIP.  
  9. //Iftheheaderincludescompress,chooseZIP.  
  10. //Otherwisechoosenocompression.  
  11.  
  12. Stringencoding=request.getHeader("Accept-Encoding");  
  13.  
  14. if(encoding!=null&&encoding.indexOf("gzip")!=-1)  
  15. {  
  16. response.setHeader("Content-Encoding","gzip");  
  17. out=newGZIPOutputStream(response.getOutputStream());  
  18. }  
  19. elseif(encoding!=null&&encoding.indexOf("compress")!=-1)  
  20. {  
  21. response.setHeader("Content-Encoding","compress");  
  22. out=newZIPOutputStream(response.getOutputStream());  
  23. }  
  24. else  
  25. {  
  26. out=response.getOutputStream();  
  27.  
  28. }  
  29. ...  
  30. ...  
  31. }  
  32.  

Optimize JSP Servlet Application Technology 5: Do not use SingleThreadModel

SingleThreadModel ensures that the Servlet processes only one request at a time. If a Servlet implements this interface, the Servlet engine will create a separate Servlet instance for each new request, which will cause a large amount of system overhead. If you need to solve the thread security problem, use other methods to replace this interface. SingleThreadModel is no longer recommended in Servlet2.4.

Optimizing JSP Servlet Application Technology 6: Using thread pools

The Servlet engine creates a separate thread for each request, assigns the thread to the service () method, and deletes the thread after the service () method is executed. By default, the Servlet engine may create a new thread for each request. Because the overhead of creating and deleting threads is very expensive, this default behavior reduces the system performance. We can use the thread pool to improve performance. Configure a thread pool based on the expected number of concurrent users and set the minimum and maximum number of threads in the thread pool and the minimum and maximum value of growth. At first, the Servlet engine created a thread pool with the same number of threads as the minimum number of threads in the configuration. Then, the Servlet engine assigns a thread in the pool to a request instead of creating a new thread each time. After the operation is completed, the Servlet engine places the thread back to the thread pool. With the thread pool, the performance can be significantly improved. If necessary, you can create more threads based on the maximum number of threads and the number of threads that increase.

Optimize JSP Servlet application technology 7: select the proper inclusion mechanism

On the JSP page, two methods can be used: including commands (<%@ includefile = "test. jsp "%>) and include actions (<jsp: includepage =" test. jsp "flush =" true "/> ). Including Commands include the content of a specified file in the compilation phase; for example, when a page is compiled into a Servlet. An action includes the file content in the request phase. For example, when a user requests a page. Including commands is faster than including actions. Therefore, unless the included files change frequently, using the include command will provide better performance.

Optimize JSP Servlet Application Technology 8: use the appropriate range in useBean actions

One of the most powerful ways to use JSP pages is to work with the JavaBean Component. JavaBean can embed the <jsp: useBean> label into the JSP page. Syntax:

 
 
  1. ﹤jsp:useBeanid="name"scope="page|request|session|application"class=  
  2. "package.className"type="typeName"﹥  
  3. ﹤/jsp:useBean﹥﹥  
  4.  

The scope attribute specifies the visible range of Bean. The default value of the scope attribute is page. You should select the correct range based on your application needs, otherwise it will affect the application performance.

For example, if you need an object dedicated to some requests, but you set the range to session, the object will be retained in the memory after the request ends. It will remain in the memory unless you explicitly delete it from the memory, make the session invalid, or the session times out. If you do not select the correct range attribute, performance will be affected due to memory and garbage collection overhead. Therefore, you can set appropriate ranges for objects and delete them immediately after they are used up.

Optimizes miscellaneous JSP Servlet applications

◆ Avoid String connection: Because the String object is an unchangeable object, using the "+" operator will lead to the creation of a large number of zero-time objects. The more "+" you use, the more objects will be generated at zero time, which will affect the performance. When you need to connect strings, use StringBuffer to replace the "+" operation.

◆ Avoid using System. out. println: System. out. println to synchronize disk input/output, which greatly reduces the System throughput. Avoid using System. out. println whenever possible. Although many mature debugging tools are available, sometimes System. out. println is still useful for tracking, or debugging. You should configure System. out. println to enable it only in the error and debugging phases. When the finalBoolean type variable is set to false, the optimization check and execution tracking output are completed in the compilation phase.

◆ Comparison between ServletOutputStream and PrintWriter: because of the character output stream and data encoding into bytes, PrintWriter introduces a small performance overhead. Therefore, PrintWriter should be used after all character sets are correctly converted. On the other hand, when you know that your Servlet only returns binary data, use ServletOutputStream because the Servlet container does not encode binary data, so that you can eliminate the character set conversion overhead.

The above are some suggestions for optimizing the JSP Servlet application. I hope you will be inspired and helpful in actual operations.

  1. A brief overview of embedded objects in JSP
  2. Functions and principles of several encodings in JSP and Servlet
  3. Use JSP include mechanism to improve appearance
  4. Six common issues for JSP Programming
  5. Storage and display of images in databases Based on JSP

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.