Several ways to improve the efficiency of JSP applications

Source: Internet
Author: User
Tags config html page

This article describes some of the most useful ways to adjust the JSP and servlet to make your servlet and JSP pages respond faster and more scalable. And in the case of increasing the number of users, the system load will show a trend of smooth and long. I will make your application's performance unexpectedly elevated through a number of practical examples and configuration methods. Some of these tuning techniques are implemented in your programming work, while others are related to the configuration of the application server. 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, you will also need to have basic servlet and JSP knowledge.


Method: Caching Data in the servlet init () method</strong>


when the application server Initializes a servlet instance, it 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 a good example, assuming that we are using the jdbc2.0 DataSource interface to get a 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 is cached datasource, making it possible for the next SQL call to continue to take advantage of 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;


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, which provides developers with a good development environment, and 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 class loader (ClassLoader).  Therefore, turning off the automatic overload feature 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, is through the httpsession to realize the session function, but at the same time convenient, it also brought the system not small burden. Because every time you get or update the session, the system needs to serialize it in a time-consuming process. You can improve the performance of the system by httpsession the following ways:


1, if not necessary, you should turn off the default settings for HttpSession in the JSP page. If you do not explicitly specify, each JSP page will default to create a httpsession. If you do not need to use session in your JSP, you can disable it by using the following JSP page designator:


<%@ page session= "false"%>


2, 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 additional burden on the system.  The larger the data you store in the HttpSession, the faster the performance of the system will fall.


3, when you don't need to httpsession, release it as quickly as possible: when you no longer need a session, you can release it by calling the Httpsession.invalidate () method.


4, try to set the timeout time of the session short: in the JSP application server, there is a default session timeout. When the customer has not done anything after this time, the related session is automatically freed from memory.  The larger the timeout time, the lower the performance of the system, so the best way is to keep its value at a lower level as much as possible.

Method 4: Compress the output of the page


compression is a good way to solve data redundancy, especially in today's network bandwidth is not developed. Some browsers support gzip (GNU Zip) to compress HTML files, which dramatically reduces the time to download HTML files. So, if you compress the HTML page generated by the servlet or JSP page, the user will feel the page is browsing very quickly. Unfortunately, not all browsers support gzip compression, but you can check to see if the client's browser supports it 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 &amp;&amp; encoding.indexof ("gzip")!=-1)


 {


Request.setheader


("content-encoding", "gzip");


out = new Gzipoutputstream


(Request.getoutputstream ());


 }


else if (encoding!=


Null &amp;&amp; encoding.indexof ("compress")!=-1)


 {


Request.setheader


("content-encoding", "compress");


out = new Zipoutputstream


(Request.getoutputstream ());


 }


Else


 {


out = Request.getoutputstream ();


 }


 ...


 ...








Method 5: Using the thread pool
the
application server defaults to creating a thread for each different client request and assigns a service () method to it, 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 this by creating a thread pool.


In addition, we will also 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 that is equal to the minimum number of threads, which, when requested by the client, is handled from the pool, and then, when the processing is complete, the thread is put back into the pool.


If the threads in the pool are not sufficient, the system automatically increases the number of threads in the pool, but the total amount 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 the JSP indicator (<jsp:includee page= "test.jsp" flush= "true"/").


in practice I have found that if you use the first method, you can make the system more performance-efficient.





Method 7: Correctly determine the life cycle of JavaBean

A powerful place for
JSP is support for JavaBean. By using the <jsp:useBean> label in a JSP page, you can insert JavaBean directly into a JSP page. It is used in the following ways:





<jsp:usebean id= "name"


scope= "Page|request|session|application"


class=


"Package.classname" type= "TypeName" >


</jsp:useBean>


The Scope property indicates the life cycle of the bean. The default life cycle is page.  If you don't choose your bean's lifecycle correctly, it will affect your system's performance.


For example, if you only want to use a bean in one request, but you set the life cycle of the bean to 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.  So setting the correct lifecycle for the bean and cleaning it up as quickly as possible after the Bean's mission is over, using system performance to improve.





Other useful methods


1, try not to use the "+" operator in string concatenation: In Java programming, we often use the "+" operator to concatenate several strings, but you probably never thought it would affect system performance. Because strings are constants, the JVM produces some temporary pairs of pixels. The more "+" you use, the more temporary the image will be generated, which will 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, when it is invoked, disk I/O operations must wait for it to complete, so we try to avoid calls to it. But when we debug the program it is an essential convenience tool, in order to solve this contradiction, I suggest you better use the log4j tool (http://Jakarta.apache.org;), it can be easily debugged, and will not produce System.out.println (  ) such a method.


3, Servletoutputstream and PrintWriter tradeoff: the use of printwriter may bring some small overhead, because it converts all the original output into a character stream to output, so if you use it 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 it is in binary output.  Therefore, in practical application to weigh the pros and cons of both.





Summary


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. With 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.