JSP message board program-development process

Source: Internet
Author: User

This article is from Sina Blog:Blog http://blog.sina.com.cn/liulijuan500

In this section, we add a message board to the online bookstore so that readers can post a book. The message board usually uses paging display when displaying users' messages, because thousands or even tens of thousands of messages may be stored in the database. If it is displayed on a page, it will surely make users dizzy. More importantly, it takes a lot of processing time to display thousands of records at a time, which will make the user wait for a long time, which is intolerable. In this example, we will introduce you to an efficient paging query technology. To develop an instance, follow these steps.

Step 1: Create a guestbook table

First, create a database table guestbook that stores users' messages in the bookstore database. In this example, if you use the MySQL database, you can select another database, open the Command Prompt window, and enter:

Mysql-uroot-p12345678 bookstore

Go to the mysql client program and access the bookstore database. Enter the SQL statement for creating the guestbook Table, as follows:

Create table guestbook (

Stst_id INT AUTO_INCREMENT not null primary key,

Gst_user VARCHAR (10) not null,

Gst_title VARCHAR (100) not null,

Ststst_content TEXT,

Stst_time TIMESTAMP not null,

Gst_ip VARCHAR (15) not null );

The structure of the guestbook table is shown in Table 12-4.

Table 12-4 Structure of the guestbook table

Field description

The primary key and integer of the stst_id bookinfo table. Set the AUTO_INCREMENT attribute,
Automatically increase the value of this column from 1

The username of the message, which is a string of the stst_user type. It cannot be blank.

The string type of the message. The title of the message. It cannot be blank.

Ststst_content text string type,Message Content, Can be empty

Stst_time TIMESTAMP type, message time

The user's IP address of the string type of gst_ip

Step 2: configure the running directory of the message board program and the JDBC Data Source

In the % CATALINA_HOME % \ conf \ Catalina \ localhost directory, create a ch12.xml file and edit the file, as shown in example 12-4.

Example 12-4 ch12.xml
<Context path = "/ch12" docBase = "F: \ JSPLesson \ ch12" reloadable = "true">
<Resource name = "jdbc/bookstore" auth = "Container" type = "javax. SQL. DataSource"
MaxActive = "100" maxIdle = "30" maxWait = "10000"
Username = "root" password = "12345678"
DriverClassName = "com. mysql. jdbc. Driver"
Url = "jdbc: mysql: // localhost: 3306/bookstore? AutoReconnect = true "/>
</Context>

Step 3: Compile say.html
Enter the message on the say.html page. Put the compiled say.html file in the F: \ JSPLesson \ ch12 \ gst directory. Complete code is shown in example 12-5.

Example 12-5 say.html
<Center>
<Form action = "process.Jsp"Method =" post ">
<Table bgcolor = "# B3B3FF">
<Caption> welcome to the message board </caption>
<Tr>
<Td> User name: </td>
<Td> <input type = "text" name = "name"> </td>
</Tr>
<Tr>
<Td> topic: </td>
<Td> <input type = "text" name = "title" size = "40"> </td>
</Tr>
<Tr>
<Td> content: </td>
<Td>
<Textarea name = "content" rows = "10" cols = "40"> </textarea>
</Td>
</Tr>
<Tr>
<Td> <input type = "submit" value = "submit"> </td>
<Td> <input type = "reset" value = "Refill"> </td>
</Tr>
</Table>
</Form>
</Center>

Step 4: Write util.Jsp
Util.JspContains a static tool method toHtml (), used to convert reserved characters and some special characters in HTML. Write util.JspPut the file in the F: \ JSPLesson \ ch12 \ gst directory. Complete source code is shown in example 12-6.

