JBuilder2005 servlet Development Self-starter

Source: Internet
Author: User
Tags define object implement resource string access server memory stringbuffer
Servlet

A significant difference between a servlet and a JSP is that the servlet can use the Web.xml file configuration to have the servlet start the servlet automatically when the Web container is started. You can use the unchanged data from this feature of the servlet to load the Web application server beforehand for caching.

Assuming that the users of our system have been created before the system is deployed and will not change much later, we can cache the Web application when it is started by caching it in the Web application server memory, which can be manually invoked if the user changes. Here we create this usercacheservlet through the servlet Wizard, which automatically downloads and caches all user IDs and user names for the system when the Web container starts:

1. Start the Create Servlet Wizard, fill in the servlet name

Start the first step of creating the Servlet Wizard by file->new...->web-> double-clicking the standard servlet icon, as shown in the following illustration:


Figure 2 Completing the servlet name

In class name, fill in the servlet name: Usercacheservlet, and fill in the package with Bookstore.servlet as the package name. Press next to the next step.

2. Select the method that the servlet will implement.

We have previously described the way in which the servlet responds to HTTP requests through different doxxx () methods, and you can choose which doxxx () methods you want to define in step 2nd of the wizard. By default, the Doget () method is checked to access the servlet through an HTTP GET request. When a servlet is accessed through a URL with a parameter, the servlet responds to the request with the Doget () method. Since we just assume that the user data is not constantly changing, not that it never changes, so we want to automatically load the user data into the cache through Usercacheservlet when the Web container is initialized, and when the user data of the database table T_user is changed, We can manually invoke Usercacheservlet to flush the user data in the cache.

The Usercacheservlet is initialized automatically when the Web container is started, when the init () method is invoked, we can load the user data through the init () method, and when the user refreshes the user data through the URL request, Usercacheservlet passes Doget () Method responds to this HTTP GET request. That is, we need to implement the Doget () method, so we accept the default settings for the wizard, as shown in the following illustration:


Figure 3 Selecting the servlet response method to overwrite


Press Next to skip step 3rd through step 4th of the wizard.

3. Specify the path to access the servlet


Figure 4 Specifying the servlet access path


· Name of the Name:usercacheservlet,servlet in the Web.xml configuration file

· URL Pattern:/usercacheservlet to access this servlet's matching path. After you specify this access path, if the Web application is deployed under Http://localhost:8080/webModule, the servlet is accessed through Http://localhost:8080/webModule/usercacheservlet.

Create a servlet directly by pressing finish.

Open the Web.xml file and you can find deployment description information about the Usercacheservlet declaration and access:

• node: Describes the name and class name of the servlet.

• node: Describes the servlet access matching path.

Double-click the Webmodule node of the Project pane resource tree, Jbuider open the Web Module DD Editor (Web module DD Editor) for editing web.xml files in the content pane, where the structure pane displays the structure of the Web.xml file, as shown in the following illustration:


Figure 5 The Web.xml file structure tree of the structure pane


A node with an icon indicates that there is already a configuration content, and a node without an icon indicates that there is no corresponding configuration content for the time being. We expand the Servlets node, navigate to Usercacheservlet and double-click the node, and the DD editor adjusts the interface to the Usercacheservlet this servlet configuration, as shown in the following figure:


Figure 6 DD Editor


The servlet can be initialized automatically when the Web container is started. Assuming that multiple servlet needs to be initialized automatically, you can set the order of startup through the Web.xml . We set the load on startup value to 2 in the DD editor so that Usercacheservlet is initialized in order 2 after the Web container starts.

The servlet that some systems use, because it is the foundation of the Web start service must be in order 1, the servlet we develop is best initialized in order 2 or sequence 3. The init () method is invoked when the servlet is initialized. After you make this setting, Web.xml will contain the configuration information shown in bold below.

Code Listing 1 Web.xml descriptive information about Usercacheservlet

1. The
2...
3. The
4. Usercacheservlet
5. Bookstore.servlet.UserCacheServlet
6. 2
7. The
8. The
9. Usercacheservlet
/usercacheservlet
One.

12...


Attention:

When Usercacheservlet is removed, the deployment description information for the servlet in Web.xml is not deleted together, and you must delete it manually.

