SoFunction
Updated on 2025-04-07

Seven tricks to improve JSP applications

Are you often complained by customers about the slow response speed of JSP pages? Have you ever thought that when customer visits increase dramatically, can your WEB application withstand the increasing number of visits? This article describes some very practical ways to tweak JSP and servlets, which can make your servlet and JSP pages more responsive and more scalable. Moreover, with the increase in the number of users, the system load will show a trend of smooth upward growth. In this article, I will use some practical examples and configuration methods to make your application's performance unexpectedly improve. Among them, some tuning techniques are implemented in your programming work. Other technologies are related to the configuration of the application server. In this article, we will describe in detail how to improve the overall performance of your application by tuning servlets and JSP pages. Before reading this article, assume that you have basic knowledge of servlets and JSP.

Method 1: Cache data in the init() method of servlet

After the application server initializes the servlet instance and before providing services to the client request, it will call the init() method of the servlet. During the lifetime of a servlet, the init() method will only be called once. System performance can be greatly improved by cached some static data in the init() method or completing some time-consuming operations that only require execution once.

For example, establishing a JDBC connection pool in the init() method is a best 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 each SQL request has to execute a JNDI query, the system performance will drop sharply. The solution is the following code, which caches DataSource so that you can continue to utilize it in the next SQL call:

public class ControllerServlet extends HttpServlet
{
 private testDS = null;
 public void init(ServletConfig config) throws ServletException
 {
(config);
Context ctx = null;
try
{
 ctx = new InitialContext();
 testDS = ()("jdbc/testDS");
}
catch(NamingException ne)
{
 ();
}
catch(Exception e)
{
 ();
}
 }

 public getTestDS()
 {
return testDS;
 }
 ...
 ...
}

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

Servlet/JSP provides a practical technology, namely automatic reloading technology, which provides developers with a good development environment when you change the servlet and JSP page without having to restart the application server. However, this technology is a huge loss to the system's resources during the product operation stage, because it will put a huge burden on the classloader of the JSP engine. Therefore, turning off the automatic reload function is a great help to improve system performance.

Method 3: Don't abuse HttpSession

In many applications, our programs need to keep the client state so that pages can be connected to each other. Unfortunately, HTTP is inherently stateless, so the state of the client cannot be saved. Therefore, general application servers provide session to save the status of customers. In JSP application server, the session function is realized through the HttpSession object, but while it is convenient, it also brings a considerable burden to the system. Because whenever you get or update the session, the system needs to perform time-consuming serialization operations on it. You can improve the performance of the system by handling HttpSession:

· If it is not necessary, the default settings for HttpSession in JSP pages should be turned off: If you do not specify it explicitly, each JSP page will create an HttpSession 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 large data objects in HttpSession: If you store large data objects in HttpSession, whenever you read and write it, the application server will serialize it, which adds an additional burden on the system. The larger the data object you store in HttpSession, the faster the system's performance will drop.

· When you don't need HttpSession, release it as soon as possible: When you no longer need the session, you can release it by calling the() method.

· Try to set the session timeout to a shorter time: In the JSP application server, there is a default session timeout time. When the customer does not perform any operations after this time, the system will automatically release the relevant session from memory. The larger the timeout, the lower the system's performance will be, so the best way is to keep its value at a lower level.

Method 4: Compress the page output

Compression is a good way to solve data redundancy, especially today when network bandwidth is not developed enough. Some browsers support gzip (GNU zip) to compress HTML files, which can dramatically reduce the download time of HTML files. Therefore, if you compress the HTML page generated by the servlet or JSP page, the user will feel that the page browsing speed will be very fast. Unfortunately, not all browsers support gzip compression, but you can check if the client's browser supports it by checking in your program. Here is a code snippet about this method implementation:

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
 OutputStream out = null
 String encoding = ("Accept-Encoding");
 if (encoding != null && ("gzip") != -1)
 {
("Content-Encoding" , "gzip");
out = new GZIPOutputStream(());
 }
 else if (encoding != null && ("compress") != -1)
 {
("Content-Encoding" , "compress");
out = new ZIPOutputStream(());
 }
 else
 {
out = ();
 }
 ...
 ...

Method 5: Use thread pool

By default, the application server creates a thread for each different client request for processing and dispatches the service() method to them. When the service() method call is completed, the corresponding thread will be cancelled. Since creating and undoing threads consumes a certain amount of system resources, this default mode reduces the performance of the system. Fortunately, we can change this by creating a thread pool. In addition, we need to set a minimum number of threads and a maximum number of threads for this thread pool. When the application server starts, it will create a thread pool with the minimum number of threads. When the client requests, it will take out a thread from the pool accordingly to process it. When the processing is completed, the thread will be re-placed into the pool. If there are not enough threads in the pool, the system will automatically increase the number of threads in the pool, but the total number cannot exceed the maximum number of threads. By using thread pools, when client requests increase dramatically, the system's load will present a smooth rising curve, thereby improving the system's scalability.

Method 6: Select the correct page inclusion mechanism

There are two ways to include another page in JSP: 1. Use the include indicator (<%@ include file=”” %>). 2. Use the jsp indicator (<jsp:includee page=””flush=”true”/>). In practice, I found that if the first method is used, the system performance can be higher.

Method 7: Correctly determine the life cycle of a javabean

A powerful part of JSP is its support for javabeans. By using the <jsp:useBean> tag in the JSP page, you can insert the javabean directly into a JSP page. It is used as follows:

<jsp:useBean scope="page|request|session|application" class=
"" type="typeName">
</jsp:useBean>

The scope attribute points out the life cycle of this bean. The default life cycle is page. If you do not choose the life cycle of a bean correctly, it will affect the performance of the system.

For example, if you only want to use a bean in one request, but you set the lifecycle of the bean to session, then when the request is over, the bean will remain in memory unless the session timed out or the user closes the browser. This will consume a certain amount of memory and will unnecessary increase the workload of the JVM garbage collector. Therefore, setting the correct lifecycle for beans and cleaning them as soon as possible after the bean's mission is over will improve the system performance.

Some other useful methods

· Try not to use the "+" operator in string concatenation operations: In Java programming, we often use the "+" operator to connect several strings, but you may never have thought that it will have an impact on system performance, right? Since strings are constants, the JVM produces some temporary objects. The more "+" you use, the more temporary objects you generate, which will also have some impact on system performance. The solution is to use the StringBuffer object instead of the "+" operator.

· Avoid using the() method: Since () 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 and convenient tool. In order to solve this contradiction, I suggest you better use Log4j tool (), which can be convenient for debugging without producing a method like ().

· Tradeoff between ServletOutputStream and PrintWriter: Using PrintWriter may bring some minor overhead because it converts all the original output into a character stream for output, so if you use it as page output, the system will have to bear a conversion process. There is no problem with using ServletOutputStream as page output, but it is output in binary. Therefore, in practical applications, we must weigh the pros and cons of both.

Summarize

The purpose of this article is to greatly improve the performance of your application through some tuning techniques for servlets and JSP, and thus improve the performance of the entire J2EE application. Through these tuning technologies, you can find that it is not actually a certain technical platform (such as the dispute between J2EE and .NET) that determines the performance of your application. The important thing is that you need to have a deeper understanding of this platform so that you can fundamentally optimize your application!