Example 12-6 util.Jsp
<%!
Public static String toHtml (String str)
{
If (str = null)
Return null;
StringBuffer sb = new StringBuffer ();
Int len = str. length ();
For (int I = 0; I <len; I ++)
{
Char c = str. charAt (I );
Switch (c)
{
Case '':
Sb. append ("");
Break;
Case '\ N ':
Sb. append ("<br> ");
Break;
Case '\ R ':
Break;
Case '\'':
Sb. append ("'");
Break;
Case '<':
Sb. append ("<");
Break;
Case '> ':
Sb. append ("> ");
Break;
Case '&':
Sb. append ("&");
Break;
Case '"':
Sb. append (""");
Break;
Case '\\':
Sb. append ("\");
Break;
Default:
Sb. append (c );
}
}
Return sb. toString ();
}
%>

When you leave a message, you may enter some special characters. If we do not convert these characters, the data entered by the user will not be properly displayed. For example, the user inputs the following data:

<? Xml version = "1.0" encoding = "gb2312"?>

If the XML declaration is not converted, the browser will not display the data.

In some network applications that require users to submit data online, such as forums, the reserved characters and special characters should be converted accordingly. On the one hand, the data can be properly displayed, the security of Web applications is also guaranteed (see section 23.5 ).

Step 5: Write process.Jsp
Process.JspUsed to insert a user's message to the database. Edit process.Jsp, CompiledJSPPut the file in the F: \ JSPLesson \ ch12 \ gst directory. Complete source code is shown in example 12-7.

Example 12-7 process.Jsp
1. <% @ page contentType = "text/html; charset = gb2312" %>
2. <% @ page import = "java. SQL. *, javax. SQL. *, javax. naming. *" %>
3. <% @ include file = "util.Jsp"%>
4.
5. <%
6. request. setCharacterEncoding ("gb2312 ");
7.
8. String name = request. getParameter ("name ");
9. String title = request. getParameter ("title ");
10. String content = request. getParameter ("content ");
11.
12. if (null = name | null = title | null = content)
13 .{
14. response. sendRedirect ("index.Jsp");
15. return;
16 .}
17.
18. name = toHtml (name. trim ());
19. title = toHtml (title. trim ());
20. if (name. equals ("") | title. equals (""))
21 .{
22. response. sendRedirect ("say.html ");
23. return;
24 .}
25. content = toHtml (content. trim ());
26. String fromIP = request. getRemoteAddr ();
27.
28. Context ctx = new InitialContext ();
29. DataSource ds = (DataSource) ctx. lookup ("java: comp/env/jdbc/bookstore ");
30. Connection conn = ds. getConnection ();
31.
32. PreparedStatement pstmt = conn. prepareStatement (
33. "insert into guestbook (stst_user, ststst_title, stst_content, stst_ip) values (?,?,?,?) ");
34. pstmt. setString (1, name );
35. pstmt. setString (2, title );
36. pstmt. setString (3, content );
37. pstmt. setString (4, fromIP );
38.
39. pstmt.exe cuteUpdate ();
40. pstmt. close ();
41. conn. close ();
42. response. sendRedirect ("index.Jsp");
43. %>

Line 2 of the Code uses the contentType attribute of the page command to set the MIME type of the page to text/html and the character encoding to gb2312. Line 3: Use the page command import attribute to import the Java class to be used on the page. Line 3: Use the include command to include util.JspIn this way, you can use the toHtml () method on the page.

The second line sets the character encoding used by the request body to gb2312.

12th ~ Line 16: determines whether the parameter objects of name, title, and content are null. Generally, users access the say.html page and indirectly call process.Jsp. The parameter objects of name, title, and content are not empty. However, to prevent users from directly accessing process.JspPage, leading to null pointer exception, so here we make a judgment, if any parameter object is null, the client will be redirected to index.JspPage.

18th ~ Line 19: remove the spaces before and after the user name and title, and then call toHtml () to process the special characters in the user name and title. 20th ~ In 24 rows, determine whether the user name and title are empty. If so, ask the user to re-enter the message. In our message board program, the user name and title must not be blank, but the content can be blank. Therefore, we can only judge whether the user name and title are empty.

In row 3, call the getRemoteAddr () method of the request object to obtain the IP address of the client. If the user accesses the Internet through the proxy server, the IP address obtained here will be the IP address of the proxy server.

28th ~ 30 rows. Use the data source object to establish a database connection.

32nd ~ Line 39:Message ContentAnd the client IP addresses are stored in the database's guestbook table. Note: here, we have not inserted the message time because the type of the field stst_time that stores the message time is TIMESTAMP. in MySQL, if NULL is inserted in a TIMESTAMP column, alternatively, if the TIMESTAMP column is not assigned a value when a new row is inserted, MySQL automatically sets the column to the current date and time. In this way, when inserting a record, you do not need to consider the current time of insertion. This method ensures that the current date and time of the message are correctly recorded. However, it should be noted that this uses the features provided by MySQL itself. If the reader uses other databases, another method should be used to insert the current date and time.

Step 6: Compile the index.Jsp
Index.JspIs the homepage of the message board, used to display users' messages. Edit index.Jsp, CompiledJSPPut the file in the F: \ JSPLesson \ ch12 \ gst directory. Complete source code is shown in example 12-8.

Example 12-8 index.Jsp
1. <% @ page contentType = "text/html; charset = gb2312" %>
2. <% @ page import = "java. SQL. *, javax. SQL. *, javax. naming. *" %>
3.
4. 5. 6. <title> online bookstore message board </title>
7. 8. <body>
9. <a href = "/say.html"> Leave a message </a> <br>
10. <%
11. Context ctx = new InitialContext ();
12. DataSource ds = (DataSource) ctx. lookup ("java: comp/env/jdbc/bookstore ");
13. Connection conn = ds. getConnection ();
14.
15. // create a scrollable result set.
16. Statement stmt = conn. createStatement (
17. ResultSet. TYPE_SCROLL_INSENSITIVE,
18. ResultSet. CONCUR_READ_ONLY );
19. ResultSet rs1_stmt.exe cuteQuery ("select * from guestbook order by maid ");
20.
21. // move the cursor to the last row of the result set.
22. rs. last ();
23.
24. // obtain the number of rows in the current row, and obtain the total number of messages in the database.
25. int rowCount = rs. getRow ();
26. if (rowCount = 0)
27 .{
28. out. println ("there are no messages currently! ");
29. return;
30 .}
31.
32. String strCurPage = request. getParameter ("page ");
33.
34. // indicates the current page number.
35. int curPage;
36.
37. if (strCurPage = null)
38. curPage = 1;
39. else
40. curPage = Integer. parseInt (strCurPage );
41.
42. // define the number of messages displayed on each page.
43. int countPerPage = 5;
44.
45. // calculate the total number of pages required for all messages.
46. int pageCount = (rowCount + countPerPage-1)/countPerPage;
47.
48. // move the cursor to the row specified in the result set. If the first page is displayed, curPage = 1,
49. // move the cursor to row 1st.
50. rs. absolute (curPage-1) * countPerPage + 1 );
51.
52. // If the page is 1st, the text without link is displayed. If the page is not 1st,
53. // you are provided with a link to jump to the first page and the previous page.
54. if (curPage = 1)
55 .{
56. %>
57. Page 1
58. Previous Page
59. <%
60 .}
61. else
62 .{
63. %>
64. <a href = "index.Jsp? Page = <% = 1%> "> page 1 </a>
65.
66. <a href = "index.Jsp? Page = curPage-1 %> "> previous </a>
67.
68. <%
69 .}
70. // if the current page is the last page, text without links is displayed. If it is not the last page,
71. // you will be given a link to jump to the last and next pages.
72. if (curPage = pageCount)
73 .{
74.
75. %>
76. Next page
77. Last Page
78. <%
79 .}
80. else
81 .{
82. %>
83. <a href = "index.Jsp? Page = <% = curPage + 1%> "> next page </a>
84.
85. <a href = "index.Jsp? Page = <% = pageCount %> "> last page </a>
86.
87. <%
88 .}
89.
90. int I = 0;
91.
92. // retrieve the data to be displayed on each page in a loop, because in the previous section,
93. // call rs. absolute (curPage-1) * countPerPage + 1 );
94. // Therefore, the data to be displayed on the current page is retrieved from the cursor location.
95. while (I <countPerPage &&! Rs. isAfterLast ())
96 .{
97. out. println ("98. out. println ("username:" + rs. getString ("maid "));
99. out. println ("");
100.
101. Timestamp ts = rs. getTimestamp ("maid ");
102. long lms = ts. getTime ();
103. Date date = new Date (lms );
104. Time time = new Time (lms );
105.
106. out. println ("message time:" + date + "" + time );
107.
108. out. println ("");
109. out. println ("user IP:" + rs. getString ("maid") + "<br> ");
110. out. println ("topic:" + rs. getString ("maid") + "<br> ");
111. out. println ("content:" + rs. getString ("maid "));
112. I ++;
113. rs. next ();
114 .}
115. rs. close ();
116. stmt. close ();
117. conn. close ();
118. %>
119. </body>
120. The paging function of the message board is implemented on this page. The main idea is to move the cursor to the corresponding position based on the number of pages to be displayed and the number of messages displayed on each page by using a scrollable result set, then read the number of messages displayed on each page. In the implementation process, it mainly refers to the logical organization, for example, how to calculate the total number of pages, how to determine which page of messages the user wants to view (by attaching a query parameter after the URL ), when should the links on the first, previous, next, and last pages take effect. Readers can carefully understand this code.

This Code adds comments, so we will not detail them here. However, there is a need to remind readers that the code is 101st ~ In row 3, we made some conversions after taking out the message time. Call the getTime () method of the Timestamp class to return the number of milliseconds that have elapsed since January 1, 1970, and 00:00:00 GMT. Then, use this number of milliseconds to construct java. SQL. date object (indicating the Date of the message) and java. SQL. the Time object (indicating the message Time), and the two objects are used together.Output MessageTime. Why not use the Timestamp object to output the time directly? This is because if ts. toString () is used directly to output the time, the following time values will be obtained:
19:35:04. 0
Note that there is a ". 0" after the number of seconds, which is a problem with the Java language display time. If you do not want to see the last ". 0 ", one way is to remove" from the time string through string operations. 0 ", the other way is the method provided by the author to the reader above.
Step 7: run the message board program
Start Tomcat server, open IE browser, and enter http: // localhost: 8080/ch12/gst/index in the address bar.JspThe page shown in 12-2 is displayed.

Figure 12-2 displays the message page-No message currently
Click "I want to leave a message" to view the page 12-3.
EnterMessage ContentClick Submit. The page shown in 12-4 is displayed.


Figure 12-3 user message page Figure 12-4 displays the message page-there is a message
Readers can continue to leave messages. When there are more than six messages, the text on the "next page" and "last page" will become hyperlinks, as shown in figure 12-5.

Figure 12-5 displays the page for messages-6 messages
If you click the next page, the next page is displayed. The text on the first page and previous page is a hyperlink.

 

Http://cache.baiducontent.com/c? M = login & p = 8979c64ad7c02de043bd9b7e0c14c123 & newp = login & user = baidu & fm = SC & query = jsp % CA % E4 % B3 % F6 % C1 % F4 % D1 % D4 % b5 % C4 % C4 % DA % C8 % DD & qid = & p1 = 1)

Related Article

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.