ssh框架中搭建DWR框架验证注册用户名唯一性
一、下载dwr.jar文件,下载地址http://directwebremoting.org/dwr/downloads/index.html
我选的是3.0.2版本,如下:(Struts2+spring3.1+hibernate4.1)
下载完之后,把dwr.jar导入到WEB-INF/lib目录下
二、搭建DWR框架
1、在web.xml添加如下内容:
<!-- 开始DWR配置 -->
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
<!-- 新加crossDomainSessionSecurity参数 -->
<init-param>
<param-name>crossDomainSessionSecurity</param-name>
<param-value>false</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
<!-- 结束DWR配置 -->
2、在web.xml的同一路径下新建dwr.xml文件,具体内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dwr PUBLIC
"-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN"
"http://getahead.org/dwr/dwr30.dtd">
<dwr>
<allow>
<create javascript="UserDAOAjax" creator="spring" scope="application">
<param name="beanName" value="customerService"></param>
<include method="existUser"/>
</create>
</allow>
</dwr>
3、applicationContext.xml文件中注入customerService(红色部分一致)
<!-- 普通装修客户 -->
<bean id="customerDAO" class="org.decorate.dao.CustomerDAO" parent="baseDAO"/>
<bean id="customerService" class="org.decorate.service.CustomerService">
<property name="customerDAO" ref="customerDAO" />
</bean>
<bean id="customerAction" class="org.decorate.action.CustomerAction" >
<property name="customerService" ref="customerService" />
</bean>
4、检测dwr框架是否成功,在浏览器输入:http://localhost:8080/Decorate/dwr/index.html
(Decorate是我的项目名称),有如下图显示为成功:
三、加入业务逻辑
1、在CustomerService加入existUser方法:
@Override
public boolean existUser(String customerId){
return customerDAO.existUser(customerId);
}
2、CustomerDAO类中建立与数据库查询的业务:
@Override
public boolean existUser(String customerId){
Session session = getSession();
Transaction transaction = session.beginTransaction();
Query query = session.createQuery("from Customer where customerId=?");
query.setParameter(0,customerId.trim());
List user=query.list();
transaction.commit();
if(user.size()>0)//有重名
return true;
else //无重名
return false;
}
四、JAP页面加入:
<script type="text/javascript" src="../dwr/engine.js"></script>
<script type="text/javascript" src="../dwr/util.js"></script>
<script type="text/javascript" src="../dwr/interface/UserDAOAjax.js"></script>
<script type="text/javascript">
function show(boolean){
if(boolean){
alert("用户已经存在!");
}
}
function validate(oCtl){
var name=oCtl.value;
if(name==""){
alert("用户名不能为空!");
return;
}
UserDAOAjax.existUser(name,show);
}
</script>
五、实验结果