Servlet & JSP (12)

Source: Internet
Author: User

In this article, we develop a JSP instance to implement a message board program. The database knowledge discussed in the previous servlet & JSP events (11) also paves the way for instance development. In addition, let's review the JSP knowledge discussed in servlet & JSP (10. Okay. Let's get started ~

1) create a message table

Create a messageboard database and create a message table in the database to store messages. Of course, the MySQL database is used. Enter the DOS environment and enter the following command to enter the database:

mysql -uroot -pshan

-U is followed by the user name and-P is followed by the password. Create the database messageboard and enter the following statement:

create database MessageBoard;

Then switch to the database messageboard using the following statement,

use MessageBoard;

Finally, use the following statement to create a message table:

create table Message(id INT AUTO_INCREMENT not null primary key,user VARCHAR(20) not null,title VARCHAR(100) not null,content TEXT,time TIMESTAMP not null,ip VARCHAR(20) not null);

The meaning of each item can be understood in English.

2) configure the program running directory and JDBC Data Source

We use the database connection pool method here, so we need to create a new configuration file. Create a web project directory messageboard in the d: \ apache-Tomcat-7.0.33 \ webapps \ folder. Create a new WEB-INF folder and a META-INF folder under the messageboard folder. Under the META-INF folder, create the context. xml file and edit the file content, as shown below:

<Context><Resource name="jdbc/messageboard" auth="Container"type="javax.sql.DataSource"maxActive="100" maxIdle="30" maxWait="10000"username="root" password="shan"driverClassName="com.mysql.jdbc.Driver"url="jdbc:mysql://localhost:3306/messageboard?autoReconnect=true"/></Context>

3. Compile message.html

Then, create the message.html file under the messageboardfolder to fill in the message information. The file content is as follows:

<Center> <form action = "process. JSP "method =" Post "> <Table bgcolor =" # b3b3ff "> <caption> welcome to the message board </caption> <tr> <TD> User Name: </TD> <input type = "text" name = "name"/> </TD> </tr> <TD> subject: </TD> <input type = "text" name = "title" size = "40"/> </TD> </tr> <TD> content: </TD> <textarea name = "content" rows = "10" Cols = "40"> </textarea> </TD> </tr> <tr> <TD> <input type = "Submit" value = "Submit"/> </TD> <input type = "reset" value = "Refill"/> </TD> </tr> </table> </form> </center>

4) Write util. jsp

Then, write util. jsp in the messageboard folder to process some special characters. The content is as follows:

<%!  public static String toHtml(String str) {    if(str == null) {      return null;    }    StringBuffer sb = new StringBuffer();    for(int i = 0; i < str.length(); 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);        break;      }    }    return sb.toString();  }%>

5) compile process. jsp

Then, write process. jsp in the messageboard folder to insert users' messages to the database.

<% @ Page contenttype = "text/html; charset = gb2312" %> <% @ page import = "Java. SQL. *, javax. SQL. *, javax. naming. * "%> <% @ include file =" util. JSP "%> <% // set the body encoding format request. setcharacterencoding ("gb2312"); string name = request. getparameter ("name"); String title = request. getparameter ("title"); string content = request. getparameter ("content"); // if the user is a citizen, the title, one of the content is null, redirect to the home page if (null = Name | null = title | nu LL = content) {response. sendredirect ("index. JSP "); return;} name = tohtml (name. trim (); Title = tohtml (title. trim (); If (name. equals ("") | title. equals ("") {response. sendredirect ("message.html"); return;} content = tohtml (content. trim (); string fromip = request. getremoteaddr (); // use the data source object to establish a database connection context CTX = new initialcontext (); datasource DS = (datasource) CTX. lookup ("Java: COMP/ENV/jdbc/Messa Geboard "); connection conn = Ds. getconnection (); preparedstatement pstmt = Conn. preparestatement ("insert into message (user, title, content, ip) values (?,?,?,?) "); Pstmt. setstring (1, name); pstmt. setstring (2, title); pstmt. setstring (3, content); pstmt. setstring (4, fromip); pstmt.exe cuteupdate (); pstmt. close (); Conn. close (); response. sendredirect ("index. JSP "); %>

Note: There is no message insertion time in this file, because in MySQL, if a timestamp type data item is empty, MySQL will automatically Insert the current date into a new row. When using other databases, you must use another method to insert the current date and time.

6) Compile index. jsp

In the messageboard folder, compile index. jsp for the homepage of the message board to display users' messages, including the paging function. The Code is as follows:

<% @ Page contenttype = "text/html; charset = gb2312" %> <% @ page import = "Java. SQL. *, javax. SQL. *, javax. naming. * "%> <HTML> 

7) running result

Shenma is too troublesome. So it is no longer. You can follow these steps and enter http: // localhost: 8080/messageboard/index. jsp in the browser URL bar. By the way, you forget the important step. You need to put the downloaded driver in the Lib folder in the tomcat installation folder so that the Tomcat server can find the MySQL driver. You must understand that Tomcat needs a driver to access the database using the data source provided by Tomcat, rather than an application needs a driver.

In addition, if you do not place the application under the webapps directory, you must. configure context in XML. or create a messageboard in D: \ apache-Tomcat-7.0.33 \ conf \ Catalina \ localhost. XML, set context. copy the content of the XML file to the file, and the server. like XML, you need to change the file content as follows:

<Context docbase = "file directory (for example, D: \ messageboard)"> <Resource Name = "JDBC/messageboard" auth = "Container" type = "javax. SQL. datasource "maxactive =" 100 "maxidle =" 30 "maxwait =" 10000 "username =" root "Password =" Shan "driverclassname =" com. mySQL. JDBC. driver "url =" JDBC: mysql: // localhost: 3306/messageboard? Autoreconnect = true "/> </context>

Okay, that's all. We have reviewed some of the database knowledge and some of the previous JSP knowledge, which is the purpose of this Article. By the way, the entire web project is here:Click to download 

Reprinted please indicate the source: http://blog.csdn.net/iAm333

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.