springmvc4开发rest
Spring MVC 4 RESTFul Web Services CRUD Example+RestTemplate
Short & Quick introduction to REST
- To Create a resource : HTTP POST should be used
- To Retrieve a resource : HTTP GET should be used
- To Update a resource : HTTP PUT should be used
- To Delete a resource : HTTP DELETE should be used
- Spring Boot+AngularJS+Spring Data+Hibernate+MySQL CRUD App
- Spring Boot REST API Tutorial
- Spring Boot WAR deployment example
- Spring Boot Introduction + Hello World Example
- Spring 4 MVC+JPA2+Hibernate Many-to-many Example
- Secure Spring REST API using OAuth2
- AngularJS+Spring Security using Basic Authentication
- Secure Spring REST API using Basic Authentication
- Spring 4 Email Template Library Example
- Spring 4 Cache Tutorial with EhCache
- Spring 4 Email With Attachment Tutorial
- Spring 4 Email Integration Tutorial
- Spring MVC 4+JMS+ActiveMQ Integration Example
- Spring 4+JMS+ActiveMQ @JmsLister @EnableJms Example
- Spring 4+JMS+ActiveMQ Integration Example
- Spring MVC 4+Apache Tiles 3 Integration Example
- Spring MVC 4+Spring Security 4 + Hibernate Integration Example
- Spring MVC 4+AngularJS Example
- Spring MVC 4+AngularJS Routing with ngRoute Example
- Spring MVC 4+AngularJS Routing with UI-Router Example
- Spring MVC 4+Hibernate 4 Many-to-many JSP Example
- Spring MVC 4+Hibernate 4+MySQL+Maven integration example using annotations
- Spring MVC4 FileUpload-Download Hibernate+MySQL Example
- TestNG Mockito Integration Example Stubbing Void Methods
- Maven surefire plugin and TestNG Example
- Spring MVC 4 Form Validation and Resource Handling
Rest Based Controller
- GET request to /api/user/ returns a list of users
- GET request to /api/user/1 returns the user with ID 1
- POST request to /api/user/ with a user object as JSON creates a new user
- PUT request to /api/user/3 with a user object as JSON updates the user with ID 3
- DELETE request to /api/user/4 deletes the user with ID 4
- DELETE request to /api/user/ deletes all the users
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;@RestControllerpublic class HelloWorldRestController {@AutowiredUserService userService; //Service which will do all data retrieval/manipulation work//-------------------Retrieve All Users--------------------------------------------------------@RequestMapping(value = "/user/", method = RequestMethod.GET)public ResponseEntity<List<User>> listAllUsers() {List<User> users = userService.findAllUsers();if(users.isEmpty()){return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND}return new ResponseEntity<List<User>>(users, HttpStatus.OK);}//-------------------Retrieve Single User--------------------------------------------------------@RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)public ResponseEntity<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(@RequestBody 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 exist");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 --------------------------------------------------------@RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)public ResponseEntity<User> updateUser(@PathVariable("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(@PathVariable("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 --------------------------------------------------------@RequestMapping(value = "/user/", method = RequestMethod.DELETE)public ResponseEntity<User> deleteAllUsers() {System.out.println("Deleting All Users");userService.deleteAllUsers();return new ResponseEntity<User>(HttpStatus.NO_CONTENT);}}
Deploy and Test this API, let’s dig deeper into how this thing works
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.3</version></dependency>
Writing REST Client using RestTemplate
- HTTP GET : getForObject, getForEntity
- HTTP PUT : put(String url, Object request, String…urlVariables)
- HTTP DELETE : delete
- HTTP POST : postForLocation(String url, Object request, String… urlVariables), postForObject(String url, Object request, ClassresponseType, String… uriVariables)
- HTTP HEAD : headForHeaders(String url, String… urlVariables)
- HTTP OPTIONS : optionsForAllow(String url, String… urlVariables)
- HTTP PATCH and others : exchange execute
package com.websystique.springmvc;import java.net.URI;import java.util.LinkedHashMap;import java.util.List;import org.springframework.web.client.RestTemplate;import com.websystique.springmvc.model.User;public class SpringRestTestClient {public static final String REST_SERVICE_URI = "http://localhost:8080/Spring4MVCCRUDRestService";/* GET */@SuppressWarnings("unchecked")private static void listAllUsers(){System.out.println("Testing listAllUsers API-----------");RestTemplate restTemplate = new RestTemplate();List<LinkedHashMap<String, Object>> usersMap = restTemplate.getForObject(REST_SERVICE_URI+"/user/", List.class);if(usersMap!=null){for(LinkedHashMap<String, Object> map : usersMap){ System.out.println("User : id="+map.get("id")+", Name="+map.get("name")+", Age="+map.get("age")+", Salary="+map.get("salary"));; }}else{System.out.println("No user exist----------");}}/* GET */private static void getUser(){System.out.println("Testing getUser API----------");RestTemplate restTemplate = new RestTemplate(); User user = restTemplate.getForObject(REST_SERVICE_URI+"/user/1", User.class); System.out.println(user);}/* POST */ private static void createUser() {System.out.println("Testing create User API----------"); RestTemplate restTemplate = new RestTemplate(); User user = new User(0,"Sarah",51,134); URI uri = restTemplate.postForLocation(REST_SERVICE_URI+"/user/", user, User.class); System.out.println("Location : "+uri.toASCIIString()); } /* PUT */ private static void updateUser() {System.out.println("Testing update User API----------"); RestTemplate restTemplate = new RestTemplate(); User user = new User(1,"Tomy",33, 70000); restTemplate.put(REST_SERVICE_URI+"/user/1", user); System.out.println(user); } /* DELETE */ private static void deleteUser() {System.out.println("Testing delete User API----------"); RestTemplate restTemplate = new RestTemplate(); restTemplate.delete(REST_SERVICE_URI+"/user/3"); } /* DELETE */ private static void deleteAllUsers() {System.out.println("Testing all delete Users API----------"); RestTemplate restTemplate = new RestTemplate(); restTemplate.delete(REST_SERVICE_URI+"/user/"); } public static void main(String args[]){listAllUsers();getUser();createUser();listAllUsers();updateUser();listAllUsers();deleteUser();listAllUsers();deleteAllUsers();listAllUsers(); }}
Testing listAllUsers API-----------User : id=1, Name=Sam, Age=30, Salary=70000.0User : id=2, Name=Tom, Age=40, Salary=50000.0User : id=3, Name=Jerome, Age=45, Salary=30000.0User : id=4, Name=Silvia, Age=50, Salary=40000.0Testing getUser API----------User [id=1, name=Sam, age=30, salary=70000.0]Testing create User API----------Location : http://localhost:8080/Spring4MVCCRUDRestService/user/5Testing listAllUsers API-----------User : id=1, Name=Sam, Age=30, Salary=70000.0User : id=2, Name=Tom, Age=40, Salary=50000.0User : id=3, Name=Jerome, Age=45, Salary=30000.0User : id=4, Name=Silvia, Age=50, Salary=40000.0User : id=5, Name=Sarah, Age=51, Salary=134.0Testing update User API----------User [id=1, name=Tomy, age=33, salary=70000.0]Testing listAllUsers API-----------User : id=1, Name=Tomy, Age=33, Salary=70000.0User : id=2, Name=Tom, Age=40, Salary=50000.0User : id=3, Name=Jerome, Age=45, Salary=30000.0User : id=4, Name=Silvia, Age=50, Salary=40000.0User : id=5, Name=Sarah, Age=51, Salary=134.0Testing delete User API----------Testing listAllUsers API-----------User : id=1, Name=Tomy, Age=33, Salary=70000.0User : id=2, Name=Tom, Age=40, Salary=50000.0User : id=4, Name=Silvia, Age=50, Salary=40000.0User : id=5, Name=Sarah, Age=51, Salary=134.0Testing all delete Users API----------Testing listAllUsers API-----------No user exist----------
Complete Example
Project Structure
Declare project dependencies
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.websystique.springmvc</groupId> <artifactId>Spring4MVCCRUDRestService</artifactId> <packaging>war</packaging> <version>1.0.0</version> <name>Spring4MVCCRUDRestService Maven Webapp</name> <properties><springframework.version>4.2.0.RELEASE</springframework.version><jackson.version>2.5.3</jackson.version></properties><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${springframework.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>${springframework.version}</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version></dependency></dependencies><build><pluginManagement><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.2</version><configuration><source>1.7</source><target>1.7</target></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-war-plugin</artifactId><version>2.4</version><configuration><warSourceDirectory>src/main/webapp</warSourceDirectory><warName>Spring4MVCCRUDRestService</warName><failOnMissingWebXml>false</failOnMissingWebXml></configuration></plugin></plugins></pluginManagement><finalName>Spring4MVCCRUDRestService</finalName></build></project>
User Service
package com.websystique.springmvc.service;import java.util.List;import com.websystique.springmvc.model.User;public interface UserService {User findById(long id);User findByName(String name);void saveUser(User user);void updateUser(User user);void deleteUserById(long id);List<User> findAllUsers(); void deleteAllUsers();public boolean isUserExist(User user);}
package com.websystique.springmvc.service;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.concurrent.atomic.AtomicLong;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import com.websystique.springmvc.model.User;@Service("userService")@Transactionalpublic class UserServiceImpl implements UserService{private static final AtomicLong counter = new AtomicLong();private static List<User> users;static{users= populateDummyUsers();}public List<User> findAllUsers() {return users;}public User findById(long id) {for(User user : users){if(user.getId() == id){return user;}}return null;}public User findByName(String name) {for(User user : users){if(user.getName().equalsIgnoreCase(name)){return user;}}return null;}public void saveUser(User user) {user.setId(counter.incrementAndGet());users.add(user);}public void updateUser(User user) {int index = users.indexOf(user);users.set(index, user);}public void deleteUserById(long id) {for (Iterator<User> iterator = users.iterator(); iterator.hasNext(); ) { User user = iterator.next(); if (user.getId() == id) { iterator.remove(); }}}public boolean isUserExist(User user) {return findByName(user.getName())!=null;}private static List<User> populateDummyUsers(){List<User> users = new ArrayList<User>();users.add(new User(counter.incrementAndGet(),"Sam",30, 70000));users.add(new User(counter.incrementAndGet(),"Tom",40, 50000));users.add(new User(counter.incrementAndGet(),"Jerome",45, 30000));users.add(new User(counter.incrementAndGet(),"Silvia",50, 40000));return users;}public void deleteAllUsers() {users.clear();}}
Model class
package com.websystique.springmvc.model;public class User {private long id;private String name;private int age;private double salary;public User(){id=0;}public User(long id, String name, int age, double salary){this.id = id;this.name = name;this.age = age;this.salary = salary;}public long getId() {return id;}public void setId(long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public double getSalary() {return salary;}public void setSalary(double salary) {this.salary = salary;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + (int) (id ^ (id >>> 32));return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;User other = (User) obj;if (id != other.id)return false;return true;}@Overridepublic String toString() {return "User [id=" + id + ", name=" + name + ", age=" + age+ ", salary=" + salary + "]";}}
Configuration class
package com.websystique.springmvc.configuration;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.EnableWebMvc;@Configuration@EnableWebMvc@ComponentScan(basePackages = "com.websystique.springmvc")public class HelloWorldConfiguration {}
Initialization Class
package com.websystique.springmvc.configuration;import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;public class HelloWorldInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[] { HelloWorldConfiguration.class }; } @Override protected Class<?>[] getServletConfigClasses() { return null; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } }
Adding CORS support to your REST API
package com.websystique.springmvc.configuration;import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletResponse;public class CORSFilter implements Filter {public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {System.out.println("Filtering on...........................................................");HttpServletResponse response = (HttpServletResponse) res;response.setHeader("Access-Control-Allow-Origin", "*");response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");response.setHeader("Access-Control-Max-Age", "3600");response.setHeader("Access-Control-Allow-Headers", "x-requested-with");chain.doFilter(req, res);}public void init(FilterConfig filterConfig) {}public void destroy() {}}
package com.websystique.springmvc.configuration;import javax.servlet.Filter;import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;public class HelloWorldInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[] { HelloWorldConfiguration.class }; } @Override protected Class<?>[] getServletConfigClasses() { return null; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } @Override protected Filter[] getServletFilters() { Filter [] singleton = { new CORSFilter()}; return singleton; } }
Download Source Code
Related posts:
- Secure Spring REST API using Basic Authentication
- Spring 4 MVC+AngularJS CRUD Example using $http service
- Spring Boot Rest API Example
- Spring 4 MVC+AngularJS CRUD Application using ngResource
Post navigation
- Yueqin Lin Fuller
Hi, LOVE this tutorial! When you delete a user, you use ResponseEntity as the return type, what’s the differences between ResponseEntity and ResponseEntity here? I tried both and they all work.
- Khan
Hi
Great example, In this example you are using this method (“populateDummyUsers()”) to load data, it’s fine.
I want to know, how to communicate with mysql database for CRUD. - M.Nouman Shahzad
I have been trying out this tutorial and as most of the people have reported, I too am getting an 404 error. I don’t want to run the project inside an IDE but want to compile a WAR file and deploy it on a Tomcat Server. I am able to compile a WAR file but kindly walk me through the steps to deploy it on Tomcat.
For now, it gives the following error when I try to deploy the WAR on Tomcat:
FAIL – Application at context path /Spring4MVCCRUDRestService could not be started
FAIL – Encountered exception org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/Spring4MVCCRUDRestService]] - Ganesh Chaudhari
i have imported this project as it is ..but after running it I always get a Error 404..in responce
- Pingback: Spring Boot Rest API Example - WebSystique()
- Pingback: REST and Java 8 Blogs | Servlets and Singletons()
- Deepak Ray Chowdhury
Hi websystique
http://localhost:8088/Mobitino/oauth/token?grant_type=password&username=bill&password=abc123
i imported the source and tried runnig it to my local but getting an error 404
- Deepak Ray Chowdhury
Hi Can i configure servlet.xml and web.xml file becouse i can not use view resolver.so please help me - Mahesh Thorat
Hi
I am getting this error while fetching data against id
request -http://localhost:8080/Spring4MVCCRUDRestService/user/1
Error-
Fetching User with id 1
Oct 22, 2016 1:11:58 PM org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver logException
WARNING: Handler execution resulted in exception: Could not find acceptable representation
- Andrey Stepanov
Dear site owner,
I’m very thankful to you for the fantastic set of course and your generosity in sharing your experience.
May I ask you two questions regarding this particular article? May be you could answer …
First, I got curious about specifics controller methods for POST and PUT.
Both of them have (User) user as one of the arguments.
And in both case we do not transmit id as part of the request body (in case of PUT we get it from URI parameter though)
How does it come that argument of type User is constructed as RequestBody without unique identifier?
Second question is a bit more practical,
when I run POST request in POSTMAN I do get ‘Error 415 Unsupported Media Type’ server response
despite that:
a) I have specified JSON as data type from the drop-down in POSTMAN
b) I added ‘consumes = MediaType.APPLICATION_JSON_VALUE’ to the @RequestMapping for the controller POST method
sure we have jackson-databind library on the classpath
- only adding Content-Type header in POSTMAN with value application/json solved the problem
Does it mean that the server … not always capable to read the content type from the code?
Or am I doing something wrong?
Again, let me wish you all the best, and let me hope that my questions will strike your interest and desire to reply
- Nilesh Za
Thanks for this great tutorial. I was trying to deploy this code with the help IntelliJ and Jboss 6.4 , but whenever i hit the request ,am getting 404. is there any change i need to do. Could you please help me.
- Pingback: Spring MVC 4 RESTFul Web Services | ALİ ÖZDEMİR()
- Stone Patterson
will this work in IntelliJ
- Ismael Ezequiel
Why I’m receiving that error:
java.lang.NullPointerException: null
??
- Gyver
I am very new in spring mvc, can i ask if what are the things i need to set up first in my eclipseso that i can create spring mvc application, specifically a crud application? Is there someone who can guide me? thank you!
- Naina R
plz help
and you have done a great job…by making this site…helps a lot
- Gil Shapir
1) Trying to deploy the project directly from Eclipse Neon, by right click on it and choose run on server I’m getting: this selection cannot run on any server.
I do have Tomcat 8 installed.
As there is no main method defined not so sure if/how this should work
2) also getting a message:
Cannot change version of project facet Dynamic Web Module to 3.1. Spring4MVCCRUDRestServiceline 1Maven Java EE Configuration Problem
Any help will be appreciated - Srinivasa Praneeth
Hi,
Thank you very much… it is an Awesome tutorial it helped me a lot. - Chriso Lopez C
Hi, I downloaded your project and trying to run it from Eclipse on Glassfish, I keep getting a 404 Not found.
- SG
Hi, thanks for this tutorial. This is really wonderful. I have a question more to do with the design part of the components. For the registration page, I mean the actual html/jsp client we need to have a non-rest controller ? I don’t want to call the JSP/HTML and would like to go through Springs MVC? what will be the best way to handle this.
- hzms
hi, may i know what is the difference between using spring with restful web services and using spring without it?
- ashish
hi very nice tutorial.. but so many new things… How can I integrate this module with mybatis..?
- Maun Bisma
Hi, nice tutorial,,,
I already try your tutorial http://websystique.com/springmvc/spring-mvc-4-and-spring-security-4-integration-example/,,,,but when I add the restfull controller like this tutorial, i get error 405 about POST request not support,,,, can you give me advice what wrong?
Thank you,,,
- sonia rao
Hi,I have tried this example …its asking for Username And password in postman…can anyone help with this??
- Daniel
Hi, how does it come that I did not declare this jackson dependency and it still returns a JSON with the header Content-Type →application/json;charset=UTF-8 …. I checked all the jars in my project and it does NOT seem like some other dependency transitively brought it.. any idea? Great post by the way, thanks!
ANSWER: My bad, actually spring-webmvc does bring that dependency - Girish Balodi
Ultimate guid step by step… - Pingback: Ruksis780()
- http://hendisantika.wordpress.com Hendi Santika
Hi. I’ve been enjoying your tutorials, they’re great
How ever I want to know the way you handle those api in form / web page. So that I can continue learning your nice tutorial more understand implementations.
- Kali Prasad Padhy
Hi,
Can you tell me why we use AbstractAnnotationConfigDispatcherServletInitializer to intalize HelloWorldInitializer class.
Thanks
- greo
i get error 404 in netbeans and eclipse, i try server tomcat in eclipse and server tomcat and glassfish in netbeans, how to fix that ?
- Sof Ham
Hi I’m getting “Etat HTTP 404 – /Spring4MVCCRUDRestService/user/” when calling http://localhost:8282/Spring4MVCCRUDRestService/user/
please note that tomcat is correctly installed.
- Patrick Ndukwe
Today I have been given a new task and will like to share. I have two websites written in Spring MVC that does registration and payment processing. On beginning the registration process on the first portal, when it comes to payment the user is thereby directed to the second portal to complete the payment and thereby returns the person back to the first website. The registration details entered by the user is required to be transferred from the first portal to the second portal in other to generate the required payment processing. My question is, please what are the steps to channel my efforts towards using JSON to transfer data from one portal to another considering data security using Spring MVC. Please can you help me with ideas… - Michael Dmitriev
Thank you very much! helped me a lot - Abhijit Marne Deshmukh
thank you so much for providing this great example. it is really helpful.
- Binh Thanh Nguyen
Thanks, nice tips. - sanji
Hi, very nice tutorial I learned so much from it
When creating a user via Postman I get an HTTP 201 Created (which is obvious) instead of HTTP 200 OK like in your examples (less obvious…) is there any explanations about that ?
Second, I’m using Spring Tool Suite (latest version) I wanted to deploy the app with spring-boot (have all the necessary dependencies in maven) so when I type the command “mvn spring-boot:run” I get this output http://pastebin.com/AAYnCCnN server returns 404 when I type http://localhost:8080/stbwebservice/user/ in the browser on the other hand when I deploy it as a war and run it on a standalone tomcat8 it works… How can I solve that ?
Thanks again. - Rupali Solaskar
Hi. I am running same code on my laptop and also following every step of setting tomcat with eclipse but i got an error -”Server Tomcat v8.0 Server at localhost failed to start.” i am not getting that because of what error comes. after every step performing when i tried to start tomcat at that time this error occurs.
please help me.
Thanks - Gísli Leifsson
Hi there and thanks for a great series of tutorials! Been following quite a few.
For those of you who are dealing with a 404 error, the answer might be extremely simple.
In the controller class, the request mapping for listAllUsers looks like this:
@RequestMapping(value = “/user/”, method = RequestMethod.GET)
Notice that it’s “/user/” and not “/user”. This means that if you end the URL with “/user”, it gives you a 404 error. If you end it with “/user/” however, it will work. At least it behaves like this in Tomcat 8.
Simply change the request mapping to “/user” and it will work as expected.
- Rupali Solaskar
Hi I am using your above code but it is not executing. I am getting 404 error, I am running it in Eclipse -Luna can any one help me how to remove error.
- Muhammed Abdul
Hello, I have also added Spring Security basic authentication as mentioned in your previous tutorials,
But i am not able to access it if i provide a header with authorization and Basic
Can you help? Do i need to change the securityclass ( i am using the same security class as in ur previous tutorials without any changes) - wang
A good example for study spring rest
Thanks a lot! - lab
I am using netbean, and deploying in tomcat 8. However i get error 404 – not found accessing resources. How I can solve it?
- Mamuka Arabuli
I was unable to produce xml . simple call alwaysreturns json , I added @XmlRootElement but no result :
406 Not Acceptable
- javalearner
Thanks for sharing this project .. I have downloaded the project and then did the Maven build and then Maven Install and then run on tomcat 8.0 but its giving me 404 error . Please help
- Faisal Arkan
Thanks !! it’s so helpful,, - swapyish
Great tutorial indeed. Very useful and good explaination. - dgoyal
Hi
I ran project zip shared by you successfully. I then tried to create my own project, following all inputs given by you. I get a blank HTTP 200 OK response when I try to list all users. Somehow application is not passing controls to methods specified in controller class. Any suggestions?
I see that mappings happened correctly
——————————————-
Feb 03, 2016 1:11:02 PM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping register
INFO: Mapped “{[/user/],methods=[POST]}” onto public org.springframework.http.ResponseEntity com.intelligrated.springmvc.controller.HelloWorldRestController.createUser(com.intelligrated.springmvc.model.User,org.springframework.web.util.UriComponentsBuilder)
Feb 03, 2016 1:11:02 PM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping register
INFO: Mapped “{[/user1/],methods=[GET]}” onto public org.springframework.http.ResponseEntity<java.util.List> com.intelligrated.springmvc.controller.HelloWorldRestController.listAllUsers()
Feb 03, 2016 1:11:02 PM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping register
INFO: Mapped “{[/user/{id}],methods=[GET],produces=[application/json]}” onto public org.springframework.http.ResponseEntity com.intelligrated.springmvc.controller.HelloWorldRestController.getUser(long)
Feb 03, 2016 1:11:02 PM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping register
INFO: Mapped “{[/user/{id}],methods=[PUT]}” onto public org.springframework.http.ResponseEntity com.intelligrated.springmvc.controller.HelloWorldRestController.updateUser(long,com.intelligrated.springmvc.model.User)
Feb 03, 2016 1:11:02 PM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping register
INFO: Mapped “{[/user/{id}],methods=[DELETE]}” onto public org.springframework.http.ResponseEntity com.intelligrated.springmvc.controller.HelloWorldRestController.deleteUser(long)
Feb 03, 2016 1:11:02 PM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping register
INFO: Mapped “{[/user/],methods=[DELETE]}” onto public org.springframework.http.ResponseEntity com.intelligrated.springmvc.controller.HelloWorldRestController.deleteAllUsers()
Feb 03, 2016 1:11:02 PM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
—————————————————–
One difference I notice between logs of application provided by you and created by me is that log for your project shows following and my project log does not have these lines.
—
Feb 03, 2016 1:15:33 PM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/Spring4MVCCRUDRestService/] in DispatcherServlet with name ‘dispatcher’
—
Any guidance will be appreciated. (I am on eclipse, JDK1.8, Tomcat, Windows 7)
- Tej
Superb blog and great example. I downloaded, did maven build and deploy on Tomcat 7 and even 8 but when visit http://localhost:8080/Spring4MVCCRUDRestService/user/gets Bad Format???
I am using intelliJ idea ..but no errors while deploying too !! - Pingback: Spring 4 MVC+AngularJS Example - WebSystique()
- Pingback: Spring 4 MVC+AngularJS CRUD Application using ngResource - WebSystique()
- Anurag P
Hello All,
I tried this on tomcat 7 , it was working fine …,
I have tried running it on jboss eap 6.3.0 and i am getting 404 Error!!!!!
Did anyone else tried running it on JBOSS EAP 6.3.0 ??? - Balakrishna Pedada
Hello,
I am trying to write an ajax call for form submission using this example, my question is did restcontroller only accepts json content type and json data format for processing the post request?
I am trying to do an ajax call using form data object with the content type application/json, but I am getting 400 bad request error.
Will @requestbody won’t take care of auto converting formdata to json??
Do we need to always call a rest controller with json data and content type to JSON?
Please correct me If I misunderstood something.
- Vikash Kumar
hello sir,
When i have deployed project on weblogic12 c then generates following exception.
please say to me how to remove it?.. - Vikash Kumar
May u provide me its war file????????
- Vikash Kumar
Hello admin may i know about web.xml. There is no xml why???????
- Максим Микрюков
Hello. Thanks for interesting blog. I have quastion. How bind org.joda dateTime type from JSON String.
- Pingback: Modern web: Spring 4 MVC & AngularJS Example | LearncoolTech()
- Pingback: AngularJS $http service example-server communication - WebSystique()
- Clebio Vieira
Hello. I´m from Brasil. Thanks for sharing your time !!! - nmpg
Hi. I’ve been enjoying your tutorials, they’re great
However, I’m having an issue with this one. I always get a Error 404 – Not Found when accessing
http://localhost:7001/Spring4MVCCRUDRestService/user/
I using your code as-is. I’m using Weblogic if that matters btw..
Any idea what I may doing wrong? Or how I can debug this?
- http://junjunguo.com/ guojunjun
Thanks for the grate tutorial - http://junjunguo.com/ guojunjun
hei, websystique
Thanks for another great tutorial
in the user class there are
“`
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id ^ (id >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id != other.id)
return false;
return true;
}
“`
can you explain what is the purpose of this to methods, what are overrided ?
Best Greetings - badr benabbou
Hello WebSystique , please i have this error message , i need a help thanks u
- Guilherme Marquesini Reis Ribe
- When do you call to create the user:
“URI uri = restTemplate.postForLocation(REST_SERVICE_URI+”/user/”, user, User.class);”
The method convert a object to JSON ? Where do you set this? Or send other type?
- droidark ☭
Thanks for the tutorial, it’s very helpful for me.
springmvc4开发rest的更多相关文章
- 从零开始学JAVA(09)-使用SpringMVC4 + Mybatis + MySql 例子(注解方式开发)
项目需要,继续学习springmvc,这里加入Mybatis对数据库的访问,并写下一个简单的例子便于以后学习,希望对看的人有帮助.上一篇被移出博客主页,这一篇努力排版整齐,更原创,希望不要再被移出主页 ...
- Spring-MVC4 + JPA2 + MySql-5.5 + SLF4J + JBoss WildFly-8.1开发环境的搭建
面试被问Spring4,它的目的是把过去Spring3所有升级项目Spring4.现在将记录在此环境搭建过程. 第一次使用Maven Archetype创建一个项目框架,运行以下命令: mvn arc ...
- mybatis_开发篇
一.使用mybatis的动态代理方式开发 需求:这里以crm系统中分页条件查询所有的客户信息的功能为例? 1.创建工程 2.引入所需的jar包 3.引入日志文件.数据库连接参数的配置文件等 4.创建m ...
- 基于Spring4+SpringMVC4+Mybatis3+Hibernate4+Junit4框架构建高性能企业级的部标GPS监控平台
开发企业级的部标GPS监控平台,投入的开发力量很大,开发周期也很长,选择主流的开发语言以及成熟的开源技术框架来构建基础平台,是最恰当不过的事情,在设计之初就避免掉了技术选型的风险,避免以后在开发过程中 ...
- GPS部标平台的架构设计(三) 基于struts+spring+hibernate+ibatis+quartz+mina框架开发GPS平台
注意,此版本是2014年研发的基于Spring2.5和Struts2的版本,此版本的源码仍然销售,但已不再提供源码升级的服务,因为目前我们开发的主流新版本是2015-2016年近一年推出的基于spri ...
- 基于Java Mina框架的部标808服务器设计和开发
在开发部标GPS平台中,部标808GPS服务器是系统的核心关键,决定了部标平台的稳定性和行那个.Linux服务器是首选,为了跨平台,开发语言选择Java自不待言. 我们为客户开发的部标服务器基于Min ...
- spring mvc4.1.6 + spring4.1.6 + hibernate4.3.11 + mysql5.5.25 开发环境搭建及相关说明
一.准备工作 开始之前,先参考上一篇: struts2.3.24 + spring4.1.6 + hibernate4.3.11 + mysql5.5.25 开发环境搭建及相关说明 struts2.3 ...
- SpringMVC4+thymeleaf3的一个简单实例(篇一:基本环境)
首语:用SpringMVC和thymeleaf实现一个简单的应用,包括基本环境搭建,SpringMVC4和thymeleaf3的整合,页面参数的获取,页面参数验证,以及用MySQL保存数据.我会把步骤 ...
- springmvc4+hibernate4分页查询功能
Springmvc+hibernate成为现在很多人用的框架整合,最近自己也在学习摸索,由于我们在开发项目中很多项目都用到列表分页功能,在此参考网上一些资料,以springmvc4+hibnerate ...
随机推荐
- jQuary学习の二の语法
jQuery 语法是通过选取 HTML 元素,并对选取的元素执行某些操作.基础语法: $(selector).action() 美元符号定义 jQuery 选择符(selector)"查询& ...
- 机器学习之类别不平衡问题 (2) —— ROC和PR曲线
机器学习之类别不平衡问题 (1) -- 各种评估指标 机器学习之类别不平衡问题 (2) -- ROC和PR曲线 完整代码 ROC曲线和PR(Precision - Recall)曲线皆为类别不平衡问题 ...
- 使用证书创建request请求
之前写过的程序,都是普通http request. 这是第一次使用,记录下. private static X509Certificate2 GetCert(string certId,StoreLo ...
- Online Judge(OJ)搭建——3、MVC架构
Model Model 层主要包含数据的类,这些数据一般是现实中的实体,所以,Model 层中类的定义常常和数据库 DDL 中的 create 语句类似. 通常数据库的表和类是一对一的关系,但是有的时 ...
- 微信APP长按图片禁止保存到本地
项目遇到一个问题,在web页面中,禁止长按图片保存, 使用css属性: img { pointer-events: none; } 或者 img { -webkit-user-select: no ...
- ava集合---HashSet的源码分析
一.HasnSet概述 Hashset实现set接口,由哈希表(实际上是一个HashMap实例)支持.它不保证set的迭代顺序.特别是它不保证该顺序恒久不变.此类允许使用Null元素 一.HasnSe ...
- kvm之三:本地安装虚拟机
1.格式化新添加的磁盘 [root@kvm ~ ::]#fdisk /dev/sdb Command (m for help): n //新建分区 Command action e extended ...
- JS获得一个对象的所有属性和方法
function displayProp(obj){ var names=""; for(var name in obj){ names+=name+": "+ ...
- C#中的String类
一.String类的方法 1. Trim():清除字符串两端的空格 2. ToLower():将字符串转换为小写 3. Equals():比较两个字符串的值,bool 4. IndexOf(value ...
- 关于yaml语言
yaml语言广泛用于书写配置文件. 主要特点如下: 1.使用缩进表示层级关系,缩进使用空格键(非Tab键) 2.缩进的空格数目不要求,只要相同层级的元素左侧对其即可 3.#之后的内容为注释 4.yam ...