Overview
In this tutorial, we show you how to create a simple Restful web services CRUD example in java using Spring MVC return json. We'll building a spring restful web services annotations using eclipse and tomcat step by step.Follow the steps mentioned below to develop Restful web services.
Watch Tutorial
MySQL database settings
Execute the following MySQL script in order to create a database named jack_rutorial_demo with a table named users.CREATE DATABASE `jack_rutorial_demo`; CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `firstname` varchar(45) NOT NULL DEFAULT '', `lastname` varchar(100) NOT NULL DEFAULT '', `address` varchar(100) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
Project Structure
The following screenshot shows final structure of the project.Create Spring Project in Eclipse
- Launch Eclipse IDE.
- Go to File-> New-> Others... Select Maven Project under Maven category then click Next.
- In New Maven Project wizard, select "Create a simpel project(skip archetype selection)" and click on Next
- In next wizard, type "com.jackrutorial" in the "Group ID:" field
- Type "SpringRESTFulExample" in the "Artifact Id:" field
- Packaging -> War
- Click Finish.
Maven Dependencies
We will update pom.xml file to add the required dependencies for the following 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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jackrutorial</groupId> <artifactId>SpringRESTFulExample</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.0.RELEASE</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.0.RELEASE</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warSourceDirectory>src/main/webapp</warSourceDirectory> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </pluginManagement> </build> </project>
Spring Application Configuration
To configure Spring web MVC framework, we create class WebConfig, class WebInitializer in src folder with package name com.jackrutorial.config and write the following code in it.WebConfig.java
package com.jackrutorial.config; import javax.naming.NamingException; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jndi.JndiTemplate; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.jackrutorial" }) public class WebConfig extends WebMvcConfigurerAdapter { @Autowired DataSource dataSource; @Bean public NamedParameterJdbcTemplate geNamedParameterJdbcTemplate(){ return new NamedParameterJdbcTemplate(dataSource); } @Bean public DataSource getDataSource() throws NamingException{ JndiTemplate jndiTemplate = new JndiTemplate(); DataSource dataSource = (DataSource) jndiTemplate.lookup("java:comp/env/jdbc/springmvc"); return dataSource; } }
WebInitializer.java
package com.jackrutorial.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class[] getRootConfigClasses() { return new Class[] { WebConfig.class}; } @Override protected Class[] getServletConfigClasses() { return null; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } }
Creating Model Layer
Create a User class under com.jackrutorial.model and write the following code in it.User.java
package com.jackrutorial.model; public class User { private Integer id; private String firstname; private String lastname; private String address; public User() { super(); } public User(Integer id) { super(); this.id = id; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
Database Access Object Configuration
Create a UserDao interface under com.jackrutorial.dao and write the following code in it.UserDao.java
package com.jackrutorial.dao; import java.util.List; import com.jackrutorial.model.User; public interface UserDao { public ListlistAllUser(); public void addUser(User user); public void updateUser(User user); public void delete(User user); public User findUserById(User user); }
Create a UserDaoImpl class implements UserDao Interface under com.jackrutorial.dao package and write the following code in it.
UserDaoImpl.java
package com.jackrutorial.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.stereotype.Repository; import com.jackrutorial.model.User; @Repository public class UserDaoImpl implements UserDao { NamedParameterJdbcTemplate namedParameterJdbcTemplate; @Autowired public void setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate namedParameterJdbcTemplate) { this.namedParameterJdbcTemplate = namedParameterJdbcTemplate; } public ListlistAllUser() { List list = new ArrayList (); String sql = "SELECT id, firstname, lastname, address FROM users"; list = namedParameterJdbcTemplate.query(sql, getSqlParameterByModel(null), new UserMapper()); return list; } private SqlParameterSource getSqlParameterByModel(User user){ MapSqlParameterSource parameterSource = new MapSqlParameterSource(); if(user != null){ parameterSource.addValue("id", user.getId()); parameterSource.addValue("firstname", user.getFirstname()); parameterSource.addValue("lastname", user.getLastname()); parameterSource.addValue("address", user.getAddress()); } return parameterSource; } private static final class UserMapper implements RowMapper { public User mapRow(ResultSet rs, int rowNum) throws SQLException { User user = new User(); user.setId(rs.getInt("id")); user.setFirstname(rs.getString("firstname")); user.setLastname(rs.getString("lastname")); user.setAddress(rs.getString("address")); return user; } } public void addUser(User user) { String sql = "INSERT INTO users(firstname, lastname, address) VALUES(:firstname, :lastname, :address)"; namedParameterJdbcTemplate.update(sql, getSqlParameterByModel(user)); } public void updateUser(User user) { String sql = "UPDATE users SET firstname=:firstname, lastname=:lastname, address=:address WHERE id =:id"; namedParameterJdbcTemplate.update(sql, getSqlParameterByModel(user)); } public void delete(User user) { String sql = "DELETE FROM users WHERE id=:id"; namedParameterJdbcTemplate.update(sql, getSqlParameterByModel(user)); } public User findUserById(User user) { String sql = "SELECT * FROM users WHERE id =:id"; return namedParameterJdbcTemplate.queryForObject(sql, getSqlParameterByModel(user), new UserMapper()); } }
User Service Layer Configuration
Create a UserService interface under com.jackrutorial.service and write the following code in it.UserService.java
package com.jackrutorial.service; import java.util.List; import com.jackrutorial.model.User; public interface UserService { public ListlistAllUser(); public void addUser(User user); public void updateUser(User user); public void delete(User user); public User findUserById(User user); }
Create a UserServiceImpl class implements UserService Interface under com.jackrutorial.service package and write the following code in it.
UserServiceImpl.java
package com.jackrutorial.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.jackrutorial.dao.UserDao; import com.jackrutorial.model.User; @Service public class UserServiceImpl implements UserService { UserDao userDao; @Autowired public void setUserDao(UserDao userDao) { this.userDao = userDao; } public ListlistAllUser() { return userDao.listAllUser(); } public void addUser(User user) { userDao.addUser(user); } public void updateUser(User user) { userDao.updateUser(user); } public void delete(User user) { userDao.delete(user); } public User findUserById(User user) { return userDao.findUserById(user); } }
Rest Controller Annotation Configuration
Create a UserController class under com.jackrutorial.controller package and write the following code in it.UserController.java
package com.jackrutorial.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.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 com.jackrutorial.model.User; import com.jackrutorial.service.UserService; @RestController public class UserController { @Autowired UserService userService; @RequestMapping(value="/user/", method = RequestMethod.GET, headers="Accept=application/json") public ResponseEntity<List<User>> listAllUser(){ List<User> list = userService.listAllUser(); if(list.size() == 0){ return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT); } return new ResponseEntity<List<User>>(list, HttpStatus.OK); } @RequestMapping(value="/add/", method = RequestMethod.POST, headers="Accept=application/json") public ResponseEntity<Void> add(@RequestBody User user){ userService.addUser(user); HttpHeaders headers = new HttpHeaders(); return new ResponseEntity<Void>(headers, HttpStatus.CREATED); } @RequestMapping(value="/update/{id}", method = RequestMethod.PUT, headers="Accept=application/json") public ResponseEntity<Void> update(@PathVariable("id") int id, @RequestBody User user){ user.setId(id); userService.updateUser(user); HttpHeaders headers = new HttpHeaders(); return new ResponseEntity<Void>(headers, HttpStatus.OK); } @RequestMapping(value="/delete/{id}", method = RequestMethod.DELETE, headers="Accept=application/json") public ResponseEntity<Void> delete(@PathVariable("id") int id, @RequestBody User user){ user.setId(id); userService.delete(user); HttpHeaders headers = new HttpHeaders(); return new ResponseEntity<Void>(headers, HttpStatus.NO_CONTENT); } }
Building Spring Restful web services
- Right click this project
- Select Run As -> Maven clean
- Right click this project
- Select Run As -> Maven install
How to deploy Spring Restful Web Service in Tomcat
Watch video add Apache Tomcat Server in Eclipse.Enter the following to the Host node in the TOMCAT_HOME/conf/server.xml.
<Context docBase="<Project Folder Location>\SpringRESTFulExample\target\SpringRESTFulExample-0.0.1-SNAPSHOT\" path="/SpringRESTFulExample" reloadable="true" >
<Resource
name="jdbc/springmvc"
auth="Container"
type="javax.sql.DataSource"
username="root"
password="root"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/jack_rutorial_demo"
maxActive="5"
maxIdle="3"
/>
</Context>
- Start Apache Tomcat from Eclipse Oxygen java.
How to test Spring MVC Restful web services using postman
Add User APIRequest Method: POST
URL: http://localhost:8080/SpringRESTFulExample/add/
Body: Type application/json
{ "firstname" : "Jack", "lastname" : "Rutorial", "address" : "http://www.jackrutorial.com" }
GET User API
Request Method: GET
URL: http://localhost:8080/SpringRESTFulExample/user/
Update User API
Request Method: PUT
URL: http://localhost:8080/SpringRESTFulExample/update/1
Body: Type application/json
{ "firstname" : "Jack Updated", "lastname" : "Rutorial Updated", "address" : "http://www.jackrutorial.com Updated" }
Delete User API
Request Method: DELETE
URL: http://localhost:8080/SpringRESTFulExample/delete/1
Body: Type application/json
{}