Eight Methods for 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.

Technology 1: cache 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:

Publicclasscontrollerservletextendshttpservlet
{
Privatejavax. SQL. datasourcetestds = NULL;

Publicvoidinit (servletconfigconfig) throwsservletexception
{
Super. INIT (config );
Contextctx = NULL;
Try
{
CTX = newinitialcontext ();
Testds = (javax. SQL. datasource) CTX. Lookup ("JDBC/testds ");
}
Catch (namingexceptionne)
{
Ne. printstacktrace ();
}
Catch (effectione)
{
E. printstacktrace ();
}
}

Publicjavax. SQL. javascegettestds ()
{
Returntestds;
}
...
...
}

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.

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:
L 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" %>

1) 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.

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

3) set the 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.

Technology 4: gzip Compression

Compression is used to delete redundant information and describe your information with as little space as possible. Using gzip (gnuzip) 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. BelowCodeSection describes how to send compressed content.

Publicvoiddoget (httpservletrequestrequest, httpservletresponseresponse)
Throwsioexception, servletexception
{

Outputstreamout = NULL

// Checktheaccepting-encodingheaderfromthehttprequest.
// Iftheheaderincludesgzip, choosegzip.
// Iftheheaderincludescompress, choosezip.
// Otherwisechoosenocompression.

Stringencoding = request. getheader ("Accept-encoding ");

If (encoding! = NULL & encoding. indexof ("gzip ")! =-1)
{
Response. setheader ("content-encoding", "gzip ");
Out = newgzipoutputstream (response. getoutputstream ());
}
Elseif (encoding! = NULL & encoding. indexof ("compress ")! =-1)
{
Response. setheader ("content-encoding", "compress ");
Out = newzipoutputstream (response. getoutputstream ());
}
Else
{
Out = response. getoutputstream ();

}
...
...
}

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.

Technology 6: Use a thread pool

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.

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.

Technology 8: Use appropriate ranges 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:

<JSP: usebeanid = "name" Scope = "Page | request | session | application" class =
"Package. classname" type = "typename">
</Jsp: usebean>

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.

Miscellaneous Technology

1) 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.

2) Avoid using system. Out. println: system. Out. println to synchronize disk input/output, which greatly reduces 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.

3) 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.

Summary

the purpose of this article is to show you some practical and proven performance optimization technologies for improving Servlet and JSP performance, which will improve the overall performance of your J2EE application. Next, observe the performance adjustments of other related technologies, such as EJB, JMS, and JDBC.

Related Article

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.