A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service
Are you often complained about slow response to JSP pages? Have you ever wondered whether your web applications will be able to withstand the increasing traffic volume when the number of customer visits increases dramatically? This article describes some very practical methods to adjust JSP and Servlet. It can make your Servlet and JSP page response faster and more scalable. In addition, when the number of users increases, the system load will show a smooth and long trend. In this article, I will use some practical examples and configuration methods to make your applicationProgramPerformance has been unexpectedly improved. Some tuning techniques are implemented in your programming work. Other technologies are related to the configuration of application servers. In this article, we will describe in detail how to improve the overall performance of your application by adjusting the servlet and JSP pages. Before reading this article, let's assume that you have basic Servlet and JSP knowledge.
Method 1: cache data in the servlet Init () method
After the application server initializes the servlet instance and provides services for client requests, it will call the init () method of the servlet. In the lifecycle of a servlet, The init () method is called only once. By caching some static data in the init () method or completing some time-consuming operations that only need to be executed once, the system performance can be greatly improved.
For example, establishing a JDBC connection pool in the init () method is an optimal example. Suppose we use the datasource interface of jdbc2.0 to obtain the database connection. In general, we need to obtain the specific data source through JNDI. We can imagine that in a specific application, if every SQL request needs to execute a JNDI query, the system performance will drop sharply. The solution is as follows:CodeIt caches datasource so that the next SQL call can continue to use it:
Public class controllerservlet extends httpservlet
Private javax. SQL. datasource testds = NULL;
Public void Init (servletconfig config) throws servletexception
Super. INIT (config );
Context CTX = NULL;
CTX = new initialcontext ();
Testds = (javax. SQL. datasource) CTX. Lookup ("JDBC/testds ");
Catch (namingexception ne)
Ne. printstacktrace ();
Catch (exception E)
E. printstacktrace ();
Public javax. SQL. datasource gettestds ()
Method 2: Disable auto-Reloading)
Servlet/JSP provides a practical technology, that is, automatic heavy load technology, which provides a good development environment for developers. When you change the servlet and JSP pages, you do not have to restart the application server. However, this technology is a huge loss to system resources in the product operation phase, because it will bring a great burden to the JSP Engine Class Loader (classloader. Therefore, disabling the auto-Reload function can greatly improve the system performance.
Method 3: Do not abuse httpsession
In many applications, our programs need to maintain the client state so that pages can communicate with each other. Unfortunately, because HTTP is inherently stateless, the client state cannot be saved. Therefore, common application servers provide sessions to store the customer's status. In the JSP application server, the session function is implemented through the httpsession object, but it brings a lot of burden to the system while being convenient. Because whenever you obtain or update a session, the system will perform time-consuming serialization operations on it. You can improve the system performance by processing httpsession in the following ways:
· If not necessary, disable the default settings for httpsession on the JSP page: if you do not specify it explicitly, an httpsession will be created for each JSP page by default. If you do not need to use session in your JSP, you can use the following JSP page indicator to disable it:
<% @ Page session = "false" %>
· Do not store enlarged data pairs in httpsession: If you Store enlarged data pairs in httpsession, the application server will serialize them whenever it reads/writes data, this increases the additional burden on the system. The larger the data pair you store in httpsession, the faster the system performance is.
· If you do not need an httpsession, release it as soon as possible: when you no longer need a session, you can release it by calling the httpsession. invalidate () method.
· Set the Session Timeout time to a shorter value: On the JSP application server, there is a default session timeout time. When the customer does not perform any operation after this time, the system will automatically release the relevant session from the memory. The larger the timeout value, the lower the system performance. Therefore, the best way is to keep its value at a lower level.
Method 4: compress the page output
Compression is a good solution to data redundancy, especially when the network bandwidth is insufficient. Some browsers support gzip (GNU zip) to compress HTML files. This method can dramatically reduce the download time of HTML files. Therefore, if you compress the HTML page generated by the servlet or JSP page, you will feel that the page browsing speed will be very fast. Unfortunately, not all browsers support gzip compression, but you can check whether your browser supports it in your program. The following is a code snippet about the implementation of this method:
Public void doget (httpservletrequest request, httpservletresponse response)
Throws ioexception, servletexception
Outputstream out = NULL
String encoding = request. getheader ("Accept-encoding ");
If (encoding! = NULL & encoding. indexof ("gzip ")! =-1)
Request. setheader ("content-encoding", "gzip ");
Out = new gzipoutputstream (request. getoutputstream ());
Else if (encoding! = NULL & encoding. indexof ("compress ")! =-1)
Request. setheader ("content-encoding", "compress ");
Out = new zipoutputstream (request. getoutputstream ());
Out = request. getoutputstream ();
Method 5: Use the thread pool
By default, the application server creates a thread for each different client request for processing and assigns them a service () method. After the service () method is called, the corresponding thread is also revoked. This default mode reduces system performance because creating and canceling threads consume a certain amount of system resources. But fortunately, we can change this situation by creating a thread pool. In addition, we also need to set a minimum number of threads and a maximum number of threads for this thread pool. When the application server starts, it creates a thread pool with the minimum number of threads equal to the number of threads. When the customer requests, it extracts a thread from the pool for processing, after the processing is complete, re-place the thread into the pool. If the number of threads in the pool is insufficient, the system automatically increases the number of threads in the pool, but the total number cannot exceed the maximum number of threads. By using the thread pool, when client requests increase sharply, the system load will show a smooth upward curve, thus improving the scalability of the system.
Method 6: select the correct page inclusion mechanism
There are two methods in JSP to include another page: 1. Use the include indicator (<% @ includee file = "test. jsp" %> ). 2. Use the JSP indicator (<JSP: includee page = "test. jsp" flush = "true"/> ). In practice, I found that using the first method can improve the system performance.
Method 7: correctly determine the lifecycle of the JavaBean
A powerful part of JSP is its support for JavaBean. By using the <JSP: usebean> tag on the JSP page, you can insert a JavaBean directly to a JSP page. It is used as follows:
<JSP: usebean id = "name" Scope = "Page | request | session | application" class =
"Package. classname" type = "typename">
The scope attribute specifies the bean lifecycle. The default lifecycle is page. If you do not correctly select the bean lifecycle, it will affect the system performance.
For example, if you only want to use a bean in a request, but you set the bean lifecycle to session, after this request is complete, this bean will remain in the memory unless the session times out or the user closes the browser. This will consume a certain amount of memory and increase the workload of the JVM garbage collector. Therefore, setting the correct lifecycle for beans and clearing them as soon as possible after Bean's mission will improve system performance.
Other useful methods
· Try not to use the "+" Operator in string join operations: in Java programming, we often use the "+" operator to connect several strings, but you may never have imagined that it will affect the system performance? Since the string is a constant, JVM will generate some temporary objects. The more "+" you use, the more temporary pairs you generate. This will also affect the system performance. The solution is to replace the "+" operator with the stringbuffer object.
· Avoid using system. out. println () method: Because system. out. println () is a synchronous call, that is, when calling it, the disk I/O operation must wait for it to complete, so we should try to avoid calling it. But when we debug the program, it is an indispensable convenience tool, in order to solve this conflict, I suggest you use the log4j tool (http://Jakarta.apache.org), it can be convenient debugging, instead of system. out. println.
· Balance Between servletoutputstream and printwriter: Using printwriter may bring about some small overhead, because it converts all the original output to the slave stream for output, therefore, if it is used as page output, the system must bear a conversion process. When servletoutputstream is used as the page output, there is no problem, but it is output in binary format. Therefore, we must weigh the advantages and disadvantages of the two in practical applications.
the purpose of this article is to greatly improve the performance of your application through some tuning techniques of Servlet and JSP, and thus improve the performance of the entire J2EE application. Through these optimization technologies, you can find that it is not actually a certain technical platform (such as J2EE and.. Net) determines the performance of your application. It is important that you have a deeper understanding of this platform, in this way, you can fundamentally optimize your own applications!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service