Spring 3 MVC with JSON via Jackson 2.0

Spring 3.1.2 adds support for automatic conversion to JSON via Jackson 2.x. There isn’t much that you need to do to make it work, with on caveat.

You need to be using at least Spring 3.1.2 to have Jackson 2.x support. Add the Jackson 2.x dependencies.

1
2
3
4
5
6
7
8
9
10
< dependency >
     < groupId >com.fasterxml.jackson.core</ groupId >
     < artifactId >jackson-core</ artifactId >
     < version >2.0.4</ version >
</ dependency >
< dependency >
     < groupId >com.fasterxml.jackson.core</ groupId >
     < artifactId >jackson-databind</ artifactId >
     < version >2.0.4</ version >
</ dependency >

Game项目中pom

               <dependency>

<groupId>org.codehaus.jackson</groupId>

<artifactId>jackson-mapper-asl</artifactId>

<version>1.8.5</version>

</dependency>

因为使用maven管理jar包,会自动下载依赖的jackson-core-asl-1.8.5.jar

NOTE: If you only include the jackson-core artifact and do not include the jackson-databind artifact, your spring requests will return HTTP 406 errors and there will be no indication of what the real problem is.

What happens if you don’t include jackson-databind? The <mvc:annotation-driven/> tag will not instantiate a MappingJackson2JsonView because it has an import for com.fasterxml.jackson.databind.ObjectMapper. There is no message because it just thinks that you are not using that.

Your spring mvc context should already have the <mvc:annotation-driven/>.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<? xml version = "1.0" encoding = "UTF-8" ?>
        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"
        xmlns:mvc = "http://www.springframework.org/schema/mvc"
 
     < context:component-scan base-package = "com.appriss.jxp" />
     < mvc:annotation-driven />
 
     <!-- Resolves view names for views returned by controllers -->
     < bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver"
           p:viewClass = "org.springframework.web.servlet.view.JstlView"
           p:prefix = "/WEB-INF/jsp/"
           p:suffix = ".jsp" />
</ beans >

Create a controller method. There are 2 things that must be done. First, specify that the method does produce json as the output. That will map against the “accept-header: application/json”. Then have the method return an object instead of a ModelAndView object. Annotate that object with @ResponseBody.

1
2
3
4
5
6
7
8
9
/**
  * Returns a json list of first names.
  * @param term the beginning part of the first name
  * @return json string array of first names
  */
@RequestMapping (value = "/first" , produces = "application/json" )//produces spring-web3.1以上才支持
public @ResponseBody List<String> firstNames( @RequestParam String term) {
     return nameDao.getFirstNames(term);
}

There you have it. The rest is automatic.

你可能感兴趣的:(Spring 3)