開發web項目一般不少地方須要使用ajax請求來完成相應的功能,好比表單交互或者是複雜的UI設計中數據的傳遞等等。對於返回結果,咱們通常使用JSON對象來表示,那麼Spring MVC中如何處理JSON對象?html
JSON對象的處理前端
使用@ResponseBody實現數據輸出java
要使用JSON,因此導一下JSON工具包。JSON工具包,密碼4i0l。web
Controller層代碼示例(這裏使用的是阿里巴巴的 fastjson):ajax
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。spring
@ResponseBody:將標註該註解的處理方法的返回結果直接寫入HTTP ResponseBody(Response對象的body數據區)中。通常狀況下,@ResponseBody都會在異步獲取數據時使用。sql
若是傳遞中文時出現亂碼則須要在RequestMapping註解的參數中加入produces屬性,就像這樣:@RequestMapping(value="/isExists",produces={"application/json;charset=utf-8"})。express
若是傳遞日期格式的JSON數據,須要在對應實體類的對應日期屬性上加入註解:@JSONField(format="yyyy-MM-dd"),不然日期傳遞後格式顯示爲時間戳。apache
前端ajax請求代碼這裏再也不展現。json
多視圖解析器——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