In the init () initialization method, the Userlist.filluser () method is used to download and cache user record information from the database, and Userlist.filluser () is also referenced in the Doget () method. When a user accesses usercacheservlet through a URL, the Doget () method is invoked, the cached user data is refreshed, and the "refresh success" prompt is displayed, and the code looks like this:

Code Listing 2 Usercacheservlet.java

1. Package bookstore.servlet;
2.
3. Import javax.servlet.*;
4. Import javax.servlet.http.*;
5. Import java.io.*;
6.Import Bookstore. userlist;
7.
8. public class Usercacheservlet
9. Extends HttpServlet
10. {
One. private static final String Content_Type = "text/html;" CHARSET=GBK ";
12.
//initialize Global Variables
public void Init ()
Throws Servletexception
16. {
17.Userlist.filluser ();Called after the Web container starts
18.}
19.
//process the HTTP GET request
public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException
23. {
24.Userlist.filluser ();Refreshing user data
Response.setcontenttype (Content_Type);
PrintWriter out = Response.getwriter ();
Out.println ("Out.println ("Out.println ("<body bgcolor=\" #ffffff \ ">");
Out.println ("Refresh succeeded!") ");
Out.println ("</body>");
Out.println ("Out.close ();
34.}

Of course, we have to JBuilder 2005 Practical JSP DevelopmentThe Userlist.java code created in the topic is changed to define the Filluser () method for Usercacheservlet.java calls, and the original getuserlisthtml () method needs to be adjusted as follows:

Code Listing 3 Adjusted Userlist.java code

2. Package bookstore;
3.
4. Import java.sql.*;
5.import java.util.*;
6.
7. public class UserList
8. {
9.private static Map UserMap;Map of User ID and user name
10.//cache user data in map
One. public static void Filluser ()
12. {
if (UserMap = null)
14. {
UserMap = new HashMap ();
} else
17. {
Usermap.clear ();
19.}
Connection conn = null;
StringBuffer sbuf = new StringBuffer ();
Try
23. {
conn = Dbconnection.getconnection ();
PreparedStatement PStat = conn.preparestatement (
"Select User_id,user_name from T_user");
ResultSet rs = Pstat.executequery ();
while (Rs.next ())
29. {
Usermap.put (rs.getstring (1), rs.getstring (2));
31.}
The catch (SQLException ex)
33. {
Ex.printstacktrace ();
.} finally
36. {
Panax Notoginseng. Try
38. {
IF (conn!= null)
40. {
Conn.close ();
conn = null;
43.}
A catch (SQLException Ex1)
45. {
Ex1.printstacktrace ();
47.}
48.}
.}

50.
51.//Get the HTML dropdown box user list code
public static String getuserlisthtml ()
53. {
StringBuffer sbuf = new StringBuffer ();
Set set = Usermap.keyset ();
Iterator iter = Set.iterator ();
while (Iter.hasnext ())
58. {
Object item = (object) iter.next ();
Sbuf.append ("" +
Usermap.get (item) + " \ n");
62.}
Sbuf.tostring return ();

64.}
65.}

First, we define a static UserMap object in line 9th to cache the user information, which holds the username value as a userid key. The static Filluser () method on line 11th to 49th populates the UserMap with information from the database that gets the user. When a user accesses the login.jsp build user drop-down box, the user data is read directly from the UserMap cache and is no longer read from the database, and you can see the change in the way the user data is obtained from the 54th to 56th line of code. When you add or remove users, you can refresh the cached data by Http://localhost:8080/webModule/usercacheservlet.

   Practical Experience

Using caching to save infrequently changing data is an important way to improve system performance. If your Web server does not implement the cluster, refreshing the cached data is simple, simply by using a servlet to refresh when data changes occur. If the Web server uses a cluster, the problem becomes complicated, because each Web server's JVM is separate, so each Web server has a separate cache of data, and when data changes, the cache must be refreshed on each Web server. Here are two solutions, one of which is to use a dedicated shared resource machine that is independent of the Web server to cache data, and all Web servers in the cluster access the cached data through Jndi. Another method is to sync to other machines in the cluster with any server cached data being changed through the synchronization mechanism. The JCS subproject of the Apache turbine project is developed specifically to address this enterprise-class problem, and you can learn more about JCS through http://jakarta.apache.org/jcs/index.html.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.