java实现简单留言板功能的代码实例

时间:2024-03-09 15:12:20

java实现简单留言板功能的代码实例

数据库对应的表:

guestbook:id ,name,phone,email,title,content,time;                   <pk>id

新建web project:guestbook

build Path:引入连接数据库的驱动的类库

在webRoot目录中加入:

+faceditor

+js

web.xml

代码:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <servlet-name>AddMessageServlet</servlet-name>
    <servlet-class>webbook.guestbook.AddMessageServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>GetMessagesServlet</servlet-name>
    <servlet-class>webbook.guestbook.GetMessagesServlet</servlet-class>
  </servlet>
 
   <servlet-mapping>
    <servlet-name>AddMessageServlet</servlet-name>
    <url-pattern>/servlet/addMessage</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>GetMessagesServlet</servlet-name>
    <url-pattern>/servlet/getMessages</url-pattern>
  </servlet-mapping> 
</web-app>

addMessage.htm

代码:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/css" src="/guestbook/js/validation-framework.js"></script>
<script type="text/javascript" src="/guestbook/fckeditor/fckeditor.js"></script>
<title>add message</title>
</head>
<body>
 <p align="center">请您输入留言</p>
  <p align="center"><a href="/guestbook/servlet/getMessages">查看留言</a></p>
<form id="form1" name="form1" method="post" action="/guestbook/servlet/addMessage" onsubmit="return doValidate(this)">
  <table width="600" height="400" border="0" align="center">
    <tr>
      <td width="100">姓名:</td>
      <td width="500">
        <input name="name" type="text" id="name" size="40" maxlength="20" />
      </td>
    </tr>
    <tr>
      <td>E-Mail:</td>
      <td>
        <input name="email" type="text" id="email" size="40" maxlength="40" />
      </td>
    </tr>
    <tr>
      <td>电话:</td>
      <td>
        <input name="phone" type="text" id="phone" size="40" maxlength="20" />
      </td>
    </tr>
    <tr>
      <td>主题:</td>
      <td>
        <input name="title" type="text" id="title" size="80" maxlength="80" />
      </td>
    </tr>
    <tr>
      <td valign="top">内容:</td>
      <td>
  <script type="text/javascript">
      var oFCKeditor = new FCKeditor("content");   
      oFCKeditor.BasePath = \'/guestbook/fckeditor/\' ;
      oFCKeditor.Height = 300 ;
   oFCKeditor.ToolbarSet = \'Basic\';
   oFCKeditor.Create() ;
  </script>
 </td>
    </tr>
    <tr>
      <td></td>
      <td>
         <input type="submit" name="Submit" value="提交" />
         <input type="reset" name="Reset" value="重置" />
      </td>
    </tr>  
  </table>
</form>
</body>
</html>

content.html


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>display content</title>
</head>

<body>
<div align="center">
留言内容
<br />
<br />

  <table width="357" height="107" border="1">
    <tr>
      <td width="48" >编号</td>
      <td width="293" align="left">12</td>
    </tr>
    <tr>
      <td>姓名</td>
      <td align="left">liuwei</td>
    </tr>
    <tr>
      <td>电话</td>
      <td align="left">2922266</td>
    </tr>
    <tr>
      <td>email</td>
      <td align="left">phpa@www.3ppt.com</td>
    </tr>
    <tr>
      <td>主题</td>
      <td align="left">you can test </td>
    </tr>
    <tr height="50">
      <td valign="top">内容</td>
      <td valign="top" align="left">test content! </td>
    </tr>
  </table>
  <p>&nbsp;</p>

<table width="357" height="107" border="1" align="center">
  <tr>
    <td width="48">编号</td>
    <td width="293">&nbsp;</td>
  </tr>
  <tr>
    <td>姓名</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>电话</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>email</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>主题</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>内容</td>
    <td>&nbsp;</td>
  </tr>
</table>
<p>&nbsp;</p>

