本文参照http://www.blogjava.net/daizhenghenry/archive/2008/05/21/201987.html
原理:通过页面操作调用js方法,在js方法里进行查询数据库。
1 先下载dwr.jar,放到lib目录下。
2 web.xml中追加
<servlet>
<servlet-name>dwr</servlet-name>
<servlet-class>
org.directwebremoting.servlet.DwrServlet
</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dwr</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
3 新建dwr.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://www.getahead.ltd.uk/dwr/dwr20.dtd">
<dwr>
<allow>
<create javascript="Hello" creator="new">
<param name="class" value="com.train.action.TrainQueryAction"></param>
</create>
</allow>
</dwr>
4 jsp页面
function sayHello() {
Hello.query(valuestation, change);
}
function change(datae){
if(datae!=null&&datae!=""){
//得到表格中的行数
var counte = document.getElementById('tabe').rows.length;
//如果表中存在行,将所有行删除
if(counte >0){
for(var i=counte-1;i>=0;i--){
document.getElementById('tabe').deleteRow(i);
}
}
//如果存在相关搜索记录
if(datae.length > 0){
document.getElementById('Relatede').style.display = '';
document.getElementById('xe').style.display = '';
for(var i=0;i<datae.length;i++){
var objTr6 = document.getElementById('tabe').insertRow();
var objTd16 = objTr6.insertCell(0);
objTd16.innerHTML = "<input readonly type='text' "
+"size='10' name='txtHistorye' style='border:none;background:#FFFFFF'"
+" value='"+trim(datae[i])+"' onmouseover='overChangeColor(this)'"
+" onmouseleave='leaveChangeColor(this)' "
+"onclick='clickHistorye(this)'>";
}
}else{
document.getElementById('Relatede').style.display = 'none';
}
}else{
document.getElementById('Relatede').style.display = 'none';
}
}
<table width="80%" border="1" align="center">
<tr>
<td align="left" nowrap="nowrap">
<input type="radio" name="radio" value="esStation">
站站查询:
<br>
发站:
<html:text name="trainQueryForm" property="startStation" maxlength="10" onfocus="textChange('esStation')" onkeyup="sayHello()" />
<div id="Relateds" style="position:absolute;background-color='#F7F7F7';display: 'none';">
<table id="tabs" cellpadding="0" border="0" cellspacing="0">
</table>
<a id="xs" href='javascript:;' onclick='myClose()'
style="display: none">关闭</a>
</div>
</td>
</tr>
</table>
5 java文件
public class TrainQueryAction extends BaseAction {
public List<?>
query(String content,HttpServletRequest request) {
List<?> elist=null;
try {
elist = trainService.queryStationName(content);
} catch (Exception e) {
e.printStackTrace();
}
return elist;
}
}