Method 1: Cache data in the servlet's init() method.
After the application server initializes the servlet instance and before serving client requests, it calls the servlet's init() method. In the life cycle of a servlet, the init() method will only be called once. By caching some static data in the init() method or completing some time-consuming operations that only need to be performed once, system performance can be greatly improved.
For example, establishing a JDBC connection pool in the init() method is the best example. Suppose we use the DataSource interface of jdbc2.0 to obtain a database connection. Under normal circumstances, we need to obtain specific data through JNDI. source. We can imagine that in a specific application, if a JNDI query is executed for every SQL request, the system performance will drop sharply. The solution is the following code, which caches the DataSource so that it can still be used during the next SQL call:
The following is a reference fragment:
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 reloading (auto-reloading)
Servlet/JSP provides a practical technology, namely automatic reloading technology, which provides developers with a good development environment when you change servlet and JSP pages without having to restart the application server. However, this technology is a huge loss of system resources during the product running stage, because it will bring a huge burden to the class loader 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 program needs to maintain the state of the client so that pages can communicate with each other. But unfortunately, because HTTP is inherently stateless, it cannot save the client's state. Therefore, general application servers provide sessions to save the client's state. In the JSP application server, the session function is implemented through the HttpSession object, but while it is convenient, it also brings a lot of burden to the system. Because every time you obtain or update a session, the system operator has to perform time-consuming serialization operations on it. You can improve system performance through the following processing methods for HttpSession.
If it is not necessary, the default settings for HttpSession in the JSP page should be turned off. Each JSP page will create an HttpSession by default if you do not specify it explicitly. If you do not need to use session in your JSP, you can disable it through the following JSP page indicator:
The following is a reference fragment:
<%@ page session="false"%>
Do not store large data objects in HttpSession: If you store large data objects in HttpSession, the application server will serialize it every time it is read or written, thus adding extra burden to the system. . The larger the data object you store in HttpSession, the faster the system performance will decrease.
When you no longer need the HttpSession, release it as soon as possible: When you no longer need the session, you can release it by calling the HttpSession.invalidate() method. Try to set the session timeout as short as possible: In the JSP application server, there is a default session timeout. When the customer does not perform any operations after this time, the system will automatically release the relevant session from the memory. The larger the timeout is set, the lower the system performance will be, so the best way is to try to keep its value as low as possible.
Method 4: Compressing page output
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. This method can dramatically reduce the download time of HTML files. Therefore, if you compress the HTML page generated by a 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 in your program whether the client's browser supports it. The following is a code snippet about the implementation of this method:
The following is a quotation snippet:
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 creates a thread for processing each different client request by default, and assigns the service() method to them. When the service() method call is completed, the corresponding thread also Then cancel. Since creating and destroying threads consumes certain system resources, this default mode reduces system performance. 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 will create a thread pool with a number equal to the minimum number of threads. When a customer has a request, a thread is taken out from the pool for processing. When the processing is completed, the thread is put back into the pool. middle. 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 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: Choose the correct page inclusion mechanism.
There are two methods in JSP that can be used to include another page:
1. Use the include directive.
The following is a reference fragment:
<%@ includee file=”test.jsp” %>
2. Use the jsp indicator.
The following is a reference fragment:
<jsp:includee page="test.jsp" flush="true"/>
In practice, it is found that if the first method is used, the system performance can be higher.
Method 7: Correctly determine the life cycle of javabeans.
One of the powerful aspects of JSP is its support for javabeans. JavaBeans can be inserted directly into a JSP page by using the jsp:useBean tag in the JSP page. Here's how to use it:
Here's a quote snippet:
<jsp:useBean id="name" scope="page|request|session|application"
class="package.className" 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 bean life cycle correctly, it will affect the performance of the system.
For example, if you only want to use a certain bean in one request, but you set the bean's life cycle to session, then when the request ends, the bean will still remain in memory unless the session Timeout or user closes browser. This will consume a certain amount of memory and unnecessarily increase the workload of the JVM garbage collector. Therefore, setting the correct life cycle for beans and cleaning them up as soon as possible after their mission is over will improve system performance.
Some other useful methods
1. Try not to use the "+" operator in string connection operations: In java programming, we often use the "+" operator to connect several strings, but you may have never thought of it. Will it actually affect system performance? Because strings are constants, the JVM will generate some temporary objects. The more "+" you use, the more temporary objects will be generated, which will also have some impact on system performance. The solution is to use a StringBuffer object instead of the "+" operator.
2. Avoid using the System.out.println() method: Since System.out.println() is a synchronous call, that is, when calling it, the disk I/O operation must wait for its completion, so we should try to avoid using it. its call. But it is an indispensable and convenient tool when we debug the program. In order to solve this contradiction, I suggest you use the Log4j tool ( http://Jakarta.apache.org ), which can facilitate debugging without Methods like System.out.println() will be generated.
3. Trade-off between ServletOutputStream and PrintWriter: Using PrintWriter may bring some small overhead, because it converts all original output into a character stream for output, so if it is used as page output, the system has to bear a conversion process . There is no problem if you use ServletOutputStream as page output, but it is output in binary. Therefore, the pros and cons of both must be weighed in practical applications.
Summary
The purpose of this article is to greatly improve the performance of your application through some tuning techniques for servlets and JSP, and therefore improve the performance of the entire J2EE application. Through these tuning techniques, you can find that it is not a certain technical platform (such as the dispute between J2EE and .NET) that determines the performance of your application. What is important is that you have a deeper understanding of this platform, so that Only then can you fundamentally optimize your application.