Let’s start with runtime dependencies which you will need to write these RESTFul APIs. In fact, all you need is Spring MVC support only.
pom.xml
< project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
< modelVersion >4.0.0</ modelVersion >
< groupId >com.howtodoinjava.demo</ groupId >
< artifactId >springrestexample</ artifactId >
< packaging >war</ packaging >
< version >0.0.1-SNAPSHOT</ version >
< name >springrestexample Maven Webapp</ name >
< dependencies >
< dependency >
< groupId >junit</ groupId >
< artifactId >junit</ artifactId >
< version >4.12</ version >
< scope >test</ scope >
</ dependency >
<!-- Spring MVC support -->
< dependency >
< groupId >org.springframework</ groupId >
< artifactId >spring-webmvc</ artifactId >
< version >4.1.4.RELEASE</ version >
</ dependency >
< dependency >
< groupId >org.springframework</ groupId >
< artifactId >spring-web</ artifactId >
< version >4.1.4.RELEASE</ version >
</ dependency >
< dependency >
< groupId >org.springframework</ groupId >
< artifactId >spring-core</ artifactId >
< version >4.1.4.RELEASE</ version >
</ dependency >
</ dependencies >
< build >
< finalName >springrestexample</ finalName >
</ build >
</ project >
|
Note: If you please planning to include JSON support as well then all you need to do is include Jackson libraries into classpath, and same APIs will work for jackson as well.
<!-- Jackson JSON Processor --> < dependency >
< groupId >com.fasterxml.jackson.core</ groupId >
< artifactId >jackson-databind</ artifactId >
< version >2.4.1</ version >
</ dependency >
|
Spring MVC Configuration
For creating APIs, you will need to configure your applications same as you do in Spring MVC.
web.xml
<! DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
< web-app >
< display-name >Archetype Created Web Application</ display-name >
< servlet >
< servlet-name >spring</ servlet-name >
< servlet-class >
org.springframework.web.servlet.DispatcherServlet
</ servlet-class >
< load-on-startup >1</ load-on-startup >
</ servlet >
< servlet-mapping >
< servlet-name >spring</ servlet-name >
< url-pattern >/</ url-pattern >
</ servlet-mapping >
</ web-app >
|
spring-servlet.xml
xsi:schemaLocation="http://www.springframework.org/schema/beans
< context:component-scan base-package = "com.howtodoinjava.demo" />
< mvc:annotation-driven />
</ beans >
|
JAXB Annotated Model Objects
You will need to annotate your model objects with jaxb annotations so that JAXB can marshal the java object into XML representation to be sent to client for that API.
EmployeeVO.java
package com.howtodoinjava.demo.model;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement (name = "employee" )
@XmlAccessorType (XmlAccessType.NONE)
public class EmployeeVO implements Serializable
{ private static final long serialVersionUID = 1L;
@XmlAttribute
private Integer id;
@XmlElement
private String firstName;
@XmlElement
private String lastName;
@XmlElement
private String email;
public EmployeeVO(Integer id, String firstName, String lastName, String email) {
super ();
this .id = id;
this .firstName = firstName;
this .lastName = lastName;
this .email = email;
}
public EmployeeVO(){
}
//Setters and Getters
@Override
public String toString() {
return "EmployeeVO [id=" + id + ", firstName=" + firstName
+ ", lastName=" + lastName + ", email=" + email + "]" ;
}
} |
EmployeeListVO.java
package com.howtodoinjava.demo.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement (name= "employees" )
public class EmployeeListVO implements Serializable
{ private static final long serialVersionUID = 1L;
private List<EmployeeVO> employees = new ArrayList<EmployeeVO>();
public List<EmployeeVO> getEmployees() {
return employees;
}
public void setEmployees(List<EmployeeVO> employees) {
this .employees = employees;
}
} |
REST Controller
This is main class which will decide that which API will behave which way.
EmployeeRESTController.java
package com.howtodoinjava.demo.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.howtodoinjava.demo.model.EmployeeListVO;
import com.howtodoinjava.demo.model.EmployeeVO;
@RestController public class EmployeeRESTController
{ @RequestMapping (value = "/employees" )
public EmployeeListVO getAllEmployees()
{
EmployeeListVO employees = new EmployeeListVO();
EmployeeVO empOne = new EmployeeVO( 1 , "Lokesh" , "Gupta" , "howtodoinjava@gmail.com" );
EmployeeVO empTwo = new EmployeeVO( 2 , "Amit" , "Singhal" , "asinghal@yahoo.com" );
EmployeeVO empThree = new EmployeeVO( 3 , "Kirti" , "Mishra" , "kmishra@gmail.com" );
employees.getEmployees().add(empOne);
employees.getEmployees().add(empTwo);
employees.getEmployees().add(empThree);
return employees;
}
@RequestMapping (value = "/employees/{id}" )
public ResponseEntity<EmployeeVO> getEmployeeById ( @PathVariable ( "id" ) int id)
{
if (id <= 3 ) {
EmployeeVO employee = new EmployeeVO( 1 , "Lokesh" , "Gupta" , "howtodoinjava@gmail.com" );
return new ResponseEntity<EmployeeVO>(employee, HttpStatus.OK);
}
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
} |
Let’s note down few important things.
1) We have used @RestController annotation. Till Spring 3, we would have been using @Controller annotation and in that case it was important to use@ResponseBody annotation as well. e.g.
@Controller public class EmployeeRESTController
{ @RequestMapping (value = "/employees" )
public @ResponseBody EmployeeListVO getAllEmployees()
{
//API code
}
} |
Spring 4 introduced @RestController
which is combination of @Controller + @ResponseBody
. So when using @RestController
, you do not need to use@ResponseBody
. It’s optional.
2) Here we are relying on the Spring MVC HttpMessageConverter
s to convert an object to the xml representation requested by the user. @ResponseBody
annotation (included through @RestController
) tells Spring MVC that the result of the method should be used as the body of the response. As we want XML this marshaling is done by the Jaxb2RootElementHttpMessageConverter
provided by Spring which is automatically registered in spring context if JAXB libraries are found in classpath. As I am using JRE 7 to run this application and it has JAXB inbuilt, so I do not need to add external dependency through maven.
3) Due to the @ResponseBody
annotation, we don’t need the view name anymore but can simply return the employees object.
4) Instead of returning the java objects directly, you can wrap them inside ResponseEntity
. The ResponseEntity
is a class in Spring MVC that acts as a wrapper for an object to be used as the body of the result together with a HTTP status code. This provides greater control over what you are returning to client in various use cases. e.g. returning a 404 error if no employee is found for given employee id.
Project Structure
Test the APIs
Let’s test above REST APIs.
1) Hit URL : http://localhost:8080/springrestexample/employees
You can pass accept header “application/xml
” as well.
2) Hit URL : http://localhost:8080/springrestexample/employees/1
3) Hit URL : http://localhost:8080/springrestexample/employees/123
Status Code: 404 Not Found
Content-Length: 0
Date: Fri, 18 Feb 2015 07 : 01 : 17 GMT
Server: Apache-Coyote/ 1.1
|
That’s all for this quick hello world application for RESTFul APIs using spring mvc.
相关推荐
基于maven的springMVC@RestController的使用,适合初学者,......................................................................................................................................................
本节主要介绍如何在`RestController`中获取不同类型的数据,包括URL路径变量、请求体、请求头、查询参数、请求头信息、Cookie值、文件上传等。 1. **URL路径变量**: 使用`@PathVariable`注解可以从URL路径中获取...
在Spring 4.0中,`@RestController`是一个重要的新特性,它标志着Spring MVC框架对RESTful服务支持的增强。`@RestController`是`@Controller`和`@ResponseBody`两个注解的组合,使得处理HTTP请求变得更加简洁和高效...
因此,在前后端分离的项目中,`@RestController`常被用于构建提供数据服务的API接口,因为它可以直接返回数据,由前端负责展示和交互。 举个例子,如果你有一个`@Controller`注解的类,其中的一个方法返回"success...
@RestController注解是SpringBoot框架中一个非常重要的注解,它是@Controller和@ResponseBody的组合体,主要用于标记当前类是一个控制器,并且所有的方法返回值都会被转换为Json字符串。 首先,我们来看一下@...
Spring @RestController 注解组合实现方法解析 在 Spring 框架中,@RestController 注解是一个非常重要的注解,它是 @Controller 和 @ResponseBody 两个注解的组合。通过使用 @RestController 注解,我们可以将 ...
@Controller、@RestController注解区别详解 @Controller和@RestController是Spring框架中两个重要的注解,它们都是用于标识控制器类的,但是它们之间有着很大的区别。 首先,让我们来了解一下@Controller注解。@...
@RestController public class UserController { @RequestMapping(value = "/users", method = RequestMethod.GET) public List<User> getAllUsers() { // 实现获取所有用户逻辑 } @RequestMapping(value = ...
Spring Boot JPA @RestController 没有视图和 Thymeleaf 带有图像public class EmployeeImageController和 Swagger 的 Rest Controller 应用程序属性 类:JPA @Entity Employee 和 CrudRepository 接口 数据库:H2...
Spring 4 Web Service类用@RestController 进行注释, 可以取代@Controller和@ResponseBody的使用。要映射REST Web服务URL,请使用注释@RequestMapping。Web服务方法参数包含@RequestParam,该属性具有defaultValue...
高级控制器@AdvancedController是一个增强型的RestController注解,可以使用接口来定义Controller类,自动匹配Service类并调用Service中的方法。 TestController.java @RequestMapping("/test")@AdvancedController...
主类:**SpringBOotDemoApplication**在包java.com.springbootdemo; controller类放在包java.com中; 因为SpringBoot只会扫描启动类当前包和以下的包 ,所以上面这处情况是找不到controller的,所以出现404错误。
测试url : 在mian下面加以下代码,在@SpringBootApplication上@RestController @GetMapping("/demo") public String demo() { return "Hello World!"; } 如果测试发现运行中止,console显示 Process finished ...
弹簧座控制器Spring 4 Rest 控制器脚手架示例项目展示了 Spring 4 的 RestController 来提供 XML 和 JSON。 注意 pom 文件中使用的 Jackson 版本,因为 Spring 似乎特别关注 Jackson 版本。 样品用途: curl -v -i -...
继承自库中的RestController类,而不是CodeIgniter的CI_Controller。这样,你的控制器就有了处理REST请求的能力。 3. **定义API方法**:在API.php控制器中,你可以定义各种处理HTTP请求的方法。例如,你可以有一个`...
一个简单的应用程序,公开了一个简单的Webflux Restcontroller。 您可以使用或来测试API。 生成并运行 先决条件: Java 11+ Apache Maven( ) 生成并运行 用 mvn clean install 生成应用程序并 java -jar ...
SimpleWebApplication 测试项目(html,javacript,jquery,AJAX发布请求,JSON文档,RESTcontroller,spring,CORS过滤器) UI模块: 具有下一个元素的简单HTML表单: textarea字段“输入”; textarea字段“输出”...
基于Spring Boot框架的微信小程序音乐播放器项目旨在为用户提供便捷、多样化的音乐播放体验,结合了后端逻辑处理和微信小程序的用户界面,实现了以下主要功能: 音乐资源管理:允许管理员在系统中上传和管理音乐...
2.@RestController注解,相当于@Controller+@ResponseBody两个注解的结合,返回json数据不需要在方法前面加@ResponseBody注解了,但使用@RestController这个注解,就不能返回jsp,html页面,视图解析器无法解析jsp,...
在SpringMVC中,我们可以使用@RestController注解来标注控制器,使用@RequestMapping注解来标注请求映射,使用@RequestBody注解来标注请求体,使用@ResponseBody注解来标注响应体。 例如,我们可以编写一个简单的...