【Java】Spring MVC 扩展和SSM框架整合
开发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框架整合的更多相关文章
- 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 ...
- springmvc(二) ssm框架整合的各种配置
ssm:springmvc.spring.mybatis这三个框架的整合,有耐心一步步走. --WH 一.SSM框架整合 1.1.整合思路 从底层整合起,也就是先整合mybatis与spring,然后 ...
- Spring3 + Spring MVC+ Mybatis 3+Mysql 项目整合(注解及源码)
Spring3 + Spring MVC+ Mybatis 3+Mysql 项目整合(注解及源码) 备注: 之前在Spring3 + Spring MVC+ Mybatis 3+Mysql 项目整合中 ...
- 基于maven的ssm框架整合
基于maven的ssm框架整合 第一步:通过maven建立一个web项目. 第二步:pom文件导入jar包 (1 ...
- JavaWeb之ssm框架整合,用户角色权限管理
SSM框架整合 Spring SpringMVC MyBatis 导包: 1, spring 2, MyBatis 3, mybatis-spring 4, fastjson 5, aspectwea ...
- SSM框架整合环境构建——基于Spring4和Mybatis3
目录 环境 配置说明 所需jar包 配置db.properties 配置log4j.properties 配置spring.xml 配置mybatis-spring.xml 配置springmvc.x ...
- SSM框架整合过程总结
-----------------------siwuxie095 SSM 框架整合过程总结 1.导入相关 jar 包( ...
- SSM框架整合搭建教程
自己配置了一个SSM框架,打算做个小网站,这里把SSM的配置流程详细的写了出来,方便很少接触这个框架的朋友使用,文中各个资源均免费提供! 一. 创建web项目(eclipse) File-->n ...
- 使用IntelliJ IDEA创建Maven聚合工程、创建resources文件夹、ssm框架整合、项目运行一体化
一.创建一个空的项目作为存放整个项目的路径 1.选择 File——>new——>Project ——>Empty Project 2.WorkspaceforTest为项目存放文件夹 ...
随机推荐
- http中COOKIE和SESSION有什么区别?(转知乎)
作者:知乎用户链接:https://www.zhihu.com/question/19786827/answer/28752144来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注 ...
- SSD 从形式到实质之改变
SSD 从形式到实质之改变 作者:廖恒 SSD的物理尺寸之混战正在进行其中. 数据中心的硬件架构师由于要规划下一代server的机械设计.还要制定JBOD的设计规范,想必面临不少困 ...
- E. XOR and Favorite Number
题意:很多询问,求每个询问下,有多少个区间,异或=k. 分析:异或也有前缀和.[L,R] = pre[R] ^ pre[L-1]: 莫队算法:是莫涛队长发明的,一种改良版的暴力离线算法. 首先将问题重 ...
- Ubuntu 16.04 安装 IDEA
1.下载地址:https://www.jetbrains.com/idea/download/#section=linux 选择without jdk版本下载 2.下载完成 解压 到 /opt下 先却 ...
- C# 利用HttpWebRequest进行HTTPS的post请求的示例
最近一个推送信息的目标接口从http格式换成https格式,原来的请求无法正常发送,所以修改了发送请求的方法.标红的代码是新加了,改了之后就可以正常访问(不检测证书的) public static s ...
- 【luogu T34117 打油门】 题解
王强怎么这么强啊 王强太强了 二维树状数组 #include <cstdio> #include <cstring> #include <iostream> #in ...
- Tomcat 启动速度优化
创建一个web项目 选择发布到 汤姆猫 的下面 deploy path: 表示发布到的文件名称 把项目添加到 tomcat 里,运行,我们可以在 tomcat里找到我们发布的项目: 现在启动时间: 现 ...
- Mac 使用问题
Mac 使用 Mac改变系统截图存储位置 鼠标在屏幕中间上下滚动时,有时反应不灵敏: 看看偏好设置-> 鼠标 -> 跟踪速度或者手势部分是否有哪里设置不当: 考虑重新开启鼠标鼠标底部有一个 ...
- 在Win7虚拟机下搭建Hadoop2.6.0+Spark1.4.0单机环境
Hadoop的安装和配置可以参考我之前的文章:在Win7虚拟机下搭建Hadoop2.6.0伪分布式环境. 本篇介绍如何在Hadoop2.6.0基础上搭建spark1.4.0单机环境. 1. 软件准备 ...
- iOS 让视图UIView单独显示某一侧的边框线
iOS 让视图UIView 单独显示某一侧的边框线 有时候需要让view显示某一侧的边框线,这时设置layer的border是达不到效果的.在网上查阅资料发现有一个投机取巧的办法,原理是给view ...