【Java】Spring MVC 扩展和SSM框架整合

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

JSON对象的处理

使用@ResponseBody实现数据输出

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

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

 1   /**
 2      * 判断注册时用户编码是否唯一
 3      * @param request 获取表单数据
 4      * @param model 用于传递数据到页面
 5      * @return ajax需要解析的JSON格式数据
 6      */
 7     @RequestMapping("/isExists")
 8     @ResponseBody
 9     public String isExists(HttpServletRequest request, Model model) {
10         String userCode = request.getParameter("userCode");
11         int count = userService.queryName(userCode);
12         Map<String, Object> map = new HashMap<String, Object>();
13         if (count > 0) {
14             map.put("message", "ERROR");
15         } else {
16             map.put("message", "OK");
17         }
18         return JSONArray.toJSONString(map);
19     }

@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配置文件中将视图解析器替换为:

 1 <bean
 2         class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
 3         <property name="favorParameter" value="true"></property>
 4         <property name="mediaTypes">
 5             <map>
 6                 <entry key="json" value="application/json;charset=UTF-8"></entry>
 7                 <entry key="html" value="text/html;charset=UTF-8"></entry>
 8             </map>
 9         </property>
10         <property name="viewResolvers">
11             <list>
12                 <bean
13                     class="org.springframework.web.servlet.view.InternalResourceViewResolver">
14                     <property name="prefix" value="/WEB-INF/jsp/"></property>
15                     <property name="suffix" value=".jsp"></property>
16                 </bean>
17             </list>
18         </property>
19     </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

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 5     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 6     <display-name></display-name>
 7     <welcome-file-list>
 8         <welcome-file>index.jsp</welcome-file>
 9     </welcome-file-list>
