[ 永遠的UNIX::UNIX技術資料的寶庫 ]   GB | BIG5

首頁 > 編程技術 > Java > 正文
基java servlet技術的留言簿
http://www.linuxforum.net 作者 dream_bird@163.net (2001-04-21 17:36:45)
這幾天整理我機器中的舊文檔時,發現了一個不錯的基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\nCopyright \251 2000 meng_bo";
    }

    private void printCommentForm(ServletOutputStream out)
    throws IOException {
        out.println("
");
        out.println("");
        out.println("");
        out.println("");
        out.println("
");
        out.println("");
        out.println("");
        out.println("");
        out.println("");
        out.println("
");
        out.println("");
        out.println("");
        out.println("");
        out.println("
");
        out.println("");
        out.println("");
        out.println("");
        out.println("");
        out.println("");
        out.println("");
        out.println("
Name:
Email:
Comments:
");
        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("Guest Book");
        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文件時一定要注意。

(http://www.fanqiang.com)     進入【UNIX論壇

相關文章
 

★  樊強制作 歡迎分享  ★