开发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. Selenium2学习(十五)-- 单选框和复选框(radiobox、checkbox)

    本篇主要介绍单选框和复选框的操作 一.认识单选框和复选框 1.先认清楚单选框和复选框长什么样 2.各位小伙伴看清楚哦,上面的单选框是圆的:下图复选框是方的,这个是业界的标准,要是开发小伙伴把图标弄错了 ...

  2. javascript正则表达式 - 学习笔记

    JavaScript 正则表达式 学习笔记 标签(空格分隔): 基础 JavaScript 正则表达式是用于匹配字符串中字符组合的模式.在javascript中,正则表达式也是对象.这些模式被用于Re ...

  3. day2-基础 变量,判断,循环

    1.第一个程序 print ("Hello World!") 输出: 1 Hello World 2.第一个变量 a = ( print (a) 输出: Hello World 3 ...

  4. 元素float以后,div高度无法自适应解决方案

    首先要明白 >> 浮动的子元素会脱离文档流,不再占据父元素的空间,父元素也就没有了高度. 解决方案:1 给父元素加上overflow:hidden;属性就行了. 第一种:(给父级加over ...

  5. Docker镜像提交命令commit的工作原理和使用方法

    在本地创建一个容器后,可以依据这个容器创建本地镜像,并可把这个镜像推送到Docker hub中,以便在网络上下载使用. 下面我们来动手实践. docker pull nginx:1.15.3 用命令行 ...

  6. jquery.dataTables列中内容居中问题?求解?

    .table > tbody > tr > td {  vertical-align: middle; }

  7. 深搜(DFS),Image Perimeters

    题目链接:http://poj.org/problem?id=1111 解题报告: 1.这里深搜有一点要注意,对角线上的点,如果为'.',则total不应该增加,因为这不是他的边长. #include ...

  8. React中的虚拟DOM

    当组件当state和props发生变化当时候,组件当render函数就会重新执行,组件就会被重新渲染,react中实现这种重新渲染,他的性能是非常高的,因为他引入了一个虚拟Dom的概念,那么什么是虚拟 ...

  9. mac下登录服务器

    1.先通过帐号密码登录到服务器: ssh 用户名@服务器地址 https://jingyan.baidu.com/article/546ae1853132bf1148f28c42.html 2.登录后 ...

  10. highcharts(前端报表生成)

    前端报表技术:使用 JavaScript 生成漂亮图表 百度 echarts: http://echarts.baidu.com/examples.html Funsioncharts : http: ...