JAVA basics: Seven Tips for improving JSP applications

Source: Internet
Author: User
JAVA basics: Seven Tips for improving JSP applications-general Linux technology-Linux programming and kernel information. For details, see below. 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 unexpectedly improve the performance of your application. 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 the following code, which 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;
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 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, disable the default settings for HttpSession on the JSP page. If you do not specify the default settings, an HttpSession is 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 ());
}
Else
{
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">
</Jsp: useBean>

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.

? The trade-off 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, so if it is used as the page output, the system is responsible for 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.

Summary

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