Full Tutorial: http://git.oschina.net/didispace/SpringBoot-Learning
First, review and elaborate on the, annotations used in the QuickStart @Controller
@RestController
@RequestMapping
. If you are unfamiliar with spring MVC and have not yet tried a QuickStart case, it is recommended that you take a look at QuickStart content first.
@Controller
: Modifier class, used to create an object that handles HTTP requests
@RestController
: Spring4 added after the annotation, the original in the @Controller
return JSON needs @ResponseBody
to mate, if directly with the @RestController
substitution @Controller
will not need to configure @ResponseBody
, the default return JSON format.
@RequestMapping
: Configure URL Mappings
Below we try to use spring MVC to implement a set of restful APIs for user object operations, with comments detailing how HTTP requests are mapped in spring MVC, how to pass the parameters, and how to write unit tests.
* The RESTful API is specifically designed as follows:*
Request Type |
URL |
function Description |
GET |
/users |
Querying the user list |
POST |
/users |
Create a user |
GET |
/users/id |
Query a user by ID |
PUT |
/users/id |
Update a user by ID |
DELETE |
/users/id |
Delete a user by ID |
User Entity definition:
public class User { private Long ID; private String name; Private Integer age;
Implementing an interface for manipulating user objects
@RestController @RequestMapping (value= "/users")//by configuring this to make the following mappings under/users public class Usercontroller {//Create thread-safe m AP Static Map<long, user> users = Collections.synchronizedmap (new Hashmap<long, user> ()); @RequestMapping (value= "/", Method=requestmethod.get) public list<user> getuserlist () {//handle "/users/" ge T request, used to get a list of users//can also be passed @requestparam from the page parameters to query conditions or the transfer of page information list<user> r = new Arraylist<user> ( Users.values ()); return R; } @RequestMapping (value= "/", method=requestmethod.post) public String postuser (@ModelAttribute user user) { A POST request for "/users/" is used to create a user///In addition to the @modelattribute binding parameter, you can pass parameters users.put from the page by @requestparam (User.geti D (), user); Return "Success"; } @RequestMapping (value= "/{id}", method=requestmethod.get) public User getUser (@PathVariable Long ID) {// Get request to process "/users/{id}" to get user information for ID value in URL//ID in URL can be tied by @pathvariablereturn Users.get (ID) to the parameters of the function; } @RequestMapping (value= "/{id}", method=requestmethod.put) public String putuser (@PathVariable Long ID, @ModelAttr Ibute User user) {//Processing "/users/{id}" put request to update user information user U = users.get (id); U.setname (User.getname ()); U.setage (User.getage ()); Users.put (ID, u); Return "Success"; } @RequestMapping (value= "/{id}", method=requestmethod.delete) public String deleteuser (@PathVariable Long ID) { Delete request to process "/users/{id}" to delete user users.remove (ID); Return "Success"; } }
The following test case validation correctness is written for the controller, as follows. Of course, the browser plug-in can also be used to submit validation requests.
@RunWith (Springjunit4classrunner.class) @SpringApplicationConfiguration (classes = mockservletcontext.class) @ Webappconfiguration public class Applicationtests {private MOCKMVC mvc; @Before public void SetUp () throws Exception {MVC = Mockmvcbuilders.standalonesetup (New Usercontroller ()). Bui LD (); } @Test public void Testusercontroller () throws Exception {//test Usercontroller Requestbuilder req Uest = null; 1, get check the user list, should be empty request = Get ("/users/"); Mvc.perform (Request) Andexpect (status () IsOk ()). Andexpect (Content (). String (Equalto ("[]") )); 2. Post submits a user request = post ("/users/"). PARAM ("id", "1"). Param ("name", "Test Master" "). Param (" Age "," 20 "); Mvc.perform (Request) Andexpect (content (). String (Equalto ("Success")); 3, get get the user list, should have just inserted the data request = Get ("/users/"); MVc.perform (Request). Andexpect (Status (). IsOk ()). Andexpect (Content (). String (Equalto ("[{\" I D\ ": 1,\" name\ ": \" Test master \ ", \" age\ ": 20}]")); 4, put modifies the user request with id 1 = put ("/users/1"). Param ("name", "Test Ultimate Master"). Param ("Age "," 30 "); Mvc.perform (Request) Andexpect (content (). String (Equalto ("Success")); 5. Get a user request with id 1 = Get ("/USERS/1"); Mvc.perform (Request). Andexpect (Content (). String (Equalto ("{\" id\ ": 1,\" name\ ": \" test Ultimate master \ ", \" age\ ": 30}"))); 6. del Delete user request with id 1 = delete ("/USERS/1"); Mvc.perform (Request) Andexpect (content (). String (Equalto ("Success")); 7, get check the user list, should be empty request = Get ("/users/"); Mvc.perform (Request) Andexpect (status () IsOk ()). Andexpect (Content (). String (Equalto ("[]") )); } }
At this point, by introducing a Web module (without any other configuration), we can easily take advantage of the functionality of Spring MVC and complete the creation of a restful API for user objects and the writing of unit tests with very simple code. It also introduces some of the most commonly used core annotations in spring MVC:, @Controller
@RestController
RequestMapping
as well as some parameter binding annotations: @PathVariable
,, and @ModelAttribute
@RequestParam
so on.
Spring Boot Tutorial Full case
Spring Boot builds RESTful APIs and unit tests