本来是不想写的,但是忽然发现今天是201314,要等5201314(5201-3-14)要等几千年啊。作为一个单身屌丝无论如何都要留下些东西,什么也好,写点吧。
本文主要介绍spring mvc如果拦截了所有请求怎么返回jstl、json、xml视图,访问静态文件,以及使用dwr,我把这几个都集中到一个工程,看看他们是怎样协同工作的。
阅读本文前需要对spring mvc和dwr有基本了解
不多说,去图,目录结构:
其他文件不看,就看主要的,要项目的可以在后面给出的链接下载,不需要积分,多点下载啊,我要积分!!!
这是web.xml的有关配置,重点是dwr的url要用相同的serlvet配多一次。
<!-- 加载配置文件 -->
<!-- ================================================================= -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/test-service.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- ================================================================= -->
<!-- 配置servlet拦截spring请求 -->
<!-- ================================================================= -->
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
<!-- ================================================================= -->
<!-- 强制转码 -->
<!-- ================================================================= -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- ================================================================= -->
这是test-serlvet.xml的部分配置,详细请去下载源码来看。
<mvc:annotation-driven />
<context:component-scan base-package="com.web"></context:component-scan>
<!-- 视图解析器,根据视图的名称new ModelAndView(name),在配置文件查找对应的bean配置 -->
<!-- ============================================================ -->
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
<property name="order" value="3" />
</bean>
<!-- ============================================================ -->
<!-- annotation默认的方法映射适配器 -->
<!-- ============================================================ -->
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="order" value="1" />
</bean>
<!-- ============================================================ -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
</bean>
下面看是配置视图:
这个是json视图,配置起来比较简单:
<!-- json视图,jsontournamenttemplate,可以转换任何形式的java对象 -->
<!-- ============================================================ -->
<bean id="jsontournamenttemplate"
class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"></bean>
<!-- ============================================================ -->
这个是xml视图,配置的时候可以看看注释:
<!-- xml视图,XStreamMarshaller,可以转换任何形式的java对象 -->
<!-- ============================================================ -->
<bean name="xStreamMarshallingView"
class="org.springframework.web.servlet.view.xml.MarshallingView">
<property name="marshaller">
<bean class="org.springframework.oxm.xstream.XStreamMarshaller">
<!-- 为了初始化XStreamMarshaller,这个类会把我们接口中得到结果以XML文档形式展现出来 -->
<property name="autodetectAnnotations" value="true" />
<!-- 类名别名 -->
<property name="aliases">
<map>
<!-- Account这个类的别名就变成了账户,那么转换后的xml中就是账户 -->
<entry key="账户" value="com.model.Account" />
<entry key="学生" value="com.model.Student" />
</map>
</property>
<!-- 基本属性别名 -->
<property name="fieldAliases">
<map>
<!-- Account中的属性别名 -->
<entry key="com.model.Account.id" value="用户id" />
<entry key="com.model.Account.account" value="账号" />
<entry key="com.model.Account.password" value="密码" />
<entry key="com.model.Account.student" value="对应的学生" />
</map>
</property>
</bean>
</property>
</bean>
<!-- ============================================================ -->
这个是jstl视图,找不到匹配的视图的时候就会找这个,一般返回字符串的controller会找这个视图
<!-- jstl视图解析器 -->
<!-- ================================================================= -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- ================================================================= -->
dwr的配置,大家看看注释,有过dwr的基础的应该不难,记得要定义可以暴露的类,没有定义的话是不会作转换处理的
<!-- dwr配置 -->
<!-- ================================================================= -->
<!-- 要求dwr在spring容器中检查拥有@RemoteProxy 和 @RemoteMethod注解的类。注意它不会去检查Spring容器之外的类。 -->
<dwr:annotation-config id="dwr" />
<!-- 要求DWR将util.js和engine.js映射到dwrController -->
<dwr:url-mapping />
<!-- 定义dwr -->
<dwr:controller id="dwrController" debug="true">
<dwr:config-param name="allowScriptTagRemoting"
value="true" />
<dwr:config-param name="crossDomainSessionSecurity"
value="true" />
</dwr:controller>
<!-- 定义可以暴露的类 -->
<dwr:configuration>
<dwr:convert type="bean" class="com.model.Account"></dwr:convert>
<dwr:convert type="bean" class="com.model.Student"></dwr:convert>
</dwr:configuration>
<!-- ================================================================= -->
下面是对静态资源做处理,把静态资源放到某几个文件夹下面,由url的前缀决定是否把这个请求视为静态资源
<!-- 对静态资源文件的访问 -->
<!-- ================================================================= -->
<mvc:resources location="/img/" mapping="/img/**" />
<mvc:resources location="/js/" mapping="/js/**" />
<!-- ================================================================= -->
几个种类的请求及视图的配置基本上就是那么多,下面看看怎么返回这些视图,我用2个controller简单的演示完,一个是dwr的,一个是出了dwr以外的。
先看看dwr的:
package com.web.dwr;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.model.Account;
import com.service.interfaces.AccountService;
@Controller
@RemoteProxy(name = "dwrTest")
public class DwrTestController {
@Autowired
private AccountService accountService;
public void setAccountService(AccountService accountService) {
this.accountService = accountService;
}
@RemoteMethod
public Account getJsonTest() {
return accountService.getAccount();
}
}
@RemoteProxy注解标记要暴露给前台使用的类,前提是这个包要被spring扫描,所以要配好xml扫描包和加上@Controller注解
这是前台js调用dwr的过程
var showInfo = function() {
dwrTest.getJsonTest(function(data) {
alert("账号是:" + data.account + "\n密码是:" + data.password
+ "\n姓名是:" + data.student.name + "\n性别是:" + data.student.sex);
});
};
启用dwr要引入几个文件,是经过spring过滤的几个文件:
<script type="text/javascript" src="/sprjson/dwr/engine.js"></script>
<script type="text/javascript" src="/sprjson/dwr/util.js"></script>
<script type="text/javascript" src="/sprjson/dwr/interface/dwrTest.js"></script>
dwrTest就是刚才注解的name属性。
下面是jstl,json,xml视图的controller:
package com.web.test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.model.Account;
import com.service.interfaces.AccountService;
@Controller
public class TestController {
@Autowired
private AccountService accountService;
public void setAccountService(AccountService accountService) {
this.accountService = accountService;
}
@RequestMapping(value = "/jsptest.html", method = RequestMethod.GET)
public String jspTest(Model model) {
model.addAttribute("account", accountService.getAccount());
return "indextest";
}
@RequestMapping(value = "/jsontest.html", method = RequestMethod.GET)
public ModelAndView jsonTest() {
ModelAndView model = new ModelAndView("jsontournamenttemplate");
model.addObject("myAccount", accountService.getAccount());
model.addObject("success", true);
return model;
}
@RequestMapping(value = "/xmltest.html", method = RequestMethod.GET)
public ModelAndView xmlTest() {
ModelAndView model = new ModelAndView("xStreamMarshallingView");
Account account = accountService.getAccount();
model.addObject(BindingResult.MODEL_KEY_PREFIX, account);
return model;
}
}
返回字符串的是jstl视图,返回ModelAndView的会根据构造函数设的参数寻找这个名字对应的bean的视图。xml视图addObject的时候如果不设置key是BindingResult.MODEL_KEY_PREFIX的话有可能响应出一大堆无关的信息,但是另一个工程则没有出现这种状况,原因不明,望高人指点。
下面是jsp文件:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>spring mvc url测试</title>
<script type="text/javascript" src="/sprjson/dwr/engine.js"></script>
<script type="text/javascript" src="/sprjson/dwr/util.js"></script>
<script type="text/javascript" src="/sprjson/dwr/interface/dwrTest.js"></script>
<script type="text/javascript" src="js/showInfo.js"></script>
</head>
<body>
controller传过来的数据
<table border="1">
<tr>
<th>用户账号</th>
<th>用户密码</th>
<th>学生姓名</th>
<th>学生性别</th>
</tr>
<tr>
<td>${account.account}</td>
<td>${account.password}</td>
<td>${account.student.name}</td>
<td>${account.student.sex}</td>
</tr>
</table><br>
下面是spring mvc访问静态路径的文件的图片<br>
<img alt="吃货秋" src="img/qiuqiu.jpg"><br><br>
访问json字符串:<a href="/sprjson/jsontest.html" target="_blank">/sprjson/jsontest.html</a><br><br>
访问xml字符串:<a href="/sprjson/xmltest.html" target="_blank">/sprjson/xmltest.html</a><br><br>
<button οnclick="showInfo()">提示用户信息json</button>
</body>
</html>
访问
http://localhost:8080/sprjson/jsptest.html
可以经过controller跳到jsp页面,该页面的图片和静态的js文件可以正常引入,按那两个json视图和xml视图的链接可以得出json视图和xml视图。
访问
http://localhost:8080/sprjson/jsontest.html
的结果
访问
http://localhost:8080/sprjson/xmltest.html
的结果
这里显示的属性是中文是由于在xml配置文件设置了属性的别名的原因。