WEB开发网
开发学院WEB开发Jsp 基于java servlet技术的留言簿 阅读

基于java servlet技术的留言簿

 2008-01-05 08:45:43 来源:WEB开发网   
核心提示:http://www.linuxforum.net 作者 dream_bird@163.net 这几天整理我机器中的旧文档时,发现了一个不错的基于javaservlet技术的留言簿,基于java servlet技术的留言簿,好象是几个月前我从http://go.163.com/~netjava/找到的,后台数据

  http://www.linuxforum.net 作者 dream_bird@163.net

这几天整理我机器中的旧文档时,发现了一个不错的基于java servlet技术的留言簿,好象是几个月前我从 http://go.163.com/~netjava/ 找到的,后台数据库用的是SQL Server。现在我的Redhat 6.1上正好安装了Apache Jserv 1.1、GNUjsp 1.0、MySQL(包括mm.mysql的JDBC驱动),除此之外还有Tomcat 3.1和Cocoon 1.8。当然,一般只运行Jserv + GNUJSP + Cocoon + MySQL,Tomcat是不运行的。既然环境是现成的,为什么不把这个留言簿改改让它可以运行呢?

首先改造它的源代码,把JDBC 驱动和URL改成MySQL的。GuestBookServlet.java程序代码如下:

//javac -encoding iso8859_1 GuestBookServlet.java ( for Chinese gb2312 )
//javac GuestBookServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.net.*;
import java.sql.*;
import java.text.DateFormat;
import java.util.Locale;

public class GuestBookServlet extends HttpServlet {
    public void init(ServletConfig conf) throws ServletException {

     super.init(conf);

        try {
            Class.forName("org.gjt.mm.mysql.Driver");
        }
        catch( Exception e ) {
        }
    }
//Sign guestbook
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
        String url = "jdbc:mysql://localhost.localdomain:3306/GuestBook?user=guest&passWord=password";
        ServletOutputStream out = res.getOutputStream();
        java.util.Date date = new java.util.Date();
        String name, email, comment;
        Connection conn = null;
        Exception err = null;
        int id = -1;
        String[] tmp;
//init

//accept name 
        tmp = req.getParameterValues("name");
        if( tmp == null  tmp.length != 1 ) {
            name = null;
        }
        else {
            name = tmp[0];
        }
//accept email  
        tmp = req.getParameterValues("email");
        if( tmp == null  tmp.length != 1 ) {
            email = null;
        }
        else {
            email = tmp[0];
        }
//accept comments       
        tmp = req.getParameterValues("comments");
        if( tmp == null  tmp.length != 1 ) {
            comment = null;
        }
        else {
            comment = tmp[0];
        }
  //header
        res.setContentType("text/Html");
        PRintPageHeader(out);
        if( name.length() < 1 ) {
            out.println("You must specify a valid name!");
            printCommentForm(out);
            printPageFooter(out);
            return;
        }
        if( email.length() < 3 ) {
            out.println("You must specify a valid email address!");
            printCommentForm(out);
            printPageFooter(out);
            return;
        }
        if( email.indexOf("@") < 1 ) {
            out.println("You must specify a valid email address!");
            printCommentForm(out);
            printPageFooter(out);
            return;
        }
        if( comment.length() < 1 ) {
            out.println("You left no comments!");
            printCommentForm(out);
            printPageFooter(out);
            return;
        }
        //access to MySQL
        try {
            Statement statement;
            ResultSet result;
            
            conn = DriverManager.getConnection(url);
            statement = conn.createStatement();
            result = statement.executeQuery("SELECT next_id " +
                                            "FROM sys_gen " +
                                            "WHERE id = ´comment_id´");
            if( !result.next() ) {
                throw new java.sql.SQLException("Failed to generate id.");
            }
            id = result.getInt(1) + 1;
            result.close();
            statement.close();
            statement = conn.createStatement();
            statement.executeUpdate("UPDATE sys_gen SET next_id = " + id +
                                    " WHERE id = ´comment_id´");
            statement.close();
            statement = conn.createStatement();
            comment = fixComment(comment);
            statement.executeUpdate("INSERT into comments " +
                                    "(comment_id, email, name, comment, " +
                                    "cmt_date) "+
                                    "VALUES (" + id +", ´" + email +
                                    "´, ´" + name + "´, ´" +
                                    comment + "´, ´" + date.getTime() +
                                    "´)");
            statement.close();
        }
        catch( java.sql.SQLException e ) {
            e.printStackTrace();
            err = e;
        }
        finally {
            if( conn != null ) {
                try { conn.close(); }
                catch( Exception e ) { }
            }
        }
        if( err != null ) {
            out.println("An error occurred on save: " + err.getMessage());
        }
        else {
            printCommentForm(out);
            printComments(out);
        }
    }
    
    
