2024.3.13 Wednesday
Continuing from 【WEEK3】 【DAY2】JSON Interaction Handling Part One 【English Version】
Contents
- 6.4 Code Optimization
- 6.4.1 Unified Solution for Garbled Text
- 6.4.2 Unified Solution for Returning JSON Strings
- 6.5 Testing Collection Output
- 6.5.1 Add a new method json2 in UserController.java
- 6.5.2 Run
- 6.6 Outputting Time Objects
- 6.6.1 Add a new method json3 in UserController.java
- 6.6.2 Run
- 6.6.3 Changing the Method of Outputting Time
- 6.6.3.1 Java Solution
- 6.6.3.2 ObjectMapper Formatted Output
6.4 Code Optimization
6.4.1 Unified Solution for Garbled Text
- The previous method is cumbersome as it requires adding code for each request in the project. We can specify a uniform configuration through Spring, which eliminates the need to handle garbled text each time. A StringHttpMessageConverter conversion configuration can be added in the
springMVC
configuration file. - Modify springmvc-servlet.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.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Automatically scan the specified package, all annotated classes below are managed by the IOC container -->
<context:component-scan base-package="P14.controller"/>
<!-- Configuration to solve JSON garbled text issue -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- View Resolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- Prefix -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- Suffix -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
- Now revert
UserController.java
to the version without the garbled text solution (comment out the following line) to check the effectiveness of this method.
//Fix garbled text issue
// @RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")
- Run to check that the garbled text issue has been resolved.
http://localhost:8080/springmvc_05_json_war_exploded/j1
6.4.2 Unified Solution for Returning JSON Strings
- Use
@RestController
directly on the class so that all methods return JSON strings without adding @ResponseBody for each method. @RestController is commonly used in front-end and back-end separated development, which is very convenient.
package P14.controller;
import P14.project.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
//@Controller //Through view resolver
@RestController //Not through view resolver, the following methods will only return JSON strings (The scope is very broad, so there is no need to write @ResponseBody on line 18)
public class UserController {
//Fix garbled text issue
// @RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")
@RequestMapping("/j1")
// @ResponseBody //Will not go through the view resolver, will directly return a string
public String json1() throws JsonProcessingException {
//Use ObjectMapper from imported jackson-databind package
ObjectMapper mapper = new ObjectMapper();
//Create an object
User user = new User("Zhang San",11,"female");
//Convert an object to a string
String str = mapper.writeValueAsString(user);
//Due to @ResponseBody annotation, this will convert str to JSON format and return it; very convenient
return str;
}
}
- The run results are the same as above, not much to elaborate.
6.5 Testing Collection Output
6.5.1 Add a new method json2 in UserController.java
@RequestMapping("/j2_set")
public String json2() throws JsonProcessingException {
//Use ObjectMapper from imported jackson-databind package
ObjectMapper mapper = new ObjectMapper();
//Create a collection
List<User> userList = new ArrayList<>();
User user1 = new User("Zhang San",11,"female");
User user2 = new User("Li Si",11,"male");
User user3 = new User("Wang Wu",11,"female");
//Add users to collection
userList.add(user1);
userList.add(user2);
userList.add(user3);
//Convert a collection to a string
String str = mapper.writeValueAsString(userList);
//Return multiple objects
return str; //Equivalent to returning new ObjectMapper().writeValueAsString(userList)
}
6.5.2 Run
http://localhost:8080/springmvc_05_json_war_exploded/j2_set
6.6 Outputting Time Objects
6.6.1 Add a new method json3 in UserController.java
@RequestMapping("/j3_time")
public String json3() throws JsonProcessingException {
//Use ObjectMapper from imported jackson-databind package
ObjectMapper mapper = new ObjectMapper();
//Make sure to import from java.util package
Date date = new Date();
//ObjectMapper default timestamp format after parsing time
return mapper.writeValueAsString(date);
}
6.6.2 Run
http://localhost:8080/springmvc_05_json_war_exploded/j3_time
The string of numbers obtained from the run is a timestamp, which is Jackson’s default time conversion form. Timestamp refers to the number of seconds passed since January 1, 1970 (midnight UTC/GMT), not considering leap seconds. Reference link: https://tool.lu/timestamp/
6.6.3 Changing the Method of Outputting Time
Add a method on top of the above to have the output time appear in a custom way.
6.6.3.1 Java Solution
- Create json4
@RequestMapping("/j4_time")
public String json4() throws JsonProcessingException {
//Use ObjectMapper from imported jackson-databind package
ObjectMapper mapper = new ObjectMapper();
//Make sure to import from java.util package
Date date = new Date();
//Use custom date format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//ObjectMapper default timestamp format after parsing time
return mapper.writeValueAsString(sdf.format(date));
}
- Run
http://localhost:8080/springmvc_05_json_war_exploded/j4_time
6.6.3.2 ObjectMapper Formatted Output
- Create json5
@RequestMapping("/j5_time")
public String json5() throws JsonProcessingException {
//Use ObjectMapper from imported jackson-databind package
ObjectMapper mapper = new ObjectMapper();
//Format output with ObjectMapper
//Turn off timestamp usage
mapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS,false);
//Use custom date format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//Set a new custom timestamp usage
mapper.setDateFormat(sdf);
//Make sure to import from java.util package
Date date = new Date();
//ObjectMapper default timestamp format after parsing time
return mapper.writeValueAsString(date);
}
- Run
http://localhost:8080/springmvc_05_json_war_exploded//j5_time