Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize data Exchange by SpringBoot

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of "how to achieve data interaction in SpringBoot". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to achieve data interaction in SpringBoot" can help you solve the problem.

1. Data format

In the actual project scenario, front and back separation is almost the standard configuration of all projects, the era of full stack is gradually gone, the back end is responsible for business logic processing, and the front end is responsible for data display has become a fixed development mode. Generally speaking, in the data interface provided by the back end, there may be two forms of data, Json and XML, which is often related to the company's engineer culture.

1.1. Json message

For SpringBoot, it uses Json as the response message format by default. Let's test it with a simple example:

First, we create a UserController to handle the front-end Web request.

@ Controller@RequestMapping ("/ sys/user") public class UserController {@ RequestMapping ("login") @ ResponseBody public Map login () {Map hashMap = new HashMap (); hashMap.put ("msg", "login successful"); return hashMap;}}

I believe this example is not unfamiliar to most people who have used SpringMVC. Define a simple controller and equivalent mapping. Unlike the Controller that usually returns Url, we use the @ ResponseBody annotation here, which indicates that the response of this interface is pure data without any interface display. The output of the address corresponding to the request is as follows:

Obviously, we got the desired result, a standard format Json string, is not very simple.

Further optimizations can be made for the above code, and since all Restful interfaces just return data, we can add @ ResponseBody annotations directly at the class level. In most cases, @ Controller and @ ResponseBody are used together, so we replace them with the @ RestController annotation to implement the function more succinctly.

@ RestController@RequestMapping ("/ sys/user") public class UserController {@ RequestMapping ("login") public Map login () {Map hashMap = new HashMap (); hashMap.put ("msg", "login successful"); return hashMap;} 1.2. Xml message

In most cases, we can meet our needs by using Json, but there are still some specific scenarios that require the use of XML messages, such as Wechat official account development. However, don't worry, you only need to make minor changes to switch to XML messages. Add related dependencies as follows:

"com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.8.8"

Then we can start testing. Here, we can use a simulation HTTP request tool (Postman) to help us test the API. Without saying much about how to use it, we can go straight to the figure above:

In the above test example, we specified Accept as text/xml so that SpringBoot will return data in the form of XML.

two。 Interface specification

For every company, it will define its own data specification, a unified and standard data specification is very important for system maintenance, but also improves the development efficiency to a great extent.

2.1. Response message specification

Generally speaking, the interface response needs to tell the user at least three pieces of information: status code, description, and data. Among them, data is not required for every interface, and if it is just a simple modification action, there may be no need to return data. Let's define a Result class to encapsulate our response message.

Public class Result {private int code; private String msg; private Object data; public Result (ResultCode resultCode, Object data) {this (resultCode); this.data = data;} public Result (ResultCode resultCode) {this.code = resultCode.getCode (); this.msg = resultCode.getMsg ();}.}

At the same time, define an enumeration class to maintain our status code:

Public enum ResultCode {SUCCESS (0, "request successful"), WARN (- 1, "network exception, please try again later"); private int code; private String msg; ResultCode (int code, String msg) {this.msg = msg;} public int getCode () {return code;} public String getMsg () {return msg;}}

In this way, our response data specification has been basically established. Modify the return Map in the above code to return Result, and return the data according to the specified specification. The result is as follows.

2.2. Request data specification

We have defined the format of the response message, so how do we receive the request data? Generally speaking, the request and response will use the same message form, that is, if the response is Json, then the request is also recommended to use Json. If you want to add input parameters to the login request above, you need to complete the following steps:

First, we define the user entity:

Public class User {private String username; private String password;...}

Then, use the entity to receive the parameters directly in the mapping method, and return the received parameters directly:

@ RestController@RequestMapping ("/ sys/user") public class UserController {@ RequestMapping ("login") public Result login (@ RequestBody User loginUser) {return new Result (ResultCode.SUCCESS, loginUser);}}

Call up our Postman, enter the correct Url, select POST to send the request, select Body, set Content-Type to application/json, enter the request data in Json format, and click Send to get the following result.

Data reception is very successful, but in the above response message, there is a very serious problem, that is, the user's password is also returned to the client along with the user information, which is obviously not a correct approach. We need to filter it once, because SpringBoot uses Jackson as the Json serialization tool by default, if you want to filter out some fields in the response, simply add the @ JsonIgnore annotation to the get method corresponding to the filter field. However, this will lead to another problem, that is, the fields in the request are also filtered out. For this problem, you can extract the request parameter model, that is, customize the Model received by a set of parameters. For example, users who log in will use UserModel to receive parameters, which makes the request parameter model completely separated from the database mapping entity, which improves the security of the system to a certain extent.

@ RequestMapping ("login") public Result login (@ RequestBody UserModel userModel) {User user = new User (); user.setUsername (userModel.getUsername ()); user.setPassword (userModel.getPassword ()); return new Result (ResultCode.SUCCESS, user);}

After replacing it with the Model object, we can add the @ JsonIgnore annotation to the database mapping entity User to ignore the serialization of the field without affecting the input of the request parameters.

3. Parameter check

For the sake of system robustness, generally speaking, we need to check the necessity of all the parameters, such as: when a login request, if there is no user name, the program should reject the request immediately. The abstraction of the above request parameter model (Model) also makes it easier for us to validate data, which mainly depends on the strong support of SpringBoot's Validate feature.

3.1. Simple parameter check

For the login interface, the user name and password are required, so we now add the corresponding parameter check, without if-else judgment, a few simple comments can help us to complete all the work.

@ RequestMapping ("login") public Result login (@ RequestBody @ Valid UserModel userModel) {...}-- public class UserModel {private String username; private String password; @ NotBlank (message = "user name cannot be empty") public String getUsername () {return username;} @ NotBlank (message = "password cannot be empty") public String getPassword () {return password;}.}

In the above example, we annotate the Model object that requests the parameters with @ Valid, and in the Model class, add the corresponding check annotation to the get method that needs to verify the field. The effect is as follows:

3.2. Complex parameter check 3.2.1. Regular expression check

If the user's login name is the mobile phone number, then the format of the login name needs to be further checked, and the following regular expressions are used to verify the validity of the mobile phone number.

@ NotBlank (message = "user name cannot be empty") @ Pattern (regexp = "1 (([38]\ d) | (5 [^ 4 & &\\ d]) | (4 [0135678]))\\ d {8}", message = "invalid mobile number format") public String getUsername () {return username;} 3.2.2. Custom check comment

In the process of using the system, there are many places that need to check the format of the mobile phone number, such as: registration, CAPTCHA transmission and so on. However, the regular expression for verifying the mobile phone number is too complex, and if it is written in many places, once the operator adds a certain number segment, it will be bad news for the maintenance personnel of the program. At this point, you can use custom check annotations instead of these commonly used checks.

Mobile number verification implementation class PhoneValidator:

Public class PhoneValidator implements ConstraintValidator {private Pattern pattern = Pattern.compile ("1 (([38]\ d) | (5 [^ 4 & &\ d]) | (7 [0135678]))\\ d {8}"); @ Override public void initialize (Phone phone) {} @ Override public boolean isValid (String value, ConstraintValidatorContext constraintValidatorContext) {return pattern.matcher (value). Matches ();}}

Mobile phone number check Note Phone:

@ Constraint (validatedBy = PhoneValidator.class) @ Target ({ElementType.METHOD, ElementType.FIELD}) @ Retention (RetentionPolicy.RUNTIME) @ Documentedpublic @ interface Phone {String message () default "invalid Mobile number format"; Class [] groups () default {}; Class

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report