开发web项目通常很多地方需要使用ajax请求来完成相应的功能,比如表单交互或者是复杂的UI设计中数据的传递等等。对于返回结果,我们一般使用JSON对象来表示,那么Spring MVC中如何处理JSON对象?

JSON对象的处理

使用@ResponseBody实现数据输出

要使用JSON,所以导一下JSON工具包。JSON工具包,密码4i0l。

Controller层代码示例(这里使用的是阿里巴巴的 fastjson):

   /**
* 判断注册时用户编码是否唯一
* @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"),否则日期传递后格式显示为时间戳。

前端ajax请求代码这里不再展示。

多视图解析器——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映射文件编写。

到此处SSM框架搭建得就差不多了,余下的都是编码工作了。

END

【Java】Spring MVC 扩展和SSM框架整合的更多相关文章

  1. MVC+Spring.NET+NHibernate .NET SSH框架整合 C# 委托异步 和 async /await 两种实现的异步 如何消除点击按钮时周围出现的白线? Linq中 AsQueryable(), AsEnumerable()和ToList()的区别和用法

    MVC+Spring.NET+NHibernate .NET SSH框架整合   在JAVA中,SSH框架可谓是无人不晓,就和.NET中的MVC框架一样普及.作为一个初学者,可以感受到.NET出了MV ...

  2. springmvc(二) ssm框架整合的各种配置

    ssm:springmvc.spring.mybatis这三个框架的整合,有耐心一步步走. --WH 一.SSM框架整合 1.1.整合思路 从底层整合起,也就是先整合mybatis与spring,然后 ...

  3. Spring3 + Spring MVC+ Mybatis 3+Mysql 项目整合(注解及源码)

    Spring3 + Spring MVC+ Mybatis 3+Mysql 项目整合(注解及源码) 备注: 之前在Spring3 + Spring MVC+ Mybatis 3+Mysql 项目整合中 ...

  4. 基于maven的ssm框架整合

    基于maven的ssm框架整合 第一步:通过maven建立一个web项目.                第二步:pom文件导入jar包                              (1 ...

  5. JavaWeb之ssm框架整合,用户角色权限管理

    SSM框架整合 Spring SpringMVC MyBatis 导包: 1, spring 2, MyBatis 3, mybatis-spring 4, fastjson 5, aspectwea ...

  6. SSM框架整合环境构建——基于Spring4和Mybatis3

    目录 环境 配置说明 所需jar包 配置db.properties 配置log4j.properties 配置spring.xml 配置mybatis-spring.xml 配置springmvc.x ...

  7. SSM框架整合过程总结

    -----------------------siwuxie095                                 SSM 框架整合过程总结         1.导入相关 jar 包( ...

  8. SSM框架整合搭建教程

    自己配置了一个SSM框架,打算做个小网站,这里把SSM的配置流程详细的写了出来,方便很少接触这个框架的朋友使用,文中各个资源均免费提供! 一. 创建web项目(eclipse) File-->n ...

  9. 使用IntelliJ IDEA创建Maven聚合工程、创建resources文件夹、ssm框架整合、项目运行一体化

    一.创建一个空的项目作为存放整个项目的路径 1.选择 File——>new——>Project ——>Empty Project 2.WorkspaceforTest为项目存放文件夹 ...

随机推荐

  1. 如何在SAP CRM里创建和消费Web service

    Created by Wang, Jerry, last modified on Dec 19, 2014 The following steps demonstrates how to expose ...

  2. 确定浏览器是否支持某些DOM模块

    var supportDOM2Core = document.implementation.hasFeature("Core","2.0"); var supp ...

  3. bootstrap table 主子表 局部数据刷新(刷新子表)

    1.主表中设置data-detail-view="true",启用主子表模式: <table class="table table-striped" wi ...

  4. { ($0, Resolver($0.box)) }(Promise<T>(.pending)):闭包的定义与执行合一

    public class func pending() -> (promise: Promise<T>, resolver: Resolver<T>) { return ...

  5. LA 4987 背包

    题意: 有n个施工队,给定他们的位置,有m个防空洞,给定位置,求将施工队放到m个防空洞里面,最少的总距离? n<=4000 分析: dp[i][j] 前 i 个施工队,放到前 j 个防空洞里面的 ...

  6. Uva 10534 波浪子序列

    题目链接:https://vjudge.net/contest/160916#problem/C 题意: 求一个奇数长的子序列,前一半严格递增,后一半严格递减:O(nlogn) 分析: 再次复习一下L ...

  7. python-函数的使用

    一.函数的定义 首先,我们来看一个简单的例子来定义函数: def test(): print('hello') 在其中 def  : 关键字,用来告诉解释器,接下来的一段代码是一个函数 test : ...

  8. ASP.NET整体运行机制+asp.net请求管道+页面生命周期

  9. 纯JS拖动案例

    <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...

  10. Vue nodejs商城-地址模块

    一.地址列表渲染 ,则不可以点击. src/views/Cart.vue <a class="btn btn--red" v-bind:class="{'btn-- ...