In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces how to optimize the JSP Servlet application, the article is very detailed, has a certain reference value, interested friends must read it!
Optimizing JSP Servlet Application Technology 1: caching data in the HttpServletinit () method
The server calls the init () method of Servlet after the Servlet instance is created and before Servlet processes any requests. This method is called only once in the life cycle of the Servlet. To improve performance, cache static data in init () or perform expensive operations to be done during initialization. For example, a * practice is to use JDBC connection pooling that implements the javax.sql.DataSource interface.
DataSource is obtained from the JNDI tree. Every time SQL is called, it is very expensive to use JNDI to find DataSource, and it seriously affects the performance of the application. The init () method of Servlet can be used to get the DataSource and cache it for later reuse:
PublicclassControllerServletextendsHttpServlet {privatejavax.sql.DataSourcetestDS=null; publicvoidinit (ServletConfigconfig) throwsServletException {super.init (config); Contextctx=null; try {ctx=newInitialContext (); testDS= (javax.sql.DataSource) ctx.lookup ("jdbc/testDS");} catch (NamingExceptionne) {ne.printStackTrace ();} catch (Exceptione) {e.printStackTrace ();}} publicjavax.sql.DataSourcegetTestDS () {returntestDS;}.
Optimize JSP Servlet application technology 2: disable autoloading of Servlet and Jsp
Every time you change the Servlet/JSP, you will have to restart the server. Because the automount feature reduces development time, it is considered to be very useful during the development phase. However, it is very expensive at run time; Servlet/JSP has poor performance due to unnecessary loading, which increases the burden on the classloader. Similarly, this will cause your application to have strange conflicts because the classes already loaded by some class loader cannot cooperate with the classes loaded by the current class loader. Therefore, in order to get better performance in the running environment, the automount function of Servlet/JSP is turned off.
Optimizing JSP Servlet Application Technology 3: controlling HttpSession
Many applications require a series of client requests, so they can be related to each other. Because the HTTP protocol is stateless, Web-based applications are responsible for maintaining such a state called session. In order to support applications that must maintain state, JavaServlet technology provides API that manages session and allows multiple mechanisms to implement session. The HttpSession object acts as session, but there is a cost to use it. Whenever HttpSession is used and rewritten, it is read by Servlet. You can improve performance by using the following techniques:
Do not create a default HttpSession in a JSP page: by default, a JSP page creates a HttpSession. If you do not use HttpSession in JSP pages, to save performance overhead, use the following page instructions to avoid automatically creating HttpSession objects:
< @ pagesession= "false" >
◆ do not store large object graphs in HttpSession: if you store data in HttpSession as a large object graph, the application server will have to process the entire HttpSession object at a time. This will force Java serialization and increase computational overhead. Due to the overhead of serialization, the throughput of the system will decrease as the data objects stored in the HttpSession object grow.
Release HttpSession after ◆ is used: use the HttpSession.invalidate () method to invalidate sesion when HttpSession is no longer in use.
◆ sets the timeout value: a Servlet engine has a default timeout value. If you don't delete session or keep using session until it times out, the Servlet engine will remove session from memory. Due to the overhead of memory and garbage collection, the greater the timeout value of Session, the greater its impact on system resilience and performance. Try to set the timeout value of session as low as possible.
Optimizing JSP Servlet Application Technology 4: using gzip Compression
Compression is the way to delete redundant information and describe your information in as little space as possible. Compressing documents with gzip (GNUzip) can effectively reduce the time it takes to download HTML files. The smaller the amount of information you have, the faster they will be sent. Therefore, if you compress the content generated by your web application, the faster it reaches the user and appears on the user's screen. Not all browsers support gzip compression, but it's easy to check if a browser supports it and send gzip compressed content to the browser. The following code snippet shows how to send compressed content.
PublicvoiddoGet (HttpServletRequestrequest,HttpServletResponseresponse) throwsIOException,ServletException {OutputStreamout=null / / ChecktheAccepting-EncodingheaderfromtheHTTPrequest. / / Iftheheaderincludesgzip,chooseGZIP. / / Iftheheaderincludescompress,chooseZIP. / / Otherwisechoosenocompression. Stringencoding=request.getHeader ("Accept-Encoding"); if ("gzip")! =-1) {response.setHeader ("Content-Encoding", "gzip"); out=newGZIPOutputStream (response.getOutputStream ());} elseif ("compress")! =-1) {response.setHeader ("Content-Encoding", "compress"); out=newZIPOutputStream (response.getOutputStream ());} else {out=response.getOutputStream () }......}
Optimizing JSP Servlet Application Technology 5: do not use SingleThreadModel
SingleThreadModel guarantees that Servlet processes only one request at a time. If an Servlet implements this interface, the Servlet engine will create a separate Servlet instance for each new request, which will incur a lot of overhead. If you need to solve thread safety problems, please use another way to replace this interface. SingleThreadModel is no longer advocated in Servlet2.4.
Optimizing JSP Servlet Application Technology 6: using Thread Pool
The Servlet engine creates a separate thread for each request, assigns the thread to the service () method, and then deletes the thread after the service () method finishes execution. By default, the Servlet engine may create a new thread for each request. Because the cost of creating and deleting threads is expensive, this default behavior degrades system performance. We can use thread pools to improve performance. According to the expected number of concurrent users, configure a thread pool and set the minimum and * * values for the number of threads in the thread pool and the minimum and * * values for growth. Initially, the Servlet engine creates a thread pool with the number of threads equal to the minimum number of threads in the configuration. The Servlet engine then assigns a thread in the pool to a request instead of creating a new thread each time, and after completing the operation, the Servlet engine puts the thread back into the thread pool. Using thread pools, performance can be significantly improved. If necessary, more threads can be created based on the number of threads and the number of growth.
Optimize JSP Servlet application technology 7: choose the right inclusion mechanism
In a JSP page, there are two ways to include files: include instructions (<% @ includefile= "test.jsp"% >) and include actions (< jsp:includepage= "test.jsp" flush= "true" / >). Include instructions include the contents of a specified file during the compilation phase; for example, when a page is compiled into a Servlet. Include actions refer to the inclusion of file contents during the request phase; for example, when a user requests a page. Including instructions is faster than including. Therefore, unless the included files change frequently, the use of include instructions will achieve better performance.
Optimizing JSP Servlet Application Technology 8: using the appropriate scope in useBean actions
One of the major ways to use JSP pages is to work with JavaBean components. JavaBean can be embedded in a JSP page using the < jsp:useBean > tag. The syntax is as follows:
< jsp:useBeanid= "name" scope= "page | request | session | application" class= "package.className" type= "typeName" > < / jsp:useBean >
The scope property describes the visible range of the Bean. The default value of the scope property is page. You should choose the correct scope according to the needs of your application, otherwise it will affect the performance of the application.
For example, if you need an object dedicated to some request, but you set the scope to session, that object will remain in memory after the request ends. It will remain in memory unless you explicitly remove it from memory, invalidate session, or time out session. If you do not select the correct scope properties, the overhead of memory and garbage collection will affect performance. So set the appropriate scope for objects and delete them as soon as they are used up.
Optimize miscellaneous techniques for JSP Servlet applications
◆ avoids string concatenation: because String objects are immutable, using the "+" operator will result in a large number of 00:00 objects being created. The more "+" you use, the more 00:00 objects you will produce, which will affect performance. When you need to connect a string, use StringBuffer instead of the "+" operation.
◆ avoids using System.out.println:System.out.println to synchronize disk input / output, which greatly reduces system throughput. Avoid using System.out.println whenever possible. Although there are many mature debugging tools available, sometimes System.out.println is still useful for tracking, or debugging situations. You should configure System.out.println to open it only during the error and debugging phase. Using finalBoolean variables, when configured to false, the optimization check and trace output are performed during the compilation phase.
◆ ServletOutputStream compared to PrintWriter: using PrintWriter introduces a small performance overhead because of the character output stream and the encoding of data into bytes. Therefore, PrintWriter should be used after all character sets have been converted correctly. On the other hand, when you know that your Servlet only returns binary data, use ServletOutputStream because the Servlet container does not encode binary data, so you can eliminate character set conversion overhead.
The above is all the contents of the article "how to optimize JSP Servlet applications". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.