//browser  the guestbook
    public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
        String url = "jdbc:mysql://localhost.localdomain:3306/GusetBook?user=guest&password=password";
        ServletOutputStream out = res.getOutputStream();
        Connection conn = null;
        int id = -1;
        Exception err = null;

        res.setContentType("text/html");
        printPageHeader(out);
        printCommentForm(out);
        printComments(out);
        printPageFooter(out);
    }

    public String getServletInfo() {
        return "Guest Book Servlet v1.0 Copyright 251 2000 meng_bo";
    }

    private void printCommentForm(ServletOutputStream out)
    throws IOException {
        out.println("
");
        out.println("");
        out.println("");
        out.println("");
        out.println(" Name: ");
        out.println(" ");
        out.println(" ");
        out.println("
");
        out.println("");
        out.println(" Email: ");
        out.println(" ");
        out.println("
");
        out.println("");
        out.println(" Comments: ");
        out.println("
");
        out.println("");
        out.println("");
        out.println("");
        out.println("");
        out.println("");
        out.println(" ");
        out.println("");
        out.println("
");
    }

    private void printComments(ServletOutputStream out)
    throws IOException {
        Connection conn = null;
        
        try {
            DateFormat fmt = DateFormat.getDateInstance(DateFormat.FULL,
                                                        Locale.getDefault());
            String url = "jdbc:mysql://localhost.localdomain:3306/GuestBook?user=guest&password=password";
            Statement stmt;
            ResultSet results;
            
            conn = DriverManager.getConnection(url);
            stmt = conn.createStatement();
            results = stmt.executeQuery("SELECT name, email, cmt_date, " +
                                        "comment, comment_id " +
                                        "FROM comments " +
                                        "ORDER BY cmt_date");
            out.println("
");
            while( results.next() ) {
                String name, email, cmt;
                java.util.Date date;

                name = results.getString(1);
                if( results.wasNull() ) {
                    name = "Unknown User";
                }
                email = results.getString(2);
                if( results.wasNull() ) {
                    email = "user@host";
                }
                date = results.getDate(3);
                if( results.wasNull() ) {
                    date = new java.util.Date();
                }
                cmt = results.getString(4);
                if( results.wasNull() ) {
                    cmt = "No comment.";
                }
                out.println("
" + name + " (" + email + ") on " +
                            fmt.format(date));
                cmt = noHTML(cmt);
                out.println("
 
" + cmt + "
");
            }
            out.println("
");
        }
        catch( SQLException e ) {
            out.println("A database error occurred: " + e.getMessage());
        }
        if( conn != null ) {
            try { conn.close(); }
            catch( Exception e ) { }
        }
    }
    
    private void printPageHeader(ServletOutputStream out)
    throws IOException {
        out.println("");
        out.println("");
        out.println("");
        out.println("");
        out.println("");
        out.println("
Guest Book
");
    }

    private void printPageFooter(ServletOutputStream out)
    throws IOException {
        out.println("");
        out.println("");
        out.flush();
    }

    private String noHTML(String cmt) {
        if( cmt.indexOf("<") != -1  cmt.indexOf(">") != -1 ) {
            String tmp = "";

            for(int i=0; i                char c = cmt.charAt(i);

                if( c == ´<´ ) {
                    tmp = tmp + "<";
                }
                else if( c == ´>´ ) {
                    tmp = tmp + ">";
                }
                else {
                    tmp = tmp + c;
                }
            }
            cmt = tmp;
        }
        return cmt;
    }

    private String fixComment(String comment) {
        if( comment.indexOf("´") != -1 ) {
            String tmp = "";
            
            for(int i=0; i                char c = comment.charAt(i);
                
                if( c == ´´´ ) {
                    tmp = tmp + "\´";
                }
                else {
                    tmp = tmp + c;
                }
            }
            comment = tmp;
        }
        return comment;
    }
}

对于该程序所要使用的数据库和表,我写了如下三个脚本:

1. create_database.sql

create database GuestBook;
grant select,insert,update,delete,create,drop
on GuestBook.*
to guest@localhost.localdomain
identified by ´password´;

2. create_tables.sql

use GuestBook;
create table sys_gen(
next_id int(8) not null,
id char(10) not null);

insert into sys_gen (next_id, id) values (0, ´comment_id´);

create table comments(
comment_id int(8) not null,
email varchar(64),
name varchar(32),
comment varchar(128),
cmt_date date default ´0000-00-00´ not null);

3. install.sh

#/bin/sh

mysql --user=root --host=localhost.localdomain --password=password < create_database.sql
mysql --user=guest --host=localhost.localdomain --password=password < create_tables.sql

有了这些代码,一切就再明白不过了吧。这里还需要注重的是“<”和“>”在HTML文件中会出问题,所以谁要把这篇文档转换成HTML文件时一定要注重。

Tags:基于 java servlet

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接