10     <!-- 监听器 -->
11     <listener>
12         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
13     </listener>
14     <!-- 加载app.xml文件 -->
15     <context-param>
16         <param-name>contextConfigLocation</param-name>
17         <param-value>classpath:app.xml</param-value>
18     </context-param>
19     
20     <!-- 前端控制器 -->
21     <servlet>
22         <servlet-name>springmvc</servlet-name>
23         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
24         <init-param>
25             <param-name>contextConfigLocation</param-name>
26             <param-value>classpath:springmvc-servlet.xml</param-value>
27         </init-param>
28     </servlet>
29     
30     <servlet-mapping>
31         <servlet-name>springmvc</servlet-name>
32         <url-pattern>/</url-pattern>
33     </servlet-mapping>
34     
35     <!-- 过滤器设置字符编码UTF-8 -->
36     <filter>
37         <filter-name>characterEncoding</filter-name>
38         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
39         <init-param>
40             <param-name>encoding</param-name>
41             <param-value>UTF-8</param-value>
42         </init-param>
43     </filter>
44     
45     <filter-mapping>
46         <filter-name>characterEncoding</filter-name>
47         <url-pattern>/*</url-pattern>
48     </filter-mapping>
49 </web-app>

这些配置在前文都有提到,这里不再赘

3.配置文件

(1)applicationContext.xml

这里把mybatis相关配置和spring相关配置结合到一个xml文件了,并没有分开。

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 4     xmlns:p="http://www.springframework.org/schema/p"
 5     xmlns:aop="http://www.springframework.org/schema/aop" 
 6     xmlns:tx="http://www.springframework.org/schema/tx"
 7     xmlns:context="http://www.springframework.org/schema/context"
 8     xsi:schemaLocation="http://www.springframework.org/schema/beans 
 9      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
10      http://www.springframework.org/schema/tx
11      http://www.springframework.org/schema/tx/spring-tx.xsd
12      http://www.springframework.org/schema/aop 
13      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
14      http://www.springframework.org/schema/context
15      http://www.springframework.org/schema/context/spring-context-3.0.xsd">
16      
17      <!-- 扫包 -->
18      <context:component-scan base-package="cn.xxxx.service"></context:component-scan>
19 
20     <!-- 读取jdbc配置文件 -->
21     <context:property-placeholder location="classpath:jdbc.properties" />
22 
23 
24     <!-- JNDI获取数据源 -->
25     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
26         destroy-method="close" scope="singleton">
27         <property name="driverClassName" value="${driverClassName}" />
28         <property name="url" value="${url}" />
29         <property name="username" value="${uname}" />
30         <property name="password" value="${password}" />
31     </bean>
32 
33     <!-- 事务管理 -->
34     <bean id="transactionManager"
35         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
36         <property name="dataSource" ref="dataSource" />
37     </bean>
38     
39     <!-- 使用aop管理事务 -->
40     <tx:advice id="advice">
41         <tx:attributes>
42             <tx:method name="add*" propagation="REQUIRED"/>
43             <tx:method name="del*" propagation="REQUIRED"/>
44             <tx:method name="uodate*" propagation="REQUIRED"/>
45             <tx:method name="query*" propagation="NEVER" read-only="true"/>
46             <tx:method name="get*" propagation="NEVER" read-only="true"/>
47         </tx:attributes>
48     </tx:advice>
49     <aop:config>
50         <aop:pointcut expression="execution(* cn.xxxx.service..*.*(..))" id="pointcut1"/>
51             <aop:advisor advice-ref="advice" pointcut-ref="pointcut1"/>
52     </aop:config>
53     
54     <!-- 配置mybitas SqlSessionFactoryBean-->
55     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
56         <property name="dataSource" ref="dataSource" />
57         <property name="configLocation" value="classpath:mybatis-config.xml" />
58     </bean>
59 
60     <!-- Mapper接口所在包名,Spring会自动查找其下的Mapper -->
61     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
62         <property name="basePackage" value="cn.xxxx.mapper" />
63     </bean>
64 
65 </beans>

导入了properties属性文件进行数据源信息的读取,方便后期修改。

(2)springmvc-servlet.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 4     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
 5     xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans
 7            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 8            http://www.springframework.org/schema/context
 9            http://www.springframework.org/schema/context/spring-context-2.5.xsd
10            http://www.springframework.org/schema/aop 
11            http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
12            http://www.springframework.org/schema/tx 
13            http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
14               http://www.springframework.org/schema/mvc
15            http://www.springframework.org/schema/mvc/spring-mvc.xsd">
16 
17     <!-- 扫包 -->
18     <context:component-scan base-package="cn.xxxx.controller"></context:component-scan>
19 
20     <!-- JSON格式转换-->
21     <mvc:annotation-driven>
22         <mvc:message-converters>
23             <bean
24                 class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
25                 <property name="supportedMediaTypes">
26                     <list>
27                         <value>text/html;charset=UTF-8</value>
28                         <value>applcation/json</value>
29                     </list>
30                 </property>
31                 <property name="features">
32                     <list>
33                         <value>WriteDateUseDateFormat</value>
34                     </list>
35                 </property>
36             </bean>
37             <bean class="org.springframework.http.converter.StringHttpMessageConverter">
38                 <property name="supportedMediaTypes">
39                     <list>
40                         <value>application/json;charset=UTF-8</value>
41                     </list>
42                 </property>
43             </bean>
44         </mvc:message-converters>
45     </mvc:annotation-driven>
46 
47     <!-- 多视图解析器 -->
48     <bean
49         class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
50         <property name="favorParameter" value="true"></property>
51         <property name="mediaTypes">
52             <map>
53                 <entry key="json" value="application/json;charset=UTF-8"></entry>
54                 <entry key="html" value="text/html;charset=UTF-8"></entry>
55             </map>
56         </property>
57         <property name="viewResolvers">
58             <list>
59                 <bean
60                     class="org.springframework.web.servlet.view.InternalResourceViewResolver">
61                     <property name="prefix" value="/WEB-INF/jsp/"></property>
62                     <property name="suffix" value=".jsp"></property>
63                 </bean>
64             </list>
65         </property>
66     </bean>
67 
68     <!-- 静态资源加载 -->
69     <mvc:resources location="/statics/" mapping="/statics/**" />
70 
71     <!-- 全局异常处理 -->
72     <bean
73         class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
74         <property name="exceptionMappings">
75             <props>
76                 <prop key="java.lang.RuntimeException">error</prop>
77             </props>
78         </property>
79     </bean>
80 
81     <!-- 文件上传 -->
82     <bean name="multipartResolver"
83         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
84         <property name="maxUploadSize" value="5024000"></property>
85         <property name="defaultEncoding" value="UTF-8"></property>
86     </bean>
87 
88     <!-- 拦截器 -->
89     <mvc:interceptors>
90         <!-- 判断用户是否登录 -->
91         <mvc:interceptor>
92             <mvc:mapping path="/user/**"/>
93             <bean class="cn.bdqn.interceptor.SystemInterceptor"/>
94         </mvc:interceptor>
95     </mvc:interceptors>
96 </beans> 

(3)mybatis_config.xml

 1 <?xml version="1.0" encoding="UTF-8"?>  
 2     <!DOCTYPE configuration   
 3         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"   
 4         "http://mybatis.org/dtd/mybatis-3-config.dtd">       
 5     <configuration>  
 6         <!-- 设置全局性懒加载——即所有相关联的实体都被初始化加载 -->
 7         <settings>  
 8             <setting name="lazyLoadingEnabled" value="false" />  
 9         </settings>  
10         
11        <!-- 为pojo类取别名 -->
12        <typeAliases>  
13            <package name="cn.xxxx.pojo"/>
14        </typeAliases>  
15    </configuration>  

编写dao层、pojo层、service层和Controller层等,和之前的搭建没有太大区别。dao层使用xml映射文件编写。

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

END

原文地址:https://www.cnblogs.com/xiaotie666/p/9347667.html