开发web项目通常很多地方需要使用ajx清求来完成相应的功能,比如表单交巨或者是复杂的U设计中数据的传递等等。对于返回结果,我们一般使用ISON对象来表示,那么Sping MVC中如何处理ISON对象?
JSON对象的处理
使用@ResponseBody实现数据输出
/**
* 判断注册时用户编码是否唯一
* @param request 获取表单数据
* @param model 用于传递数据到页面
* @return ajax需要解析的JSON格式数据
*/
@RequestMapping("/isExists")
@ResponseBody
public String isExists(HttpServletRequest request, Model model) {
String userCode = request.getParameter("userCode");
int count = userService.queryName(userCode);
Map<String, Object> map = new HashMap<String, Object>();
if (count > 0) {
map.put("message", "ERROR");
} else {
map.put("message", "OK");
}
return JSONArray.toJSONString(map);
}
@RequestMapping:指定请求的URL。
@ResponseBody:将标注该注解的处理方法的返回结果直接写入HTTP ResponseBody(Response对象的body数据区)中。一般情况下,@ResponseBody都会在异步获取数据时使用。
如果传递中文时出现乱码则需要在RequestMapping注解的参数中加入produces属性,就像这样:@RequestMapping(value="/isExists",produces={"application/json;charset=utf-8"})。
如果传递日期格式的JSON数据,需要在对应实体类的对应日期属性上加入注解:@JSONField(format="yyyy-MM-dd"),否则日期传递后格式显示为时间戳。
多视图解析器——ContentNegotiatingViewResolver
由于Spring MVC可以根据请求报文头的Accept属性值,将处理方法的返回值以XML、JSON、HTML等不同的形式输出响应,即可以通过设置请求报文头Accept的值来控制服务器端返回的数据格式。这时可以使用一个强大的多试图解析器来进行灵活处理。
在Springmvc-servlet配置文件中将视图解析器替换为:
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="favorParameter" value="true"></property>
<property name="mediaTypes">
<map>
<entry key="json" value="application/json;charset=UTF-8"></entry>
<entry key="html" value="text/html;charset=UTF-8"></entry>
</map>
</property>
<property name="viewResolvers">
<list>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</list>
</property>
</bean>
favorParameter属性:设置为true(默认为true),则表示支持参数匹配,可以根据请求参数的值确定MIME类型,默认的请求参数为format。
mediaTypes属性:根据请求参数值和MIME类型的映射列表,即contentType以何种格式来展示。
viewResolvers属性:表示网页视图解析器,此处采用InternalResourceViewResolver进行视图解析。
框架整合(Spring MVC+Spring+MyBatis)
SSM框架,是spring + Spring MVC + MyBatis的缩写,这个是继SSH之后,目前比较主流的Java EE企业级框架,适用于搭建各种大型的企业级应用系统。
整合思路
1.新建Web工程并导入相关jar文件,点这里获取,密码:jaj7
2.web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 加载app.xml文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:app.xml</param-value>
</context-param>
<!-- 前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 过滤器设置字符编码UTF-8 -->
<filter>
<filter-name>characterEncoding</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>
</filter>
<filter-mapping>
<filter-name>characterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
3.配置文件
(1)applicationContext.xml
这里把mybatis相关配置和spring相关配置结合到一个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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- 扫包 -->
<context:component-scan base-package="cn.xxxx.service"></context:component-scan>
<!-- 读取jdbc配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- JNDI获取数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" scope="singleton">
<property name="driverClassName" value="${driverClassName}" />
<property name="url" value="${url}" />
<property name="username" value="${uname}" />
<property name="password" value="${password}" />
</bean>
<!-- 事务管理 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 使用aop管理事务 -->
<tx:advice id="advice">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="del*" propagation="REQUIRED"/>
<tx:method name="uodate*" propagation="REQUIRED"/>
<tx:method name="query*" propagation="NEVER" read-only="true"/>
<tx:method name="get*" propagation="NEVER" read-only="true"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut expression="execution(* cn.xxxx.service..*.*(..))" id="pointcut1"/>
<aop:advisor advice-ref="advice" pointcut-ref="pointcut1"/>
</aop:config>
<!-- 配置mybitas SqlSessionFactoryBean-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
</bean>
<!-- Mapper接口所在包名,Spring会自动查找其下的Mapper -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.xxxx.mapper" />
</bean>
</beans>
导入了properties属性文件进行数据源信息的读取,方便后期修改。
(2)springmvc-servlet.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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 扫包 -->
<context:component-scan base-package="cn.xxxx.controller"></context:component-scan>
<!-- JSON格式转换-->
<mvc:annotation-driven>
<mvc:message-converters>
<bean
class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>applcation/json</value>
</list>
</property>
<property name="features">
<list>
<value>WriteDateUseDateFormat</value>
</list>
</property>
</bean>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 多视图解析器 -->
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="favorParameter" value="true"></property>
<property name="mediaTypes">
<map>
<entry key="json" value="application/json;charset=UTF-8"></entry>
<entry key="html" value="text/html;charset=UTF-8"></entry>
</map>
</property>
<property name="viewResolvers">
<list>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</list>
</property>
</bean>
<!-- 静态资源加载 -->
<mvc:resources location="/statics/" mapping="/statics/**" />
<!-- 全局异常处理 -->
<bean
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.RuntimeException">error</prop>
</props>
</property>
</bean>
<!-- 文件上传 -->
<bean name="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5024000"></property>
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
<!-- 拦截器 -->
<mvc:interceptors>
<!-- 判断用户是否登录 -->
<mvc:interceptor>
<mvc:mapping path="/user/**"/>
<bean class="cn.bdqn.interceptor.SystemInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
</beans>
(3)mybatis_config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 设置全局性懒加载——即所有相关联的实体都被初始化加载 -->
<settings>
<setting name="lazyLoadingEnabled" value="false" />
</settings>
<!-- 为pojo类取别名 -->
<typeAliases>
<package name="cn.xxxx.pojo"/>
</typeAliases>
</configuration>
编写dao层、pojo层、service层和Controller层等,和之前的搭建没有太大区别。dao层使用xml映射文件编写。