http://www.Linuxforum.net 作者 dream_bird@163.net
这几天整理我机器中的旧文档时,发现了一个不错的基于Javaservlet技术的留言簿,好象是几个月前我从http://go.163.com/~netjava/找到的,后台数据库用的是SQLServer。现在我的Redhat6.1上正好安装了ApacheJserv1.1、GNUjsp1.0、mysql(包括mm.mysql的JDBC驱动),除此之外还有Tomcat3.1和Cocoon1.8。当然,一般只运行Jserv+GNUJSP+Cocoon+MySQL,Tomcat是不运行的。既然环境是现成的,为什么不把这个留言簿改改让它可以运行呢?
首先改造它的源代码,把JDBC驱动和URL改成MySQL的。GuestBookServlet.java程序代码如下:
//javac-encodingiso8859_1GuestBookServlet.java(forChinesegb2312)
//javacGuestBookServlet.java
importjavax.servlet.*;
importjavax.servlet.http.*;
importjava.io.*;
importjava.net.*;
importjava.sql.*;
importjava.text.DateFormat;
importjava.util.Locale;
publicclassGuestBookServletextendsHttpServlet{
publicvoidinit(ServletConfigconf)throwsServletException{
super.init(conf);
try{
Class.forName("org.gjt.mm.mysql.Driver");
}
catch(Exceptione){
}
}
//Signguestbook
publicvoiddoPost(HttpServletRequestreq,HttpServletResponseres)
throwsServletException,IOException{
Stringurl="jdbc:mysql://localhost.localdomain:3306/GuestBook?user=guest&passWord=password";
ServletOutputStreamout=res.getOutputStream();
java.util.Datedate=newjava.util.Date();
Stringname,email,comment;
Connectionconn=null;
Exceptionerr=null;
intid=-1;
String[]tmp;
//init
//acceptname
tmp=req.getParameterValues("name");
if(tmp==nulltmp.length!=1){
name=null;
}
else{
name=tmp[0];
}
//acceptemail
tmp=req.getParameterValues("email");
if(tmp==nulltmp.length!=1){
email=null;
}
else{
email=tmp[0];
}
//acceptcomments
tmp=req.getParameterValues("comments");
if(tmp==nulltmp.length!=1){
comment=null;
}
else{
comment=tmp[0];
}
//header
res.setContentType("text/Html");
printPageHeader(out);
if(name.length()<1){
out.println("Youmustspecifyavalidname!");
printCommentForm(out);
printPageFooter(out);
return;
}
if(email.length()<3){
out.println("Youmustspecifyavalidemailaddress!");
printCommentForm(out);
printPageFooter(out);
return;
}
if(email.indexOf("@")<1){
out.println("Youmustspecifyavalidemailaddress!");
printCommentForm(out);
printPageFooter(out);
return;
}
if(comment.length()<1){
out.println("Youleftnocomments!");
printCommentForm(out);
printPageFooter(out);
return;
}
//AccesstoMySQL
try{
Statementstatement;
ResultSetresult;
conn=DriverManager.getConnection(url);
statement=conn.createStatement();
result=statement.executeQuery("SELECTnext_id"+
"FROMsys_gen"+
"WHEREid=´comment_id´");
if(!result.next()){
thrownewjava.sql.SQLException("Failedtogenerateid.");
}
id=result.getInt(1)+1;
result.close();
statement.close();
statement=conn.createStatement();
statement.executeUpdate("UPDATEsys_genSETnext_id="+id+
"WHEREid=´comment_id´");
statement.close();
statement=conn.createStatement();
comment=fixComment(comment);
statement.executeUpdate("INSERTintocomments"+
"(comment_id,email,name,comment,"+
"cmt_date)"+
"VALUES("+id+",´"+email+
"´,´"+name+"´,´"+
comment+"´,´"+date.getTime()+
"´)");
statement.close();
}
catch(java.sql.SQLExceptione){
e.printStackTrace();
err=e;
}
finally{
if(conn!=null){
try{conn.close();}
catch(Exceptione){}
}
}
if(err!=null){
out.println("Anerroroccurredonsave:"+err.getMessage());
}
else{
printCommentForm(out);
printComments(out);
}
}
//browsertheguestbook
publicvoiddoGet(HttpServletRequestreq,HttpServletResponseres)
throwsServletException,IOException{
Stringurl="jdbc:mysql://localhost.localdomain:3306/GusetBook?user=guest&password=password";
ServletOutputStreamout=res.getOutputStream();
Connectionconn=null;
intid=-1;
Exceptionerr=null;
res.setContentType("text/html");
printPageHeader(out);
printCommentForm(out);
printComments(out);
printPageFooter(out);
}
publicStringgetServletInfo(){
return"GuestBookServletv1.0
Copyright2512000meng_bo";
}
privatevoidprintCommentForm(ServletOutputStreamout)
throwsIOException{
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("
");
}
privatevoidprintComments(ServletOutputStreamout)
throwsIOException{
Connectionconn=null;
try{
DateFormatfmt=DateFormat.getDateInstance(DateFormat.FULL,
Locale.getDefault());
Stringurl="jdbc:mysql://localhost.localdomain:3306/GuestBook?user=guest&password=password";
Statementstmt;
ResultSetresults;
conn=DriverManager.getConnection(url);
stmt=conn.createStatement();
results=stmt.executeQuery("SELECTname,email,cmt_date,"+
"comment,comment_id"+
"FROMcomments"+
"ORDERBYcmt_date");
out.println("
");
while(results.next()){
Stringname,email,cmt;
java.util.Datedate;
name=results.getString(1);
if(results.wasNull()){
name="UnknownUser";
}
email=results.getString(2);
if(results.wasNull()){
email="user@host";
}
date=results.getDate(3);
if(results.wasNull()){
date=newjava.util.Date();
}
cmt=results.getString(4);
if(results.wasNull()){
cmt="Nocomment.";
}
out.println("
"+name+"("+email+")on"+
fmt.format(date));
cmt=noHTML(cmt);
out.println("
"+cmt+"
");
}
out.println("
");
}
catch(SQLExceptione){
out.println("Adatabaseerroroccurred:"+e.getMessage());
}
if(conn!=null){
try{conn.close();}
catch(Exceptione){}
}
}
privatevoidprintPageHeader(ServletOutputStreamout)
throwsIOException{
out.println("");
out.println("");
out.println("");
out.println("");
out.println("");
out.println("
GuestBook
");
}
privatevoidprintPageFooter(ServletOutputStreamout)
throwsIOException{
out.println("");
out.println("");
out.flush();
}
privateStringnoHTML(Stringcmt){
if(cmt.indexOf("<")!=-1cmt.indexOf(">")!=-1){
Stringtmp="";
for(inti=0;icharc=cmt.charAt(i);
if(c==´<´){
tmp=tmp+"<";
}
elseif(c==´>´){
tmp=tmp+">";
}
else{
tmp=tmp+c;
}
}
cmt=tmp;
}
returncmt;
}
privateStringfixComment(Stringcomment){
if(comment.indexOf("´")!=-1){
Stringtmp="";
for(inti=0;icharc=comment.charAt(i);
if(c==´´´){
tmp=tmp+"\´";
}
else{
tmp=tmp+c;
}
}
comment=tmp;
}
returncomment;
}
}
对于该程序所要使用的数据库和表,我写了如下三个脚本:
1.create_database.sql
createdatabaseGuestBook;
grantselect,insert,update,delete,create,drop
onGuestBook.*
toguest@localhost.localdomain
identifiedby´password´;
2.create_tables.sql
useGuestBook;
createtablesys_gen(
next_idint(8)notnull,
idchar(10)notnull);
insertintosys_gen(next_id,id)values(0,´comment_id´);
createtablecomments(
comment_idint(8)notnull,
emailvarchar(64),
namevarchar(32),
commentvarchar(128),
cmt_datedatedefault´0000-00-00´notnull);
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文件时一定要注重。