Seven tips for improving the response speed of JSP pages

Source: Internet
Author: User
Tags config html page

Method One: Caching data in the Init () method of the Servlet

After the application server initializes the servlet instance, he invokes the Init () method of the servlet before servicing the client request. In the lifecycle of a servlet, the init () method is invoked only once. System performance can be greatly improved by caching some static data in the Init () method or by completing some time-consuming operations that need to be performed only once.

For example, creating a JDBC Connection pool in the init () method is the best example, assuming that we are using the jdbc2.0 DataSource interface to get the database connection, and that, in general, we need to get a specific data source through Jndi. We can imagine that in a specific application, if a jndi query is executed every time a SQL request is performed, the performance of the system will drop dramatically. The workaround is the following code, which he caches datasource, making it possible for the next SQL call to continue using him:

public class Controllerservlet extends httpservlet{
Private Javax.sql.DataSource Testds = null;
public void init (ServletConfig config) throws servletexception {
Super.init (config);
Context ctx = null;
try{
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 () {
return Testds;
}
...
...
}

Method 2: Disable servlet and JSP automatic overloading (auto-reloading)

SERVLET/JSP provides a practical technology, automatic overload technology, and he provides a good research and development environment for developers, when you change the servlet and JSP pages without restarting the application server. However, this technology is a great drain on the resources of the system during the operation of the product, because it will bring a great burden to the JSP engine's class loader (ClassLoader). Therefore, turning off automatic overloading is a great help to improve system performance.

Method 3: Do not abuse httpsession

In many applications, our programs need to maintain the state of the client so that the pages can be interconnected. Unfortunately, because HTTP is inherently stateless, the state of the client cannot be saved. Therefore, the general application Server provides a session to save the state of the customer. In the JSP application server, it is through the httpsession to realize the function of the session, but at the same time, he also brought a small burden to the system. Because every time you get or update the session, the system is going to take a time-consuming serialization of him. You can improve the performance of your system by following several processing methods for httpsession.

If not necessary, you should close the default configuration for HttpSession in the JSP page. If you do not explicitly specify, each JSP page creates a httpsession by default. If you do not need to use session in your JSP, you can prohibit it by using the following JSP page designator:

<%@ page session= "false"%>

Do not store large data pairs in HttpSession: If you store large data pairs in HttpSession, the application server will serialize them whenever you read and write to them, increasing the extra burden on the system. The larger the data you store in the HttpSession, the faster the performance of the system will fall.

When you do not need to httpsession, release him as soon as possible: when you no longer require a session, you can release him by calling the Httpsession.invalidate () method. Try to set the timeout for the session short: there is a default timeout for the session in the JSP application server. When the customer has not done anything after this time, the related session is automatically freed from memory. The larger the timeout, the lower the performance of the system, so the best way is to keep his value at a lower level.

Method 4: Compress the page output

Compression is a good way to solve data redundancy, especially in the network bandwidth is not developed today. Some browsers support gzip (GNU Zip) to compress HTML documents, which dramatically reduces the time it will take to download HTML documents. So, if you compress the HTML page generated by the servlet or JSP page, the user will feel the page is browsing quickly. Unfortunately, not all browsers support gzip compression, but you can check the client's browser for support in your program. Here is a snippet of 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 ("Comdivss")!=-1) {
Request.setheader ("content-encoding", "Comdivss");
out = new Zipoutputstream (Request.getoutputstream ());
}else{
out = Request.getoutputstream ();
}
...
...
}

Method 5: Use the thread pool

The application server defaults to creating a thread for each of the different client requests and assigns the service () method to them, and the corresponding thread is undone when the service () method call completes. Because creating and undoing threads consumes a certain amount of system resources, this default mode reduces the performance of the system. But fortunately we can change that by creating a thread pool.

In addition, we will also configure a minimum number of threads and a maximum number of threads for this thread pool. When the application server starts, he creates a thread pool that is equal to the minimum number of threads, which, when requested by the client, is processed from the pool, and then, when the processing is complete, the thread is put back into the pool. If the thread in the pool is insufficient, the system automatically increases the number of threads in the pool, but the total cannot exceed the maximum thread count. By using a thread pool, the system's load will be rendered a smooth upward curve when client requests increase dramatically, thereby increasing the system's scalability.

Method 6: Select the correct page inclusion mechanism

There are two ways in JSP that can be used to include another page:

1. Use the Include indicator

<%@ Includee file= "test.jsp"%>

2. Use JSP indicator



In practice, it is found that if the first method is used, it can make the system performance higher.

Method 7: Correctly determine the life cycle of the JavaBean

A powerful place for JSP is the support of JavaBean. By using the Jsp:usebean tag in the JSP page, you can insert the JavaBean directly into a JSP page. He uses the following methods:

class= "Package.classname" type= "TypeName"


The scope attribute indicates the life cycle of the bean. The default life cycle is page. If you don't select the bean's lifecycle correctly, he will affect the performance of the system.

For example, if you only want to use a bean in one request, but you configure the Bean's lifecycle to be a session, the bean will remain in memory when the request is finished, unless the sessions timeout or the user closes the browser. This consumes a certain amount of memory and needlessly increases the workload of the JVM garbage collector. Therefore, configuring the correct lifecycle for the bean and cleaning them up as soon as the Bean's mission is over will improve with system performance.

A few other useful methods

1, in string concatenation operation as far as possible not to use the "+" operator: In Java programming, we often use the "+" operator to connect a few strings, but you may never think that he can actually affect the system performance? Because strings are constants, the JVM produces some temporary pairs of pixels. The more "+" you use, the more temporary the image you generate, which can also have some impact on system performance. The workaround is to replace the "+" operator with StringBuffer.

2, avoid using the System.out.println () method: Because System.out.println () is a synchronous call, that is, when calling him, disk I/O operation must wait for his completion, so we should try to avoid the call on him. But when we debug the program he is an essential convenience tool, in order to solve this contradiction, I suggest that you should use the Log4j tool, he can be easy to debug, and will not produce System.out.println () such a method.

3, Servletoutputstream and PrintWriter trade-offs: Using PrintWriter can have some small overhead because he converts any raw output into a character stream to output, so if you use him as a page output, The system has to bear a conversion process. The use of Servletoutputstream as a page output does not have a problem, but he is the binary output. Therefore, in practical application to weigh the pros and cons of both.

Summarize

The purpose of this article is to greatly improve the performance of your application through some of the tuning techniques of the servlet and JSP, and thus enhance the performance of the entire Java EE application. Through these tuning techniques, you can see that it's not a technology platform (like Java EE and. NET contention) that determines the performance of your application, it's important that you have a deeper understanding of the platform so that you can fundamentally optimize your application.

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.