In Spring MVC, the way we usually handle Ajax mainly depends on the configuration of the controller and return type.
Use @RequestMapping annotation
In Spring MVC, you can use @RequestMapping to annotate the controller method in Ajax. Typically, Ajax requests use the GET or POST method.
import .*; @RestController @RequestMapping("/api") public class MyController { @GetMapping("/data") public ResponseEntity<MyData> getData() { MyData data = new MyData(); // Create a data object return (data); // Return data } @PostMapping("/data") public ResponseEntity<String> postData(@RequestBody MyData data) { // Process the received data return ("Data received successfully"); } }
@RequestBody
@RequestBody can obtain the request body information and use @RequestBody annotation to identify the formal parameters of the controller method. The request body of the current request will assign a value to the formal parameters identified by the current annotation.
<!--Must use it nowpostRequest method,becausegetNo request body--> <form th:action="@{/test/RequestBody}" method="post"> username:<input type="text" name="username"><br> password:<input type="password" name="password"><br> <input type="submit"> </form>
@RequestMapping("/test/RequestBody") public String testRequestBody(@RequestBody String requestBody){ ("requestBody:"+requestBody); return "success"; }
Front-end sending request:
/* Method 1 axios({ method: 'get', // Request method, pass parameters in the form of name = value & name = value No matter whether the method of passing get or post, the request parameters will be spliced to the request address. The request parameters in this way can be obtained through () url: ‘', //Request path, params: { username: 'admin', //The request parameters sent in this json method are placed in the request body and transmitted to the server. The value transmitted in this way cannot be obtained by () password: '123456' } }).then(function (response) { (response); = ; } */ /* request format of axios * Request method: * 1. () * 2. () * 3. () * 4. () * 5. () * 6. () * 7. () * 8. () //Method 2 ("/test/RequestBody").then(function (response) { (response); = ; }); }, */ /* * The format of the request body * 1. Pass parameters using url * 2. Pass parameters using json */
RequestBody gets request parameters in json format
After sending ajax request using axios, the request parameters sent by the browser to the server are in two formats:
1、name=value&name=value...
, the request parameters can be passed()
Get, corresponding to SpringMVC, you can directly obtain such request parameters through the formal parameters of the controller method.
2、{key:value,key:value,...}
, it cannot pass at this time()
Get, we used the related jar packages gson or jackson that operate json to handle such request parameters, which can be converted into a specified entity class object or map collection. In SpringMVC, use it directly@RequestBody
Annotation of the formal parameters identifying the controller method can convert such request parameters into Java objects
Use @RequestBody to get the conditions for request parameters in json format:
Importing jackson dependencies
<dependency> <groupId></groupId> <artifactId>jackson-databind</artifactId> <version>2.12.1</version> </dependency>
Set the MVC annotation driver to enable in the Spring MVC configuration file
<!--OpenmvcAnnotation driver--> <mvc:annotation-driven />
In the formal parameter position of the controller method, set the parameters of the java type (entity class or map) to be converted into in the json format, and use the @RequestBody annotation to identify
<input type="button" value="Test @RequestBody to get request parameters in json format"@click="testRequestBody()"> <script type="text/javascript" th:src="@{/js/}"></script> <script type="text/javascript" th:src="@{/js/}"></script> <script type="text/javascript"> var vue = new Vue({ el:"#app", methods:{ testRequestBody(){ ( "/SpringMVC/test/RequestBody/json", {username:"admin",password:"123456"} ).then(response=>{ (); }); } } }); </script>
//Convert json format data to map collection@RequestMapping("/test/RequestBody/json") public void testRequestBody(@RequestBody Map<String, Object> map,HttpServletResponse response) throws IOException { (map); //{username=admin, password=123456} ().print("hello,axios"); } //Convert json format data into entity class object@RequestMapping("/test/RequestBody/json") public void testRequestBody(@RequestBody User user, HttpServletResponseresponse) throws IOException { (user); //User{id=null, username='admin', password='123456', age=null,gender='null'} ().print("hello,axios"); }
@RequestBody
@ResponseBody is used to identify a controller method, which can directly respond to the response body of the response message to the browser.
@RequestMapping("/testResponseBody") public String testResponseBody(){ //At this time, it will jump to the page corresponding to the success of the logical view return "success"; } @RequestMapping("/testResponseBody") @ResponseBody public String testResponseBody(){ //Respond to the browser data success at this time return "success"; }
RequestBody responds to browser json data
After the server processes ajax request, in most cases, it is necessary to respond to a java object to the browser. At this time, the java object must be converted into a json string before it can be responded to the browser. Previously, we used the jar package gson or jackson that operates json data to convert the java object to a json string. In SpringMVC, we can directly implement this function using the @ResponseBody annotation.
@ResponseBody responds to browser json data conditions:
1. Import jackson dependencies
<dependency> <groupId></groupId> <artifactId>jackson-databind</artifactId> <version>2.12.1</version> </dependency>
2. Set the annotation driver to enable mvc in the configuration file of SpringMVC
<!--OpenmvcAnnotation driver--> <mvc:annotation-driven />
3. Use @ResponseBody annotation to identify the controller method. In the method, the java object that needs to be converted to a json string and responds to the browser is used as the return value of the controller method. At this time, SpringMVC can directly convert this object into a json string and respond to the browser.
<input type="button" value="Test @ResponseBody to respond to data in browser json format"@click="testResponseBody()"><br> <script type="text/javascript" th:src="@{/js/}"></script> <script type="text/javascript" th:src="@{/js/}"></script> <script type="text/javascript"> var vue = new Vue({ el:"#app", methods:{ testResponseBody(){ ("/SpringMVC/test/ResponseBody/json").then(response=>{ (); }); } } }); </script>
//Respond to browser list collection@RequestMapping("/test/ResponseBody/json") @ResponseBody public List<User> testResponseBody(){ User user1 = new User(1001,"admin1","123456",23,"male"); User user2 = new User(1002,"admin2","123456",23,"male"); User user3 = new User(1003,"admin3","123456",23,"male"); List<User> list = (user1, user2, user3); return list; } //Response to the browser map collection@RequestMapping("/test/ResponseBody/json") @ResponseBody public Map<String, Object> testResponseBody(){ User user1 = new User(1001,"admin1","123456",23,"male"); User user2 = new User(1002,"admin2","123456",23,"male"); User user3 = new User(1003,"admin3","123456",23,"male"); Map<String, Object> map = new HashMap<>(); ("1001", user1); ("1002", user2); ("1003", user3); return map; } //Respond to browser entity class object@RequestMapping("/test/ResponseBody/json") @ResponseBody public User testResponseBody(){ return user; }
Use @RestController
use@RestController
Annotations can simplify the definition of the controller. This annotation is@Controller
and@ResponseBody
A combination of , meaning that all methods in the controller return data in JSON or XML format, not views.
This is the article about Spring MVC processing Ajax requests. For more related Spring MVC processing Ajax requests, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!