2018/2/25

  1. 系統環境

    • Spring Framework v4.3.14.RELEASE
    • Tomcat 8.0.48
  2. 在 pom.xml 加入以下設定

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.8.11</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.11</version>
    </dependency>
    
  3. 在 web-context.xml 加入以下設定

    <bean id="messageAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
            </list>
        </property>
    </bean>
    
  4. 加入一個 JSON Object

    package idv.shunyi.entity;
    
    public class JarFile {
    
        private long id;
        private String fileName;
        private String fileType;
        private String mainClass;
    
        public long getId() {
           return id;
        }
        public void setId(long id) {
           this.id = id;
        }
        public String getFileName() {
           return fileName;
        }
        public void setFileName(String fileName) {
           this.fileName = fileName;
        }
        public String getFileType() {
           return fileType;
        }
        public void setFileType(String fileType) {
           this.fileType = fileType;
        }
        public String getMainClass() {
           return mainClass;
        }
        public void setMainClass(String mainClass) {
           this.mainClass = mainClass;
        }
    }
    
  5. Controller 寫法如下:

    @RequestMapping(value = "/testJsonObject.do", produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String param(@RequestBody JarFile jarFile) {
        String value = jarFile.getFileName();
        System.out.println(value);
        return value;
    }
    
  6. Client 端寫法如下 (e.g. JQuery ajax):

    function test() {
        $.ajax({
           method : 'post',
           url: 'testJsonObject.do',
           data: JSON.stringify({ id: '0', fileName: 'test-中文檔名.jar', fileType: 'jar', mainClass: 'idv.shunyi.entity.JarFile'}),
           contentType:'application/json; charset=UTF-8',
           success: function(data) {
             alert(data);
           }
        });
    };
    
  7. Reference
    Passing JSON Map into Spring MVC Controller