<table width="357" height="107" border="1" align="center">
  <tr>
    <td width="48">编号</td>
    <td width="293">&nbsp;</td>
  </tr>
  <tr>
    <td>姓名</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>电话</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>email</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>主题</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td><p>内容</p>
        <p>&nbsp;</p>
      <p>&nbsp;</p></td>
    <td>&nbsp;</td>
  </tr>
</table>

</div>
</body>

</html>

validation-config.xml

代码;

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE validation-config SYSTEM "validation-config.dtd">
<validation-config lang="auto">
 <form id="form1" show-error="alert" show-type="all">
  <field name="name" display-name="姓名" onfail="">
   <depend name="required" />
   <depend name="minLength" param0="2" />
   <depend name="maxLength" param0="20" />
  </field>
  <field name="title" display-name="主题">
   <depend name="required" />
  </field>
  <field name="email" display-name="email">
   <depend name="email" />
  </field> 
 </form>
</validation-config>

---------------------------------------------------------------------

******************************************************

这是一个很有用的工具类,包含了:

  判读字符串参数是否为空:validateNull(String args)

  判断输入的字符串参数是否为空或者是"null"字符:chanageNull(String source, String target)

  过滤<, >,n 字符的方法:filterHtml(String input)

*****************************************************

---------------------------------------------------------------------

StringUtil.java

代码:

package webbook.util;

public class StringUtil {

 /**
  * 判断输入的字符串参数是否为空。
  * @param args 输入的字串
  * @return true/false
  */
 public static boolean validateNull(String args) {
  if (args == null || args.length() == 0) {
   return true;
  } else {
   return false;
  }
 }

 /**
  * 判断输入的字符串参数是否为空或者是"null"字符,如果是,就返回target参数,如果不是,就返回source参数。
  */
 public static String chanageNull(String source, String target) {
  if (source == null || source.length() == 0 || source.equalsIgnoreCase("null")) {
   return target;
  } else {
   return source;
  }
 }

