这是一个用于留言板留言提交与读取的简单实例,不包括回复、编辑与删除等其它管理功能。 本实例的目的在于用一个简单的例子展示如果在java web应用中,用javascript开发Ajax应用。
一、web页面 msbord.jsp
1、本页面用于留言显示
2、本页面提供留言功能,并利用httpxmlrequest提交给servlet保存数据并使用javascript对页面显示进行调整。
3、本例子没有对httpxmlrequest提交后的返回数据进行处理的实例展示。
<% ... @ page language="java" contentType="text/html; charset=gb18030"
pageEncoding="gb18030" %>
<! DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" >
< html >
< head >

<% ... @ page import="java.sql.*" %>
< jsp:useBean id ="DataSql" scope ="page" class ="edu.scnu.cn.common.DataSql" ></ jsp:useBean >
< meta http-equiv ="Content-Type" content ="text/html; charset=gb18030" >
< title > 留言薄 </ title >

< style > ...

body{...}{font-size:12px;text-align:center;}

dl {...}{margin:0;}

dt {...}{background-color:#666;color:#fff;margin:1px;padding:0 3px;}

dd {...}{margin:3px;}

div {...}{margin:auto;line-height:150%;text-align:left;width:400px;border:1px solid #666;}

#msgInput {...}{margin-top:10px;}

dd.button {...}{text-align:center;}

dd.button.input{...}{margin:0 20px;}
</ style >

< script type ="text/javascript" > ...

function addToList()...{
var msgList=document.getElementById("msgBox");
var dl=document.createElement("dl");
var dt=document.createElement("dt");
var dd=document.createElement("dd");
var dd2=document.createElement("dd");
var dd3=document.createElement("dd");
msgList.insertBefore(dl,msgList.firstChild);
dl.appendChild(dt);
dl.appendChild(dd);
dl.appendChild(dd2);
dl.appendChild(dd3);
dt.innerHTML="主 题:"+subject.value;
dd.innerHTML="留 言 人:"+author.value;
dd2.innerHTML="内 容:"+content.value;
dd3.innerHTML="时 间:"+time.value;
subject.value="";
author.value="";
content.value="";
time.value="";
}

function createXMLHttp()...{
var xmlhttp;

try...{
xmlhttp=new XMLHttpRequest();

}catch(e)...{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}

function delRecord(id)...{

}

function ajaxSubmit()...{
var xmlhttp=createXMLHttp();

xmlhttp.onreadystatechange=function()...{

if(4==xmlhttp.readyState)...{

if(200==xmlhttp.status)...{
//alert(xmlhttp.responseXML);
addToList();

}else...{
alert("no");
}
}
}
var sql="insert into msgbox values(null,'"+subject.value+"','"+author.value+"','"+content.value+"','"+time.value+"')";
var submitUrl="/servlet/AddRecordServlet?sql="+sql;
xmlhttp.open("post",submitUrl,true);
xmlhttp.setRequestHeader('Conten-type','application/x-www-form-urlencode');
xmlhttp.send(null);
return false;
}
</ script >
</ head >
< body >

<% ...
Connection conn=DataSql.getConn();
String sql="select * from msgbox order by time DESC";
ResultSet rs=DataSql.getRs(conn,sql);
while(rs.next()){
%>
< div id ="msgBox" >
< dl id ="dl+<%=rs.getString(" id") % > ">
< dt > 主 题: <% = rs.getString( " subject " ) %> </ dt >
< dd > 留 言 人: <% = rs.getString( " author " ) %> </ dd >
< dd > 内 容: <% = rs.getString( " content " ) %> </ dd >
< dd > 时 间: <% = rs.getString( " time " ) %> </ dd >
</ dl >
</ div >

<% ...
}
%>
< div id ="msgInput" >
< form name ="msgForm" method ="POST" >
< dl >
< dt > 主 题: < input type ="text" name ="subject" size ="42" id ="subject" ></ dt >
< dd > 留 言 人: < input type ="text" name ="author" size ="42" id ="author" ></ dd >
< dd > 内 容: < textarea rows ="10" cols ="42" name ="content" id ="content" ></ textarea ></ dd >
< dd > 时 间: < input type ="text" size ="42" name ="time" id ="time" ></ dd >
< dd class ="button" >< input type ="button" onClick ="ajaxSubmit()" value ="提交" >
< input type ="Submit" value ="提交2" >
</ dd >
</ dl >
</ form >
</ div >

< script > ...
var subject=document.forms[0].subject;
var author=document.forms[0].author;
var content=document.forms[0].content;
var time=document.forms[0].time;
</ script >
</ body >
</ html >
二、servlet
用于对页面提交数据的处理。
package edu.scnu.cn.common.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import edu.scnu.cn.common.DataSql;
import java.sql. * ;


public class AddRecordServlet extends HttpServlet ... {


/** *//**
*
*/
private static final long serialVersionUID = 1L;


/** *//**
* Constructor of the object.
*/

public AddRecordServlet() ...{
super();
}


/** *//**
* Destruction of the servlet. <br>
*/

public void destroy() ...{
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}


/** *//**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException ...{

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}


/** *//**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException ...{
DataSql dataSql=new DataSql();

try ...{
Connection conn=dataSql.getConn();
String sql=request.getParameter("sql");

try ...{
int i=dataSql.execute(conn,sql);
conn.close();

} catch (SQLException e) ...{
// TODO Auto-generated catch block
e.printStackTrace();
}

} catch (InstantiationException e) ...{
// TODO Auto-generated catch block
e.printStackTrace();

} catch (IllegalAccessException e) ...{
// TODO Auto-generated catch block
e.printStackTrace();

} catch (ClassNotFoundException e) ...{
// TODO Auto-generated catch block
e.printStackTrace();
}
}


/** *//**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/

public void init() throws ServletException ...{
// Put your code here
}

}
三、web.xml
对serverlet进行配置
< servlet >
< description > This is the description of my J2EE component </ description >
< display-name > This is the display name of my J2EE component </ display-name >
< servlet-name > AddRecordServlet </ servlet-name >
< servlet-class > edu.scnu.cn.common.servlet.AddRecordServlet </ servlet-class >
</ servlet >

< servlet-mapping >
< servlet-name > AddRecordServlet </ servlet-name >
< url-pattern > /servlet/AddRecordServlet </ url-pattern >
</ servlet-mapping >
四、DataSql
数据库操作类
package edu.scnu.cn.common;
import java.sql. * ;

/** */ /**
*
* @author li
*
*数据库操作类
*/

public class DataSql ... {

/** *//**
*
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws ClassNotFoundException
*
* 直接连接到数据库,数据库指定为crjy
*/
public Connection getConn() throws InstantiationException, IllegalAccessException, ClassNotFoundException

...{
//数据库用户名
String userName="root";
//密码
String userPasswd="admin222";
//数据库名
String dbName="crjy";
//联结字符串
String url="jdbc:mysql://localhost:3306/"+dbName+"?useUnicode=true&characterEncoding=GB2312&user="+userName+"&password="+userPasswd;
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn=null;
try

...{
conn = DriverManager.getConnection(url);
}
catch (SQLException e)

...{
e.printStackTrace();
}
return conn;
}

/** *//**
*
* @param conn 到数据库的连接
* @param sql sql串
* @return
*
* 得到数据集
*
*/
public ResultSet getRs(Connection conn,String sql)

...{
Statement statement=null;
ResultSet rs=null;

try ...{
statement = conn.createStatement();
rs = statement.executeQuery(sql);

} catch (SQLException e) ...{
// TODO 自动生成 catch 块
e.printStackTrace();
}
return rs;
}

/** *//**
*
* @param conn 到数据库的连接
* @param sql sql串
* @return
*
* 执行删除,更新等操作
*/
public int execute(Connection conn,String sql)

...{
Statement statement=null;
int i=0;

try ...{
statement = conn.createStatement();
i= statement.executeUpdate(sql);

} catch (SQLException e) ...{
// TODO 自动生成 catch 块
e.printStackTrace();
}
return i;
}


}