- JSON interface Development
In the previous spring development, we needed to provide the following configuration when we provided the JSON interface:
1 adding jar packages such as Jackjson
2 Configuring the Spring Controller scan
3 Docking method Add @responsebody
If you use spring boot, you only need the class to add @RestController
, and the methods in the default class are returned in JSON format.
Example 1:
/*** @RestController = @Controller + @ResponseBody. So, when you define a Controller later, you can use @controller directly, if you need to return JSON can be added directly in the method @responsebody *@author1 **/@RestController Public classHellocontroller {@RequestMapping ("/hello") PublicHashmap<string, string>Hello () {HashMap<string, string> map =NewHashmap<string, string>(); Map.put ("W", "1"); Map.put ("Wq", "12"); Map.put ("Wq1", "123"); Map.put ("Wq12", "123"); returnmap; //return "Hello"; }}
The results of the operation are as follows:
Example 2:
PackageCom.cfj.testboot.controller;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RestController;Importcom.cfj.testboot.domain.UserDo; @RestController Public classTestreturnjson {@RequestMapping ("/returnjson") PublicUserdo Testreturnjson () {Userdo u=NewUserdo (); U.setid (1); U.settname ("Testers"); returnu; }}
The results of the operation are as follows:
@RestController annotations, equivalent to @[email protected] Two annotations, the return JSON data does not need to be preceded by the method @responsebody annotations, but using @restcontroller this annotation, Cannot return jsp,html page, view parser cannot parse jsp,html page
@RequestMapping
Requestmapping is an annotation that handles request address mappings and can be used on classes or methods. On a class, the method that represents all response requests in a class is the parent path of the address.
The following code accesses the path: Http://localhost:8081/test/returnjson
PackageCom.cfj.testboot.controller;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RestController;ImportCom.cfj.testboot.domain.UserDo, @RestController @requestmapping ("/test") Public classTestreturnjson {@RequestMapping ("/returnjson") PublicUserdo Testreturnjson () {Userdo u=NewUserdo (); U.setid (1); U.settname ("Testers"); returnu; }}
Spring Boot web Development