DWR 使程序员在编写AJAX请求的时候减少了大量JS代码,更加关注与数据的内容传输。使用Spring来管理DWR请求后,可以使DWR调用更加方便:
现在有如下需求:需要将前端文本框中的文本信息,点击提交之后,实时的显示在页面上:
使用DWR需要用到:
dwr.jar 以及spring的相关jar包
要使用DWR首先要对web.xml中进行配置:
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<!--此处的hellonickcodwr为自己定义,在页面中引入时以此为路径-->
<url-pattern>/hellonickcodwr/*</url-pattern>
</servlet-mapping>
之后要在web.xml中配置Spring的支持
<!--配置Spring配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>
<!--添加contextloader listener-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
web.xml的配置告一段落,建立需要向前端传输数据的java类,在默认的package中新建HelloNickco类
public class HelloNickco
{
public String getInput(String text)
{
return “您刚才输入的是: ” +text;
}
}
之后要用Spring把这个类管理起来,在applicationContext.xml中做如下配置:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!--beanId为自己定义,作为和dwr关联的标志,class为数据返回和处理类的路径+类名--> <bean id="getInputBean " class="HelloNickco"/> </beans>
在web-info目录下建立dwr.xml配置文件:
<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN"
"http://getahead.ltd.uk/dwr/dwr20.dtd">
<dwr>
<allow>
<!--此处的javascipt对应的是js中调用的方法名,同时也是javascipt文件的方法名-->
<create creator="spring" javascript="getInput">
<!--此处的value对应的是applicationContext中对应的bean id-->
<param name="beanName" value="getInputBean"/>
</create>
</allow>
</dwr>
到此为止,所有的配置相关的内容都已经做完了,下面我们看一下前端页面是如何调用dwr的:
1.在我们的页面中加入对dwr的支持:
<!--此处的hellonickcodwr为 web.xml中定义servlet url-mapping的定义--> <script type='text/javascript' src='./hellonickcodwr/engine.js'></script> <script type='text/javascript' src='./hellonickcodwr/util.js'></script>
2. 加入我们编写的数据处理方法的调用:
<script type='text/javascript' src='./hellonickcodwr/interface/hello.js'></script>
3.编写信息输入的代码
<h3>DWR+Spring</h3>
请输入内容:<input id="inputtext" name="inputtext" type="text"/><br>
<!--此处后面编写-->
<input type="button" value="点击" onClick="sendMessage();"/>
<hr>
调用结果是:<br>
<!--用来显示后台传输过来的信息-->
<div id= "show"></div>
4.编写sendMessage() 方法
<script>
function sendMessage()
{
//此处name和value均可以取到
hello.hellojquery(DWRUtil.getValue('inputtext') ,function(data){
DWRUtil.setValue('show' ,data);
});
}
</script>
这样整一个dwr的调用过成就全部结束了。
dwr可以大大简化程序员对js的脚本编写量,同时通过Spring可以实现对其调用和处理类的清晰管理。个人认为非常不错,此外,和Jquery 可以结合使用,利用Jquery的丰富插件,可以编写出更加复杂而易于实现的功能!
本文介绍如何使用DWR和Spring实现前后端交互,减少JavaScript代码编写,提高开发效率。详细步骤包括配置web.xml、创建Java类、设置Spring管理及前端页面调用。
939

被折叠的 条评论
为什么被折叠?



