SpringMVC: JSON data interaction

JSON data interaction

The front end can be written in many languages, but basically the backend is developed in Java. In addition to C ++ (long development cycle), PHP and #Net (pursuing speed, rapid development), these three types can also be written in the backend.

Browsers and java programs use jsp, js.

Android, IOS client and Java programs deal with each other and send JSON strings. The Java program receives it, parses the JSON string, forms a POJO object, and then performs business processing. After processing, it becomes a POJO or a wrapper class object or a List collection, which is converted into a JSON string and sent back to the Android and IOS clients.

So if you master the JSON data interaction, you don't need to care what language the front end is developed in.

Project structure

jar包

Entity class Student.java

@Component
@Scope("prototype")
public class Student {
    private int id;
    private String name;
    private int age;
    private float score;

    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

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

    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }

    public float getScore() { return score; }

    public void setScore(float score) { this.score = score; }
}

The front-end page index.jsp uses ajax to initiate the request

If you want to request plain text (string), change the value of dateType to text.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>JSON</title>
</head>
<body>
<form>
    学号:<input type="text" id="id"><br/>
    <button type="button" id="btn">查询学生信息</button>
</form>
<p id="show"></p>

<%-- <script src="${pageContext.request.contextPath}/js/jquery.min.js"></script> --%>
<script src="js/jquery-3.4.1.min.js" type="text/javascript"></script>
<script>
    $("#btn").click(function () {
        $.ajax({
            //开头不能加/,但可以加 ${pageContext.request.contextPath}/
            url: "studentController/queryStudent",
            type: "post",
            // 传给后台的数据类型、使用的字符集。可以缺省,因为data:{},看到{}就会自动作为json处理
            // contentType:"application/json;charset=utf-8",
            //传给后台的数据,json形式,key是String类型,value可以是多种类型,键值对之间逗号分隔
            data: {"id": $("#id").val()},
            //期待的返回值类型(回调函数的参数类型)
            dataType: "json",
            error: function () {
                console.log("ajax请求数据失败!");
            },
            success: function (data) {
                //浏览器把接受到的json数据作为js对象,可通过.调用属性
                var info = "姓名:" + data.name + ",年龄:" + data.age + ",成绩:" + data.score;
                $("#show").text(info);
            }
        })
    });
</script>
</body>
</html>

The background uses the controller to handle ajax requests

You can use the simple data type to receive the data from the front end, or you can use Bean to receive it (will be assigned to the attribute with the same name).

Many tutorials say that you need to add @RequestBody in front of the parameters of the business method to convert the data from ajax to the required type;

In fact, with the replacement of the version, the built-in converter of the higher version of SpringMVC can already convert the data transmitted by ajax to the required type, and adding @RequestBody will cause an error.

 

You need to add the annotation @ResponseBody on the business method, where the solution will automatically add the return value to the response body to respond to the ajax request.

No matter whether the request is text or json, you need to use @ResponseBody.

 

If the request is text, write the return value type as String;

If the request is json, the return value can be written as a bean (returning a json object, such as requesting information from a student), or it can be written as a List (returning a json array, such as requesting information from multiple students).

@Controller
@RequestMapping("studentController")
public class StudentController {
    private Student student;

    @Autowired
    public void setStudent(Student student) {
        this.student = student;
    }

    @RequestMapping("/queryStudent")
    @ResponseBody
    public Student queryStudent(int id) {
        System.out.println(id);
        //此处省略连接数据库查询
        student.setName("chy");
        student.setAge(20);
        student.setScore(100);
        return student;
    }
}

springmvc.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
      http://www.springframework.org/schema/mvc 
      http://www.springframework.org/schema/mvc/spring-mvc-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/aop
      http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

    <!--
        可以扫描controller、service、...
        这里让扫描controller,指定controller的包
     -->
    <context:component-scan base-package="org.haiwen"></context:component-scan>

    <!-- 开启spring对mvc的注解支持(全注解一定要配置) -->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <!-- 解决Controller返回json中文乱码问题 -->
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!-- 静态资源放行 -->
    <mvc:default-servlet-handler />

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize">
            <value>10000000000</value> <!-- 以字节byte为单位 -->
        </property>
        <property name="defaultEncoding">
            <value>UTF-8</value>
        </property>
    </bean>
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">

    <!-- 配置SpringMVC的核心控制器DispatcherServlet(负责所有请求的公共功能,然后在分发给具体的控制器(我们编写的控制器),完成业务逻辑,响应视图。) -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--
            服务器在启动的时候,去加载springmvc的配置文件
            如果不配置就默认去WEB-INF文件夹下找:<servlet-name>-servlet.xml的配置(这种方式需要拷贝配置文件到WEB-INF)
         -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <!-- Servlet容器启动的时候就进行初始化 -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!-- 请求的入口,所有请求都会经过DispatcherServlet处理   /:支持RESTful风格 -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>


    <!-- 配置编码过滤器 ==>目的:解决SpringMVC post提交数据时的乱码问题  -->
    <filter>
        <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

test

Published 202 original articles · praised 37 · 30,000+ views

Guess you like

Origin blog.csdn.net/lovecuidong/article/details/104560740