Spring MVC 4 restful Web Services crud example (with source) This is restful, super Classic.

Source: Internet
Author: User
Tags bind file upload http 200 http post http request json representational state transfer web services

"Other tutorials in this series are being translated, click on Category: Spring 4 mvc for viewing. Source download address at the end of the article. 】

"Translation by clearly like the month QQ 605283073" original address: http://websystique.com/springmvc/ spring-mvc-4-restful-web-services-crud-example-resttemplate/

Previous: Spring 4 MVC @RestController Annotations Implementation Rest Service Next: Spring MVC 4 File upload download Hibernate+mysql example (with source)

This article is very good, recommend everybody take a good look, many people understand the restful wrong

In this article we will implement the CRUD Restful WebService using spring MVC 4 and write a REST client by Resttemplate to define these services. We can also test these services through some external clients.


Short & Quick introduction to rest Rest represents the representational state Transfer (representation transition).

It is a framework that can be used to design Web services and can be called by different clients.

The core idea is to implement calls using a simple HTTP protocol rather than a responsible mechanism such as CORBA, RPC, or soap.


In the rest Foundation design, the resources are manipulated using the following verbs.

Create resource: Use HTTP POST to get resources: Use HTTP GET to update resources: Use HTTP PUT to delete resources: Using HTTP Delete also means that you, as a rest service developer or customer, should follow the above criteria.


Although there is no restriction on the types that must be returned, rest of the Web services-based general returns JSON or XML as a response.


The client can specify (using the HTTP Accept header) The type of resource they want, and the server returns the required resources.

Indicates the content-type of the resource. If you want a detailed understanding of the restful can refer here: StackOverflow link


Rest-based controller (controllers)

Our REST api:get Way request/api/user/Returns the user list GET method request/API/USER/1 Returns a user with ID 1 POST method request/api/user/Create a new users object by using the JSON parameter of the user object PU The T-mode request/API/USER/3 Update ID 3 sends a JSON-formatted user Object Delete mode request/API/USER/4 Delete the user object with ID 4, delete method request/api/user/Delete all user

Package Com.websystique.springmvc.controller;
 
Import java.util.List;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.http.HttpHeaders;
Import Org.springframework.http.HttpStatus;
Import Org.springframework.http.MediaType;
Import org.springframework.http.ResponseEntity;
Import org.springframework.web.bind.annotation.PathVariable;
Import Org.springframework.web.bind.annotation.RequestBody;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.bind.annotation.RequestMethod;
Import Org.springframework.web.bind.annotation.RestController;
 
Import Org.springframework.web.util.UriComponentsBuilder;
Import Com.websystique.springmvc.model.User;
 
