spring mvc整合json

    最近team要開發一個App,負責server端。本來準備是用SSH2框架的,可是感受struts2仍是比較適合用來與jsp結合使用,想了又想決定用spring mvc整合json來作。網上查了不少資料,調試了一成天,終於把調通。在這裏分享一下個人經驗: java


  1. 第一步固然建立一個新項目,加入spring啦^-^  貌似如今只有3.0版本以上才支持整合json哦。
  2. 在項目中加入兩個json的jar包:jackson-core-asl-x.x.x.jar和jackson-mapper-asl.x.x.x.jar。其中xxx是jar包的版本,網上不少說用1.4.2,可是我加入1.4.2版本後,部署會出錯。在請求中會出現ObjectMapper:NoClassDefFoundException的錯,仔細查看原來tomcat啓動的時候就錯了,報的是isFullyTyped:NoSuchMethodError的錯誤。這個錯真心糾結了好久,最後在官網上看到原來是core包裏裏面一個類沒有這個方法。查看jar包,1.4.2真的沒有這個方法。仔細查看官網API,尼瑪json居然不是向下兼容的,傷不起....最後看到了1.1版本仍是支持的,因而就下載了1.1.2的版本。因而兩個jar包就是:jackson-core-asl-1.1.2.jar和jackson-mapper-asl.1.1.2.jar。
  3. 在web.xml添加spring mvc
    <context-param>
      	<param-name>contextConfigLocation</param-name>
                      <param-value>
      		/WEB-INF/classes/applicationContext.xml,
      		/WEB-INF/classes/spring-servlet.xml
      	</param-value>
      </context-param>
      <listener>
      	<listener-class>
      		org.springframework.web.context.ContextLoaderListener
      	</listener-class>
      </listener>
      <!-- spring mvc的servlet,處理全部.json請求 -->
      <servlet>
      	<servlet-name>spring</servlet-name>
      	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      	<init-param>
      		<param-name>contextConfigLocation</param-name>
      		<param-value>/WEB-INF/classes/spring-servlet.xml</param-value>
      	</init-param>
      	<load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
      	<servlet-name>spring</servlet-name>
      	<url-pattern>*.json</url-pattern>
      </servlet-mapping>
  4. 編寫spring-servlet.xml,配置spring mvc
    <?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: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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
    	<context:annotation-config />
    	<!-- Controller 類註解標識 -->
    	<context:component-scan base-package="com.gswtek.controller" />
    	
    	<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    		<property name="mediaTypes">
    			<map>
    				<!-- 告訴視圖解析器,返回的類型爲json格式 -->
    				<entry key="json" value="application/json" />
    			</map>
    		</property>
    		<property name="defaultViews">
    			<list>
    				<!-- ModelAndView裏的數據變成JSON -->
    				<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
    			</list>
    		</property>
    	</bean>
    </beans>
  5. 編寫Controller類,返回的ModelAndView會自動將數據轉換成json數據
    package com.gswtek.controller;
    
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import org.apache.log4j.Logger;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.portlet.ModelAndView;
    
    import com.gswtek.service.UserService;
    import com.gswtek.service.UserServiceImpl;
    
    @Controller        /註解這個是個Controller
    public class UserController {
    
    	public static Logger log = Logger.getLogger(UserController.class);
    	@Autowired
    	@Qualifier("UserServiceImpl")
    	private UserServiceImpl userService;
    	
    	public void setUserService(UserServiceImpl userService) {
    		this.userService = userService;
    	}
    
            /*
            * @RequestMapping配置請求地址
            * @RequestParam將請求中的參數注入
            */
             @RequestMapping(value="/register")     public ModelAndView register(@RequestParam("username") String username
    								,@RequestParam("password") String password) {
    		log.debug("register a new user");
    		ModelAndView modelView = new ModelAndView();
    		Map<String, Object> modelMap = new HashMap<String, Object>();
    		boolean status = userService.addUser(username, password);
    		/*if(status) {
    			modelMap.put("status", true);
    		} else {
    			modelMap.put("status", false);
    		}*/
                    modelMap.put("status",status);//感謝二樓的指正,已修改
                    modelMap.put("date", new Date());
    		modelView.addAllObjects(modelMap);
    		return modelView;
    	}
    	
    }
  6. service層的代碼就不貼了,你們都懂的^-^
  7. 部署測試,測試的地址是http://localhost:8080/spring_mvc/register.json?username=kevin&password=hahahah瀏覽器中返回數據是
    {"modelAndView":{"empty":false,"reference":false,"viewName":null,"view":null,"modelMap":{"status":true,"date":1358091863067},"model":{"status":true,"date":1358091863067}}}
    ok,成功!確實是json數據。
  8. 觀察一下,數據冗餘有木有!不要緊,定義咱們本身的數據轉換類:
    package com.gswtek.util;
    
    import java.util.Map;
    
    import org.springframework.web.portlet.ModelAndView;
    import org.springframework.web.servlet.view.json.MappingJacksonJsonView;
    
    public class MappingJacksonJsonViewExd extends MappingJacksonJsonView {
    
    	@Override
    	protected Object filterModel(Map<String, Object> model) {
    		Map<?, ?> result = (Map<?, ?>) super.filterModel(model);
    		ModelAndView mav =  (ModelAndView) (result.size() != 1 ? result : result.values().iterator().next());
    		return mav.getModelMap();
    	}
    
    }
    更改spring-servlet.xml:
                    <property name="defaultViews">
    			<list>
    				<!-- ModelAndView裏的數據變成JSON -->
    				<bean class="com.gswtek.util.MappingJacksonJsonViewExd" />
    			</list>
    		</property>

  9. 再次佈局,測試:
    {"status":true,"date":1358092422728}
    ok,此次數據就比較簡潔了。

   

     到此整個例子就結束了。這是我第一次穿寫博客,貌似廢話有點多,歡迎你們拍磚,哈哈~只是想把本身的經驗與你們分享一下,但願初學者能少走彎路。明天還要上班,Good night everyone!^-^ web

相關文章
相關標籤/搜索