 /**
  * 过滤<, >,n 字符的方法。
  * @param input 需要过滤的字符
  * @return 完成过滤以后的字符串
  */
 public static String filterHtml(String input) {
  if (input == null) {
   return null;
  }
  if (input.length() == 0) {
   return input;
  }
  input = input.replaceAll("&", "&amp;");
  input = input.replaceAll("<", "&lt;");
  input = input.replaceAll(">", "&gt;");
  input = input.replaceAll(" ", "&nbsp;");
  input = input.replaceAll("\'", "&#39;");
  input = input.replaceAll(""", "&quot;");
 input = input.replaceAll("n", "<br>");
  return input;

 }
}

AddmessageServlet.java

代码;

package webbook.guestbook;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import webbook.util.StringUtil;

public class AddMessageServlet extends HttpServlet {

 private static final long serialVersionUID = -8349454122547148005L;

 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  String url = "jdbc:oracle:thin:@192.168.1.20:1521:ora9";
  String username = "scott";
  String password = "tiger";

  String sql = "insert into guestbook (id,name,email,phone,title,content,time) values(gb_seq.nextval,?,?,?,?,?,?)";
  int result = 0;
  Connection conn = null;

  request.setCharacterEncoding("utf-8");
  String name = request.getParameter("name");
  String title = request.getParameter("title");

  response.setContentType("text/html;charset=utf-8");
  PrintWriter out = response.getWriter();
  out.println("<html>");
  out.println("<head><title>guestbook input page</title></head>");
  out.println("<body>");

  if (StringUtil.validateNull(name)) {
   out.println("对不起,姓名不能为空,请您重新输入!<br>");
   out.println("<a href=""+request.getContextPath()+"/addMessage.htm">添加新的留言</a><br>");
  } else if (StringUtil.validateNull(title)) {
   out.println("对不起,主题不能为空,请您重新输入!<br>");
   out.println("<a href=""+request.getContextPath()+"/addMessage.htm">添加新的留言</a><br>");
  } else {
   try {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    conn = DriverManager.getConnection(url, username, password);

    PreparedStatement pstmt = conn.prepareStatement(sql);
    pstmt.setString(1, StringUtil.filterHtml(name));
    pstmt.setString(2, StringUtil.filterHtml(request.getParameter("email")));
    pstmt.setString(3, StringUtil.filterHtml(request.getParameter("phone")));
    pstmt.setString(4, StringUtil.filterHtml(title));
    pstmt.setString(5, request.getParameter("content"));

                     //设置格式化时间

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    pstmt.setString(6, sdf.format(new java.util.Date()));


    result = pstmt.executeUpdate();
    pstmt.close();
   } catch (ClassNotFoundException e) {
    e.printStackTrace();
   } catch (SQLException e) {
    e.printStackTrace();
   } finally {
    try {
     conn.close();
    } catch (SQLException e) {
     e.printStackTrace();
    }
   }
   if (result == 0) {
    out.println("对不起,添加留言不成功,请您重新输入!<br>");
    out.println("<a href=""+request.getContextPath()+"/addMessage.htm">添加新的留言</a><br>");
   } else {
    out.println("祝贺您,成功添加留言。<br>");
    out.println("<a href=""+request.getContextPath()+"/servlet/getMessages">查看所有留言内容</a><br>");
   }
   out.println("</body>");
   out.println("</html>");
   out.flush();
   out.close();
  }
 }
}

GetMessageServlet.java

代码:

package webbook.guestbook;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import webbook.util.StringUtil;

public class GetMessagesServlet extends HttpServlet {
 private static final long serialVersionUID = 5964428201228635704L;

 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  String url = "jdbc:oracle:thin:@192.168.1.20:1521:ora9";
  String username = "scott";
  String password = "tiger";
  String sql = "select * from guestbook order by id desc";
  Connection conn = null;
  response.setContentType("text/html;charset=utf-8");
  PrintWriter out = response.getWriter();
  out.println("<html>");
  out.println("<head><title>display messages</title></head>");
  out.println("<body>");
  out.println("<a href="" + request.getContextPath() + "/addMessage.htm">添加新的留言内容</a><br>");
  out.println("留言内容<br><br>");
  try {
   Class.forName("oracle.jdbc.driver.OracleDriver");
   conn = DriverManager.getConnection(url, username, password);
   PreparedStatement pstmt = conn.prepareStatement(sql);

   //查询结果是一个ResultSet对象。
   ResultSet rs = pstmt.executeQuery();
   while (rs.next()) {
    this.printRow(out, rs);
   }
   rs.close();
   pstmt.close();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   try {
    conn.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
  out.println(" </body>");
  out.println("</html>");
  out.flush();
  out.close();
 }

 private void printRow(PrintWriter out, ResultSet rs) throws SQLException {
  out.println("<table width="600" border="1" style="table-layout:fixed;word-break:break-all">");
  out.println("<tr><td width="50">编号</td>");
  out.println("<td width="550">" + rs.getInt("id") + "</td></tr>");
  out.println("<tr><td>姓名</td><td>" + rs.getString("name") + "</td></tr>");
  out.println("<tr><td>电话</td><td>" + StringUtil.chanageNull(rs.getString("phone"), "没填") + "</td></tr>");
  out.println("<tr><td>email</td><td>" + StringUtil.chanageNull(rs.getString("email"), "没填") + "</td></tr>");
  out.println("<tr><td valign="top">主题</td><td>" + rs.getString("title") + " </td></tr>");
  out.println("<tr><td valign="top">内容</td>");
  out.println("<td>" + StringUtil.chanageNull(rs.getString("content"), "没填") + "</td></tr>");
  out.println("<tr><td>时间</td><td>" + rs.getString("time") + " </td></tr>");
  out.println("</table><br>");
 }
}