Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How Java promotes JSP applications

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail how Java improves JSP applications, Xiaobian feels quite practical, so share it with you as a reference, I hope you can gain something after reading this article.

Method 1: Cache data in servlet init() method

After the application server initializes the servlet instance and before servicing the client request, it calls the servlet's init() method. During the life cycle of a servlet, the init() method is called only once. By caching some static data in the init() method or performing some time-consuming operation that only needs to be performed once, system performance can be greatly improved.

For example, by creating a JDBC connection pool in the init() method is a good example, assuming we are using jdbc2.0 DataSource interface to get database connections, in general we need to get specific data sources through JNDI. We can imagine that in a specific application, if we had to perform a JNDI lookup every time SQL requests were made, system performance would drop dramatically. The workaround is the following code, which caches the DataSource so that it can still be used the next time SQL is invoked:

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 servlets and JSP auto-reloading

Servlet/JSP provides a practical technology, namely automatic overload technology, it provides a good development environment for developers, when you change servlets and JSP pages without having to restart the application server. However, this technique is a significant drain on system resources during the production run because it places a significant burden on the JSP engine's classloader. Therefore, turning off the automatic reload function is a great help to improve the system performance.

Method 3: Don't abuse HttpSession

In many applications, our programs need to maintain client-side state so that pages can relate to each other. Unfortunately, HTTP is inherently stateless and therefore cannot preserve client state. Therefore, most application servers provide sessions to save the state of the client. In JSP application server, the function of session is realized through HttpSession object, but it also brings a lot of burden to the system. Because every time you get or update a session, the system operator has to serialize it in a time-consuming way. You can improve system performance by handling HttpSession in several ways:

? If not necessary, turn off the default setting for HttpSession in JSP pages: Every JSP page creates an HttpSession by default if you don't specify it explicitly. If you don't need to use sessions in your JSP, you can disable them by using the JSP page indicator:

<%@ page session="false"%>

? Do not store large data objects in HttpSession: If you store large data objects in HttpSession, the application server will serialize them every time you read or write to them, adding extra burden to the system. The larger the data object you store in HttpSession, the faster the performance of the system degrades.

? When you no longer 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.

? Try to keep session timeouts short: In JSP application servers, there is a default session timeout. When the client does not perform any operation after this time, the system will automatically release the relevant session from memory. The larger the timeout, the lower the performance of the system, so it is best to keep it as low as possible.

Method 4: Compress the page output

Compression is a good way to solve data redundancy, especially in today's less developed network bandwidth. Some browsers support gzip(GNU zip) for compressing HTML files, which can dramatically reduce the download time of HTML files. Therefore, if you compress HTML pages generated by servlets or JSP pages, users will feel that the page browsing speed will be very fast. Unfortunately, not all browsers support gzip compression, but you can check in your application to see if the client's browser supports it. Here's a snippet of code for an implementation of this approach:

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: Using Thread Pools

By default, the application server creates a thread for each different client request to process, dispatches a service() method to them, and when the service() method call completes, the corresponding thread is dropped. This default mode degrades system performance because creating and dropping threads consumes system resources. Fortunately, we can change this by creating a thread pool. In addition, we also set a minimum thread count and a maximum thread count for this thread pool. When the application server starts, it creates a thread pool equal to the minimum number of threads, takes a thread from the pool to process when the client requests it, and puts it back into the pool when the process is complete. If there are not enough threads in the pool, the system automatically increases the number of threads in the pool, but the total number cannot exceed the maximum number of threads. By using thread pools, the load on the system presents a smooth upward curve when client requests increase sharply, thereby improving the scalability of the system.

Method 6: Choosing the Right Page Inclusion Mechanism

There are two ways to include another page in JSP: 1. Use the include directive (<%@ include file="test.jsp" %>). Use the jsp indicator (). In practice, I have found that using the first method can lead to higher system performance.

Method 7: Properly Determining the Life Cycle of Javabean

One of the strengths of JSP is its javabean support. By using tags in JSP pages, javabean can be inserted directly into a JSP page. It is used as follows:

"package.className" type="typeName">

The scope attribute indicates the lifecycle of the bean. The default lifecycle is page. If you don't choose the bean lifecycle correctly, it will affect system performance.

For example, if you only want to use a bean in a single request, but you set the bean's lifecycle to session, the bean will remain in memory after the request ends unless the session times out or the user closes the browser. This consumes memory and unnecessarily increases the workload of the JVM garbage collector. So setting the bean's life cycle correctly and cleaning them up as soon as possible after the bean's mission ends will give you a boost in system performance.

Other useful methods

? Avoid using the "+" operator in string concatenation operations: in java programming, we often use the "+" operator to concatenate several strings, but you probably never thought it would affect system performance, right? Because strings are constants, the JVM generates temporary objects. The more "+" you use, the more temporary objects you generate, which also has some impact on system performance. The solution is to replace the "+" operator with a StringBuffer object.

? Avoid System.out.println(): Since System.out.println() is a synchronous call, i.e. disk I/O operations must wait for it to complete when it is called, we try to avoid calling it. But it is also an essential convenience tool when debugging programs. To solve this contradiction, I suggest you use Log4j tool (Jakarta.apache.org), which can facilitate debugging without generating System.out.println() method.

? ServletOutputStream vs. PrintWriter trade-offs: PrintWriter may incur a small overhead because it converts all raw output to a character stream for output, so the system incurs a conversion process if it is used as page output. Using ServletOutputStream as page output does not present a problem, but it is output in binary. Therefore, in practical application, we should weigh the advantages and disadvantages of both.

About "Java how to improve JSP applications" this article is shared here, I hope the above content can be of some help to everyone, so that you can learn more knowledge, if you think the article is good, please share it to let more people see.

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: 292

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

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report