2022-1-18 spring MVC data echo and JSON processing


The data is staggered. If there is no echo, it needs to be filled in again. (AJAX does not have this problem. It needs to be handled if it is filled in with a form)

1, Manual data echo

eg. a form page addstudent jsp

<%--
  Created by IntelliJ IDEA.
  User: 86133
  Date: 2022/1/18
  Time: 10:04
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="/addstudent2" method="post" >
    <table>
        <tr>
            <td>user name</td>
            <td><input type="text" name="name" value="${name}"></td>
        </tr>
        <tr>
            <td>email</td>
            <td><input type="text" name="email" value="${email}"></td>
        </tr>
        <tr>
            <td>Age</td>
            <td><input type="text" name="age" value="${age}"></td>
        </tr>
        <tr>
            <td><input type="submit" value="add to"></td>
        </tr>
    </table>
</form>

</body>
</html>

The server fills in the fields and displays the data manually
This is received using simple data types, and the framework does nothing

 @PostMapping("/addstudent2")
    public String addStudent2(String name, String email, Integer age, Model model)
    {
        model.addAttribute("name",name);
        model.addAttribute("email",email);
        model.addAttribute("age",age);
        return "addstudent";
    }

2, Automatic data echo

Echo to return to a view
If you receive with an object
One student is added to the pre filled data Prefix, which is the variable name of the data received by the server (the back end receives the data and then returns it to the front end!)

student is the variable name at the back-end receiver:

You can rename the received variables:

The front end can use s instead of student

3, @ ModelAttribute

Two functions:

  1. When data echo, define aliases for variables
  2. Define global data

There are many interfaces defined in the Controller. In many interfaces, you need to return some data to the front end. You can define a global data and use it.

    
    @ModelAttribute("info") //info is the name of this variable. Every interface in the controller can use this variable and return it to the front end
    public Map<String,Object> info()
    {
        Map<String,Object> map=new HashMap<>();
        map.put("username","kkzzjx");
        map.put("site","www.kk.com");
        return map;
    }
    
    @GetMapping("/add")
    public String addStudent3(){
        return "addstudent";
        
    }

Map to addstudent After the JSP view, the info variable can be used.

<a href="${info.site}">${info.username}</a>

4, Return JSON

return json: object return, converted to json
Mainstream json processing tools:

  • jackson
  • gson
  • fastjson

In spring MVC, jackson and gson are supported accordingly. Using these two as json converters, you only need to add corresponding dependencies.
Use fastjson: add dependency + configure HttpMessageConverter converter (the first two are provided automatically)

1. jackson

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.1</version>
        </dependency>

When jackson is added, JSON can be returned automatically. This depends on a class called HttpMessageConverter, which is used as an http message converter.
Function:

  1. Turn the returned object into json (to the front end)
  2. Convert the json submitted by the front end into an object

eg.
Book

    private String name;
    private String author;
    private Integer id;
    @JsonFormat(pattern = "yyy-MM-dd",timezone = "Asia/Shanghai")
    private Date date;

controller

@Controller
public class BookController {
    @GetMapping("/book")
    @ResponseBody
    public Book getBookById(Integer id)
    {
        Book book=new Book();
        book.setId(id);
        book.setName("Romance of the Three Kingdoms");
        book.setAuthor("Luo Guanzhong");
        book.setDate(new Date());
        return book;//Returning to the front end is a json
    }
    //In this way, the returned object / array will be parsed into json

    @GetMapping("/books")
    @ResponseBody
    public List<Book> getAllBooks()
    {
        List<Book> books=new ArrayList<>();
        Book b1=new Book();
        b1.setName("Romance of the Three Kingdoms");
        b1.setId(1);
        b1.setAuthor("Luo Guanzhong");
        books.add(b1);
        return books;
    }
}

For dates, you can add the @ JsonFormat attribute
@JsonFormat(pattern = "yyy-MM-dd",timezone = "Asia/Shanghai")
So how do you define global settings?

ctrl+N in IDEA can search for classes:

 public MappingJackson2HttpMessageConverter(com.fasterxml.jackson.databind.ObjectMapper objectMapper) { /* compiled code */ }

The following can be configured in driven:
(global configuration)

  <mvc:annotation-driven validator="validatorFactoryBean">
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" id="httpMessageConverter">
                <property name="objectMapper">
                    <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                        <property name="dateFormat">
                            <bean class="java.text.SimpleDateFormat">
                                <constructor-arg name="pattern" value="yyyy-MM-dd"/>
                            </bean>
                        </property>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

2. gson

Android is widely used in development

Dependency:

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.9</version>
</dependency>

If jackson and gson exist at the same time, jackson is preferred

3. fastjson

The fastest json parser

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.79</version>
</dependency>

In spring MVC, there is no corresponding HttpMessageConverter for fastjson, so you need to configure HttpMessageConverter when using fastjson

Configuration in driven:

    <mvc:annotation-driven validator="validatorFactoryBean">
        <mvc:message-converters>
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter" id="httpMessageConverter">
                <property name="fastJsonConfig">
                    <bean class="com.alibaba.fastjson.support.config.FastJsonConfig">
                        <property name="dateFormat" value="yyyy-MM-dd"/>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

If Chinese is garbled, you can add attributes

                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=utf-8</value>
                    </list>
                </property>

5, Receive JSON @RequestBody

Use the * * @ RequestBody * * annotation to receive json

    @PostMapping("/book")
    @ResponseBody
    public Book addBook(@RequestBody Book book)
    {
        return book;
    }

postman test:
set up:

Keywords: Java JSON

Added by nigaki on Sat, 22 Jan 2022 20:05:58 +0200