Is your J2EE app running very slow? Can they bear the continuous increase in access? This article tells the development of performance optimization techniques for developing high performance, high-elastic JSP pages and servlets. It means that it is to establish as fast and adaptable users and their requests. In this article, I will lead you to learn and have confirmed performance adjustment technology, which will greatly improve your performance of your servlet and JSP pages, which in turn enhances the performance of J2EE. The part of these technologies is used to development stages, such as design and coding stages. Another part of the technology is related to the configuration.
Technology 1: Cache data in httpservlet init () method
The server will call the servlet's init () method before creating a servlet instance and the servlet process. This method is only called once in the life cycle of the servlet. In order to improve performance, slow storage in init () or complete expensive operation to complete during initialization. For example, a best practice is to use a JDBC connection pool that implements the Javax.Sql.DataSource interface. DataSource is obtained from the JNDI tree. Every time you call SQL, you will use JNDI to find DataSource to be very expensive and seriously affecting the performance of the application. Servlet's init () method can be used to get DataSource and cache it to reuse after 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;
}
...
...
}
Technology 2: Disabling the automatic load function of servlet and JSP
When you modify the servlet / JSP each time, you will have to restart the server. This feature is considered to be very useful during the development phase due to the reduction in the development time of the automatic load function. However, it is very expensive during operation; servlet / JSP causes poor performance due to unnecessary loads, increasing the loader's burden. Similarly, this will make your application that cannot be worried about the class that has been loaded with a class loader and the class loaded with the current type loader. Therefore, in the operating environment, the automatic load function of Servlet / JSP is turned off in order to obtain better performance.
Technology 3: Control HttpSession
Many applications require a series of client requests, so they can be associated with each other. Since the HTTP protocol is stateless, the Web-based application needs to be responsible for maintaining such a status called Session. To support applications that must be maintained, Java Servlet technology provides an API that manages session and allows multiple mechanisms to implement session. The HttpSession object plays Session, but uses it needs cost. Whenever HttpSession is used and rewritten, it is read by servlet. You can improve performance by using the following technique:
l Don't create a default httpsession in the JSP page: By default, the JSP page creates httpsession. If you don't have HTTPSESSION in the JSP page, in order to save performance overhead, use the following page instructions to use the following page instructions to automatically create httpsession objects: <% @ Page session = "false"%>
l Don't store large object maps in httpsession: If you use data as a large object map in httpsession, the application server will have to handle the entire HTTPSession object each time. This will force Java serialization and increase computing overhead. Due to serialization overhead, with the increase in data objects stored in the httpsession object, the system throughput will decline.
l After using it, release httpsession: When not using HttpSession, use the httpsession.invalidate () method to make the SESION fail.
l Set the timeout value: A servlet engine has a default timeout value. If you don't delete sessions or always use the session to timeout, the servlet engine will remove the session from memory. Due to the overhead of memory and garbage collection, the larger the timeout value of the session, the greater the impact on the elasticity and performance of the system. Try to set the timeout value of the session as low as possible.
Technology 4: Compression using GZIP
Compression is the process of deleting redundant information, describing your information with as little space as possible. The use of Gzip (GNU ZIP) compressed documents can effectively reduce the time to download the HTML file. The smaller your information, the faster it is sent. So if you compress the content generated by your web application, it reaches the user and display the faster the speed on the user screen. Not any browser supports Gzip compression, but checks if a browser supports it and sends Gzip compressed content to a browser. The code segment below illustrates how to send compressed content.
Public void doget (httpservletRequest request, httpservletResponse response)
THROWS IOEXCEPTION, ServletException
{
OutputStream out = null
// check the accepting-encoding header from the http request.
// if the header incrudes Gzip, choose gzip.
// if The Header Includes Compress, Choose Zip.
// OtherWise Choose No Compression.
String Encoding = Request.getHeader ("Accept-encoding");
IF (Encoding! = Null && Encoding.indexof ("gzip")! = -1)
{
Response.setHeader ("Content-Encoding", "Gzip");
OUT = New gzipoutputstream (response.getoutputstream ());
}
Else IF (Encoding! = Null && Encoding.indexof ("compress")! = -1)
{
Response.setHeader ("Content-Encoding", "Compress");
OUT = New ZipOutputStream (response.getoutputstream ());
Else
{
OUT = response.getOutputStream ();
}
...
...
}
Technology 5: Don't use SingleThreadModel
SingleThreadModel guarantees that only a request is processed once a time. If a servlet implements this interface, the servlet engine will create a separate servlet instance for each new request, which will cause a lot of system overhead. If you need to resolve thread security issues, use other ways to replace this interface. SingleThreadModel is no longer advocated in Servlet 2.4.
Technology 6: Using thread pool
The servlet engine creates a separate thread for each request, assigns the thread to the service () method, and then delete the thread after the service () method is executed. By default, the servlet engine may create a new thread for each request. This default behavior reduces the performance of the system due to the cost of creating and deleting threads, so this default behavior reduces the performance of the system. We can use thread pools to improve performance. According to the expected quantity, configure a thread pool, set the minimum and maximum values of the number of threads in the thread pool, and the minimum and maximum growth. At first, the Servlet engine created a thread pool equal to the number of minimum threads in the configuration. The servlet engine then assigns a thread in the pool to a request instead of creating a new thread every time, after completing the operation, the servlet engine puts the thread back to the thread pool. With thread pools, performance can be significantly improved. If necessary, more threads can be created depending on the maximum number of threads and growth.
Technology 7: Select the correct included mechanism
In the JSP page, there are two middle ways can include files: including instructions (<% @ include file = "Test.jsp"%>) and include action (
Technology 8: Use the appropriate range in the useBean action
One of the most powerful ways using JSP pages is to work with JavaBean components. JavaBean can be embedded in the JSP page using the
"package.classname" type = "typeename"> jsp: usebean> The Scope property illustrates the visible range of the bean. The default value of the Scope property is Page. You should choose the correct range based on your application, otherwise it will affect the performance of the application. For example, if you need an object dedicated to some requests, you set the range to sessions, then that object will remain in memory after the request is over. It will always remain in-memory unless you explicit it clearly from memory, so that the session is invalid or session timeout. If you don't have the right range properties, the overhead of memory and garbage will affect performance. Therefore, the appropriate range is set for the object and remove it immediately after using them. Miscellaneous technology l Avoid a string connection: Since the String object is an informal object, use the " " operator will result in a large number of zero objects. The more " " you are using, the more zero output, which will affect performance. When you need to connect a string, use StringBuffer instead of " ". l Avoid using system.out.println: system.out.println to synchronize processing disk input / output, which greatly reduces system throughput. Avoid using System.out.Println as much as possible. Although there are many mature debugging tools that can be used, but sometimes system.out.println is still useful for tracking, or debugging. You should configure system.out.println to open it only in the error and debug phase. Using the Final Boolean type variable, when configuring False, the optimized check and perform the tracking output during the compile stage. l ServletOutputStream and PrintWriter Comparison: Due to the character output stream and the data encoding the data into bytes, use PrintWriter to introduce small performance overhead. Therefore, PrintWriter should be used correctly after all character sets are finished correctly. On the other hand, when you know that your servlet returns binary data, use servletoutputstream, because the servlet container does not encode binary data so you can eliminate character set conversion overhead. to sum up The purpose of this article is to show you some practical and confirmed performance optimization techniques for increasing Servlet and JSP performance, which will increase your integral performance of your J2EE application. The next step should observe the performance adjustment of other related technologies, such as EJB, JMS, and JDBC.