Import Com.websystique.springmvc.service.UserService;  @RestController public class Helloworldrestcontroller {@Autowired userservice userservice; Service which would do all data retrieval/manipulation work//-------------------Retrieve all UserS--------------------------------------------------------@RequestMapping (value = "/user/", method = Requestmeth Od. GET) public responseentity<list<user>> listallusers () {list<user> users = Userservice.finda
        Llusers (); if (Users.isempty ()) {return new responseentity<list<user>> (httpstatus.no_content);//you many decid E to return Httpstatus.not_found} return new Responseentity<list<user>> (Users, Httpstatus.ok)
    ; }//-------------------Retrieve single User--------------------------------------------------------@Req Uestmapping (value = "/user/{id}", method = Requestmethod.get, produces = mediatype.application_json_value) public Resp
        Onseentity<user> GetUser (@PathVariable ("id") long ID) {SYSTEM.OUT.PRINTLN ("Fetching User with ID" + ID);
        User user = Userservice.findbyid (ID); if (user = = null) {System.out.println ("User with ID"+ ID +" not found ");
        return new responseentity<user> (Httpstatus.not_found);
    } return new Responseentity<user> (User, Httpstatus.ok); }//-------------------Create a User--------------------------------------------------------@ Requestmapping (value = "/user/", method = requestmethod.post) public responseentity<void> CreateUser (@RequestBod
 
        Y user User, Uricomponentsbuilder ucbuilder) {System.out.println ("Creating User" + user.getname ()); if (userservice.isuserexist (user)) {System.out.println ("A User with Name" + user.getname () + "already exi
            St ");
        return new responseentity<void> (httpstatus.conflict);
 
        } userservice.saveuser (user);
        Httpheaders headers = new Httpheaders ();
        Headers.setlocation (Ucbuilder.path ("/user/{id}"). Buildandexpand (User.getid ()). Touri ()); return new responseentity<void> (headers, httpstATUs.
    CREATED); }//-------------------Update a User--------------------------------------------------------@Requ Estmapping (value = "/user/{id}", method = requestmethod.put) public responseentity<user> UpdateUser (@PathVariabl
         
        E ("id") long ID, @RequestBody user user) {System.out.println ("Updating user" + ID);
         
        User CurrentUser = Userservice.findbyid (ID);
            if (currentuser==null) {System.out.println ("User with ID" + ID + "not found");
        return new responseentity<user> (Httpstatus.not_found);
        } currentuser.setname (User.getname ());
        Currentuser.setage (User.getage ());
         
        Currentuser.setsalary (User.getsalary ());
        Userservice.updateuser (CurrentUser);
    return new Responseentity<user> (CurrentUser, Httpstatus.ok); }//-------------------Delete a User--------------------------------------------------------@Requestmapping (value = "/user/{id}", method = requestmethod.delete) public responseentity<user> deleteuser (@Path
 
        Variable ("id") long ID) {SYSTEM.OUT.PRINTLN ("Fetching & Deleting User with ID" + ID);
        User user = Userservice.findbyid (ID); if (user = = null) {System.out.println ("unable to delete.
            User with ID ' + ID + ' not found ');
        return new responseentity<user> (Httpstatus.not_found);
        } Userservice.deleteuserbyid (ID);
    return new responseentity<user> (httpstatus.no_content); }//-------------------Delete all Users--------------------------------------------------------@R
        Equestmapping (value = "/user/", method = requestmethod.delete) public responseentity<user> deleteallusers () {
 
        System.out.println ("Deleting all Users");
        Userservice.deleteallusers ();
    return new responseentity<user> (httpstatus.no_content); }
 
}

Detailed

@RestController: First we use new annotations @RestController annotations for spring 4.

This note avoids adding @responsebody annotations to each method. That is to say, @restcontroller himself put on @ResponseBody annotations, to see as

A combination of @Controller and @ResponseBody.

@RequestBody: If the method parameter is @RequestBody annotated, spring binds the HTTP request body to that parameter. If you do that, spring will use HTTP Message converters to convert the HTTP request body to a domain object based on the Accept or content-type header in the request (privately).

@ResponseBody: If the method adds a @responsebody annotation, spring returns the value to the response body. If you do this, spring will convert the domain object to the response body using HTTP Message converters, based on the Content-type header (privately) in the request.

Responseentity is a real data. It represents the entire HTTP response (response). The advantage of it is that you can control any object to put inside it.

You can specify the status code, header information, and response body. It contains the information you want to build HTTP Response.

@PathVariable This annotation means that a method parameter should be bound to a URL template variable [in one of ' {} ']

In general you, to implement rest API in Spring 4 need to understand @restcontroller, @RequestBody, responseentity and @PathVariable these annotations. In addition, spring provides some support Class helps you implement something that you can customize.

MediaType: With @RequestMapping annotations, you can specify, mediatype to produce or consume with special controller methods.
Publish and test this API Http://localhost:8080/Spring4MVCCRUDRestService.
To test this API, I will use postman, the external client, and then we will write our own client. 1. Get All Users

Open the Postman tool, select the request type is get, indicate the URI

Note: We do not specify any HTTP headers. Click Send to receive a list of all users


Also pay attention to the HTTP 200 response.

You may wonder why this response is sent through a JSON string, which is explained in the Content-type header in the response. Because we added Jackson.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId> jackson-databind</artifactid>
    <version>2.5.3</version>
</dependency

Because spring finds the library in the classpath, it calls the built-in Mappingjackson2httpmessageconverter converter to convert the response (the collection of objects) to the JSON format. The benefit of spring's built-in converters is that in most cases the conversion can be done simply by placing the library in the classpath. Of course, sometimes we also need
Use our API. For example, if we provide XML format as well, we need to add JAXB annotations to the user class.
2. Get a single user

Get mode Specifies/USER/1

Now try sending a GET request with an error ID that will receive an HTTP 404

3. Create a User
Select the Post method, indicate uri/user/indicates postman Body tab, select Application/json type
You should note that postman automatically adds Content-type header information.


Remember: The Accept header contains the types that the client can give recognition to. The Content-type header represents the actual type of data.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.