Pom文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>spring-mvc</artifactId>
  7. <groupId>com.xixi</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>springmvc_json</artifactId>
  12. <dependencies>
  13. <dependency>
  14. <groupId>org.springframework</groupId>
  15. <artifactId>spring-webmvc</artifactId>
  16. <version>5.2.3.RELEASE</version>
  17. </dependency>
  18. <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
  19. <dependency>
  20. <groupId>com.fasterxml.jackson.core</groupId>
  21. <artifactId>jackson-core</artifactId>
  22. <version>2.10.3</version>
  23. </dependency>
  24. <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
  25. <dependency>
  26. <groupId>com.fasterxml.jackson.core</groupId>
  27. <artifactId>jackson-databind</artifactId>
  28. <version>2.10.3</version>
  29. </dependency>
  30. <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
  31. <dependency>
  32. <groupId>com.fasterxml.jackson.core</groupId>
  33. <artifactId>jackson-annotations</artifactId>
  34. <version>2.10.3</version>
  35. </dependency>
  36. </dependencies>
  37. </project>

2.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">


    <!--DispatchServlet的配置 分发器 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <!-- TOMCAT容器启动的时候下载-->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


    <!-- 从上往下加载filter-->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <!--解决post请求乱码-->
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <!--解决响应乱码-->
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

3.Controller

package com.xixi.controller;

import com.xixi.enitity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;


/**
 * 1.加入jackson依赖
 * 2。将jackson的jar包加入到WEB-INF/lib目录中
 * 3。在对应到处理方法上加上@ResponeBody注解
 *
 *
 * @RestController设置之后所有的方法都是json请求和返回
 *
 *
 **/
@Controller
public class JsonController {

    @RequestMapping("/json")
    @ResponseBody
    public User responseJson(){

        System.out.println("json");

        User user = new User();
        user.setId(1);
        user.setName("zs");
        user.setPassword("12345");
        user.setBirthday(new Date());
        return user;
    }

    @PostMapping("/json/request01")
    @ResponseBody
    public User request01(@RequestBody String name){
        System.out.println("name:"+name);
        User user = new User();
        user.setId(1);
        user.setName("zs");
        user.setPassword("12345");
        user.setBirthday(new Date());
        return user;


    }

    @PostMapping("/json/request02")
    @ResponseBody
    public User request02(@RequestBody User user){
//        System.out.println("name:"+name);
//        User user = new User();
//        user.setId(1);
//        user.setName("zs");
//        user.setPassword("12345");
//        user.setBirthday(new Date());
        System.out.println(user);
        return user;


    }
}

4.Pojo

package com.xixi.enitity;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.Date;

public class User {

    private Integer id;

    private String name;

    @JsonIgnore
    private String password;


    //JsonFormat会作用到请求和响应,和DateTimeFormat选择一个就可以
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date birthday;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

5.jsp页面


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>Title</title>
  <script src="https://cdn.staticfile.org/jquery/1.10.0/jquery.js"></script>
  <script type="text/javascript">
    $(function(){
      $("#btn01").click(function (){
        $.ajax({
          url:"${pageContext.request.contextPath}/json/request01",
          method:"post",
          data:"xixi",
          contentType:"application/json",
          dataType:"json",
          success:function (result){
            alert(result.name);
          }
        });
      });


      var user = '{"id":1,"name":"lisi"}';
      $("#btn02").click(function (){
        var user={'id':'1','name':'张三'};   // 定义js对象
        var jsonValue=JSON.stringify(user); // 对象转换为json字符串
        console.log(jsonValue)
        $.ajax({
          url:"${pageContext.request.contextPath}/json/request02",
          method:"post",
          data:'{"id":1,"name":"张三","birthady":"2019-01-01"}',
          contentType:'application/json',
          dataType:"json",
          success:function(user){
            alert(user.name);
          }
        });
      });
    })
  </script>
</head>

<body>
<input id="btn01" type="button" value="发送单个数据"/>
<p></p>
<input id="btn02" type="button" value="发送单个对象"/>

</body>
</html>