Spring mvc 3.x版本,在支持Ajax方面仍是不錯的,看文檔咱們發現,只要咱們在Controller裏添加@RequestBody 和@ResponseBody兩個標籤後,就能把前臺傳過來的JSON對象進行轉換成咱們的java對象,也能將spring mvc裏面的model直接返回回Ajax請求,轉換器會自動的幫咱們將java對象轉換成JSON對象。
css
須要的jar包 : jackson-mapper-asl-1.8.4.jar
jackson-core-asl-1.8.5.jarjava
這是DispatcherServlet的配置文件web
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 配置這個component-scan 的時候,會隱式的配置了下面2個bean AutowiredAnnotationBeanPostProcessor :用於@Autowired標籤爲field注入依賴。 CommonAnnotationBeanPostProcessor --> <context:component-scan base-package="com.line.web.*"/> <!-- 配置註解式的Handler spring 3.1以前使用的是下面兩個 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/> spring 3.1以後默認注入的是 <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> --> <!-- 默認配置註解式的Handler--> <mvc:annotation-driven/> <!-- 配置視圖處理器,用於處理controller返回的視圖 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="WEB-INF/view/"/> <property name="suffix" value=".jsp"/> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> </bean> <!-- 配置靜態文件處理器 --> <mvc:resources location="/public/img/" mapping="public/img/**"/> <mvc:resources location="/public/js/" mapping="public/js/**"/> <mvc:resources location="/public/css/" mapping="public/css/**"/> <mvc:resources location="/public/file/" mapping="public/file/**"/> </beans>
想要讓咱們的項目支持JSON數據的話,必須作一些配置ajax
//spring 3.1以前的須要這樣配置 //方案一 <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" p:supportedMediaTypes="*/*" /> </mvc:message-converters> </mvc:annotation-driven> //方案二 顯式的定義messageConverters <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /> </list> </property> </bean>
//spring 3.1以後的版本 //方案一 <mvc:annotation-driven/> //方案二 <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" p:ignoreDefaultModelOnRedirect="true" > <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/> </list> </property> </bean>
配置好後,咱們的Controller只要這樣配置就星了spring
package com.line.web.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.line.web.model.User; import com.line.web.service.UserService; @Controller @RequestMapping("/user") public class UserManagerController{ @Autowired private UserService userService; @RequestMapping(value="/login",method=RequestMethod.POST) public @ResponseBody ModelMap login(@RequestBody User a,ModelMap model){ String account = a.getAccount(); String password = a.getPassword(); System.out.println("account: " + account); System.out.println("password: " + password); if( !userService.checkFormat(account, password)){ model.addAttribute("errorMsg","帳號和密碼不能爲空,且不帶特殊字符"); return model; } User user = userService.verification(account, password); if(user != null){ model.addAttribute("user",user); model.addAttribute("userId",user.getId()); }else{ model.addAttribute("errorMsg","帳戶不存在或密碼錯誤!"); } return model; } }
class User{ private String account; private String password; public String getAccount(){ return account; } public String getPassword(){ return password; } public void setPassword(String password){ this.password = password; } public void setPassword(String account){ this.account = account; } }
頁面的ajax只要向下面寫就行
json
$.ajax({ url: "user/login", type:"POST", cache:false, headers:{ 'Content-Type':'application/json', 'Accept':'application/json' }, dataType:"json", /* 有問題的版本 data: { 'account' : $("#lg-account").val(), 'password' : $("#lg-psw").val() }, */ data: JSON.stringify({ 'account' : $("#lg-account").val(), 'password' : $("#lg-psw").val() }), error: function(){}, success: function(data){} });
這裏再說一下在配置中可能出現的錯誤,好比406和415,分別是「沒法接受」以及「不支持媒體類型」,看到這裏你們均可能猜到多是json的問題,咱們首要排除的是,咱們的jar包引進來了沒有,由於這個和json的轉換息息相關,這部分沒有問題後,前面Ajax代碼註釋裏有提到一個有問題的版本,原本查了一下JQuery它的ajax函數裏的data只接受spring或者plainObject ,這裏的plainObject在通過spring 轉換器轉換的時候就有問題了,因此咱們必需要先將咱們的JSON序列化了,也就是JSON.stringify()這個方法。若是到這裏還有406的問題,那麼看一下你的http請求頭裏面Content-Type是application/json,記得在Ajax裏設置好請求頭。基本到如今就能夠了。spring-mvc