DWR在WEB项目中的配置
通过dwr可以通过JavaScript直接访问Java类中的方法,并且可以获得Java类的返回值。在Web开发中真是极其方便。下面是一个实际的配置实例。
1、导入DWR的包
2、设置web.xml,在这个xml中加入相应DwrListener和DwrServlet:
<listener>
<listener-class>org.directwebremoting.servlet.DwrListener</listener-class>
</listener>
<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>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
3、创建相应的dwr.xml在WEB-INF中,并且在这个文件中加入相应的java对象的创建信息:
<dwr>
<allow>
<!--
<filter class="com.example.dwr.monitor.MonitoringAjaxFilter"/>
<filter class="org.directwebremoting.filter.ExtraLatencyAjaxFilter">
<param name="delay" value="200"/>
</filter>
-->
<!-- intro - for the test on index.html -->
<create creator="new">将java对象公布为JavaScript对象
<param name="class" value="org.konghao.dwr.model.MyDwr"/> 要公布的java类
</create>
<convert converter="bean" match="org.konghao.dwr.model.User"/>
<convert converter="bean" match="org.konghao.dwr.model.Group"/>
<convert match="java.lang.Exception" converter="exception"/>
<convert converter="bean" match="java.lang.StackTraceElement"/>
</allow>
</dwr>
4、在页面中引入相应的dwr,
首先需要引入网站路径+dwr/engine.js
其次引入在dwr.xml中创建的类webContent/dwr/interface/Hellodwr.js
<script type="text/javascript" src="<%=request.getContextPath()%>/dwr/engine.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/dwr/interface/MyDwr.js"></script>
<script type="text/javascript">
MyDwr.hello("世界",function(data){
alert(data);
});
</script>