Json序列化输出

引用这个包: jquery-3.3.1.min.js

package com.wei.restful.controller;
import com.wei.restful.entity.Person;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController//不需要使用@ResponseBody
@RequestMapping("/restful")
public class RestfulController {

    @GetMapping("/request")
  //  @ResponseBody
    public String doGetRequest(){
        //双引号中如果包含双引号,需要使用转义符  \"
        return "{\"message\":\"返回查询结果\"}";
    }
    //Post/article/1
    //post/restful/request/100
    @PostMapping("request/{rid}")
    public String doPostRequest(@PathVariable("rid") Integer requestId){
        return"{\"message\":\"数据新建成功\",\"id\":"+requestId+"}";
    }

    @GetMapping("/person")
    public Person findByPersonId(Integer id){
        Person p =new Person();
        if (id==1){
            p.setName("莉莉");
            p.setAge(24);
        }else if (id==2){
            p.setName("默默");
            p.setAge(23);
        }else{
            p.setName("你好");
            p.setAge(22);
        }
        return p;

    }

    @GetMapping("/persons")
    public List<Person>findPersons() {
        List lsit = new ArrayList();
        Person p1 = new Person();
        p1.setName("莉莉");
        p1.setAge(24);
        p1.setBirthday(new Date());
        Person p2 = new Person();
        p2.setName("默默");
        p2.setAge(22);
        p2.setBirthday(new Date());

        lsit.add(p1);
        lsit.add(p2);

        return lsit;
    }
}
package com.wei.restful.entity;

import com.fasterxml.jackson.annotation.JsonFormat;

import java.util.Date;

public class Person {
    private String name;
    private Integer age;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private Date birthday;

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

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

 

 

applicationContext.xml

<?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:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.2.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
    <context:component-scan base-package="com.wei.restful"/>


    <!--    启动springMVc的注解开发模式-->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <!--                        相当于response.setContentType("text/html;charset=utf-8")-->
                        <value>text/html;charset=utf-8</value>
                        <value>application/json;charset=utf-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <!--    将图片/JS/CSS等静态资源排除在外,可提高执行效率-->
    <mvc:default-servlet-handler/>
</beans>

 

 

 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_3_1.xsd"
         version="3.1">
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--        xml文件是存放在哪个路径中-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
        <!--        在web应用启动时自动创建springIOC容器中,并初始化DispatcherServlet-->
        <load-on-startup>0</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!--        /代表拦截所有请求
        1、<url-pattern>/</url-pattern>
        /: 会匹配到/login这样的路径型url,不会匹配到模式为*.jsp这样的后缀型url
        2、 <url-pattern>/*</url-pattern>
        /*:会匹配所有url(只匹配当前文件夹下文件,不匹配子文件夹下文件):路径型的和后缀型的url(包括/login,*.jsp,*.js和*.html等)
        3、<url-pattern>/**</url-pattern>
        /** : 会匹配所有url(匹配当前文件夹下文件和子文件夹下文件):路径型的和后缀型的url(包括/login,*.jsp,*.js和*.html等)
        一般情况下DispatcherServlet只需要处理我们向后台服务器的请求,不需要处理静态页面等内容,所以,建议使用/-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>characterFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Restful实验室</title>
    <script src="jquery-3.3.1.min.js"></script>
    <script>
        $(function () {
            $("#btnGet").click(function () {
                $.ajax({
                    url:"restful/request",
                    type:"get",
                    dataType:"json",
                    success:function (json) {
                        $("#message").text(json.message);
                    }
                })
            })
        })

        $(function () {
            $("#btnPost").click(function () {
                $.ajax({
                    url:"restful/request/100",
                    type:"post",
                    dataType:"json",
                    success:function (json) {
                        $("#message").text(json.message+":"+json.id);
                    }
                })
            })
        })
        
    //    页面就绪函数
        $(function () {
            $("#btnPersons").click(function () {//点击按钮以后,在当前页面中
                $.ajax({
                    url: "/restful/persons",
                    type:"get",
                    dataType:"json",
                    success:function (json) {
                        console.info(json);
                        for (var i = 0; i <json.length ; i++) {
                            var p=json[i];
                            $("#divPersons").append("<h2>"+p.name+":"+p.age+p.birthday+"</h2>")
                        }
                    }

                })
            })
        })
    </script>
</head>
<body>
<input type="button" id="btnGet" value="发送Get请求" >
<input type="button" id="btnPost" value="发送Post请求" >
<h1 id="message"></h1>

<hr>
<input type="button" id="btnPersons" value="查询所有人员">
<div id="divPersons"></div>
</body>
</html>

 

上一篇:restful


下一篇:初始化 RESTful API 风格的博客系统