Spring RestController[通俗易懂]

Spring RestController[通俗易懂]SpringRestControllerannotationisaconvenienceannotationthatisitselfannotatedwith@Controllerand@ResponseBody.Thisannotationisappliedtoaclasstomarkitasarequesthandler.Spring…

大家好,又见面了,我是你们的朋友全栈君。

Spring RestController annotation is a convenience annotation that is itself annotated with @Controller and @ResponseBody. This annotation is applied to a class to mark it as a request handler.

Spring RestController注释是一个方便注释,它本身使用@Controller@ResponseBody注释。 该注释将应用于一个类,以将其标记为请求处理程序。

Spring RestController annotation is used to create RESTful web services using Spring MVC. Spring RestController takes care of mapping request data to the defined request handler method. Once response body is generated from the handler method, it converts it to JSON or XML response.

Spring RestController批注用于使用Spring MVC创建RESTful Web服务。 Spring RestController负责将请求数据映射到定义的请求处理程序方法。 从处理程序方法生成响应主体后,它将其转换为JSON或XML响应。

Spring RestController示例 (Spring RestController Example)

Let’s see how easily we can use RestController to create a REST web service in Spring. We will reuse the Spring Repository implementation and create a restful webservice.

让我们看看在Spring中使用RestController创建REST Web服务有多么容易。 我们将重用Spring Repository实现并创建一个宁静的Web服务。

We will create a standalone Web application and not use Spring Boot here. We will also expose our APIs to support both JSON and XML in request and response.

我们将在这里创建一个独立的Web应用程序,而不使用Spring Boot。 我们还将在请求和响应中公开支持JSON和XML的API。

Below image shows our final project structure.

下图显示了我们的最终项目结构。

Model and Repository classes are already provided in the Spring Repository tutorial. We will focus more on RestController implementation here.

Spring Repository教程中已经提供了Model和Repository类。 我们将在这里更多地关注RestController的实现。

Spring RestController Maven依赖关系 (Spring RestController Maven Dependencies)

Let’s have a look at the dependencies required to create our Spring RestController example project.

让我们看一下创建Spring RestController示例项目所需的依赖项。

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-webmvc</artifactId>
	<version>5.0.7.RELEASE</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-web</artifactId>
	<version>5.0.7.RELEASE</version>
</dependency>

<!-- Jackson for REST JSON Support -->
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.9.6</version>
</dependency>
<!-- JAXB for XML Response, needed to explicitly define from Java 9 onwards -->
<dependency>
	<groupId>javax.xml.bind</groupId>
	<artifactId>jaxb-api</artifactId>
	<version>2.3.0</version>
</dependency>
<dependency>
	<groupId>org.glassfish.jaxb</groupId>
	<artifactId>jaxb-runtime</artifactId>
	<version>2.3.0</version>
	<scope>runtime</scope>
</dependency>
<dependency>
	<groupId>javax.activation</groupId>
	<artifactId>javax.activation-api</artifactId>
	<version>1.2.0</version>
</dependency>

We need Spring MVC, Jackson and JAXB libraries to support both XML and JSON requests and responses from our REST web service.

我们需要Spring MVC,Jackson和JAXB库来支持XML和JSON请求以及来自REST Web服务的响应。

Our web.xml file is used to configure Spring MVC DispatcherServlet as the front controller.

我们的web.xml文件用于将Spring MVC DispatcherServlet配置为前端控制器。

Let’s look at the Spring Context file now.

现在让我们看一下Spring Context文件。

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
	xmlns="https://www.springframework.org/schema/mvc"
	xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="https://www.springframework.org/schema/beans"
	xmlns:context="https://www.springframework.org/schema/context"
	xsi:schemaLocation="https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<context:component-scan
		base-package="com.journaldev.spring" />

	<beans:bean id="jsonMessageConverter"
		class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
	<beans:bean id="xmlMessageConverter"
		class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" />

	<beans:bean
		class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
		<beans:property name="messageConverters">
			<beans:list>
				<beans:ref bean="jsonMessageConverter" />
				<beans:ref bean="xmlMessageConverter" />
			</beans:list>
		</beans:property>
	</beans:bean>

</beans:beans>

Most important part is the jsonMessageConverter and xmlMessageConverter beans defined and set in the RequestMappingHandlerAdapter messageConverters property. That’s all is needed to tell spring that we want our application to support both JSON and XML and these are the beans to be used for transformation.

最重要的部分是在RequestMappingHandlerAdapter messageConverters属性中定义和设置的jsonMessageConverterxmlMessageConverter Bean。 告诉Spring我们需要所有这些来支持我们的应用程序同时支持JSON和XML,并且这些都是用于转换的bean。

Spring RestController类 (Spring RestController Class)

Here is our Spring RestController class implementation.

这是我们的Spring RestController类的实现。

package com.journaldev.spring.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.journaldev.spring.model.Employee;
import com.journaldev.spring.repository.EmployeeRepository;

@RestController
public class EmployeeRestController {

	@Autowired
	private EmployeeRepository repository;
	
	@GetMapping("/rest/employee/get/{id}")
	public Employee getEmployeeByID(@PathVariable("id") int id) {
		return repository.retrieve(id);
	}
	
	@GetMapping("/rest/employee/getAll")
	//Returning is List is supported with JSON response only
	//If you want XML, then add a wrapper class as Root XML element, for example EmployeeList
	public List<Employee> getAllEmployees() {
		return repository.getAll();
	}

	@PostMapping("/rest/employee/create")
	public Employee createEmployee(@RequestBody Employee emp) {
		repository.store(emp);
		return emp;
	}
	
	@GetMapping("/rest/employee/search/{name}")
	public Employee getEmployeeByName(@PathVariable("name") String name) {
		return repository.search(name);
	}
	
	@DeleteMapping("/rest/employee/delete/{id}")
	public Employee deleteEmployeeByID(@PathVariable("id") int id) {
		return repository.delete(id);
	}
}

Notice that we have only defined our REST APIs here, all the business logic is part of Repository class.

注意,这里我们仅定义了REST API,所有业务逻辑都是Repository类的一部分。

If our method is returning a list or array, then spring will only support JSON response because XML root element can’t be anonymous but JSON can.

如果我们的方法返回列表或数组,那么spring将仅支持JSON响应,因为XML根元素不能匿名,而JSON可以。

If you want to support returning list as XML, then you will have to create a wrapper class to hold this list and return it.

如果要支持以XML返回列表,则必须创建一个包装器类来保存此列表并返回它。

We are expecting Employee object as the request in some of the methods, Spring will take care of parsing the request body and converting it to the Employee object for these methods.

我们期望在某些方法中将Employee对象作为请求,Spring将负责解析请求主体并将这些方法转换为Employee对象。

Similarly, we are returning Employee object as the Response Body, again Spring will take care of converting it to JSON/XML response.

同样,我们将Employee对象作为Response Body返回,Spring会再次将其转换为JSON / XML响应。

接受和内容类型请求标头 (Accept and Content-Type Request Headers)

We have configured our REST application to work with both XML and JSON. So how it will know that whether the request is XML or JSON. And if the response should be sent in JSON or XML format. This is where Accept and Content-Type Request Headers are used.

我们已经将REST应用程序配置为可以同时使用XML和JSON。 因此,它将如何知道请求是XML还是JSON。 以及是否应以JSON或XML格式发送响应。 这是使用“ Accept和“ Content-Type请求标头”的地方。

Content-Type: Defined the type of content in request body, if its value is “application/xml” then Spring will treat request body as XML document. If its value is “application/json” then the request body is treated as JSON.

Content-Type :定义了请求主体中内容的类型,如果其值为“ application / xml”,那么Spring将把请求主体视为XML文档。 如果其值为“ application / json”,则请求正文被视为JSON。

Accept: Defined the type of content client is expecting as response. If its value is “application/xml” then XML response will be sent. If its value is “application/json” then JSON response will be sent.

接受 :定义客户端期望作为响应的内容类型。 如果其值为“ application / xml”,则将发送XML响应。 如果其值为“ application / json”,则将发送JSON响应。

Spring RestController测试 (Spring RestController Test)

Our application is ready to be tested, I have deployed it on Tomcat-9 and testing with Postman. Below are the testing results with the explanation.

我们的应用程序已准备好进行测试,我已经将其部署在Tomcat-9上并通过Postman进行了测试。 以下是测试结果及其说明。

Spring RestController GET JSON响应 (Spring RestController GET JSON Response)

It’s a simple GET request, the important point to note is the value of “Accept” header.

这是一个简单的GET请求,需要注意的重要一点是“ Accept”标头的值。

Spring RestController GET XML响应 (Spring RestController GET XML Response)

Spring REST XML Response Accept header

When we changed “Accept” header value to “application/xml”, we are getting XML response.

当我们将“ Accept”标头值更改为“ application / xml”时,我们得到了XML响应。

Spring RestController GET列表 (Spring RestController GET List)

Let’s try to call the API to get list of employees.

Spring REST GET List JSON

We are getting list of elements in JSON with anonymous root element.

让我们尝试调用API以获取员工列表。

我们正在获取带有匿名根元素的JSON中的元素列表。

Spring REST GET List XML

Since XML doesn’t support anonymous root element, we are getting exception message.

由于XML不支持匿名根元素,因此我们收到了异常消息。

Spring RestController POST (Spring RestController POST)

Spring RestController POST with JSON Request and Response

Spring RestController POST带有JSON请求和响应

Spring RestController POST with JSON Request Body

Spring RestController POST与JSON请求正文

Spring RestController POST with JSON Request and XML Response

Spring RestController POST JSON Request and XML Response

Spring RestController POST带有JSON请求和XML响应

Spring RestController删除 (Spring RestController DELETE)

摘要 (Summary)

Spring RestController helps us in focusing on business logic by taking care of all the boiler-plate stuffs for creating REST web services APIs.

Spring RestController通过处理创建REST Web服务API的所有样板内容,帮助我们专注于业务逻辑。

GitHub Repository.
GitHub Repository下载完整的项目。

翻译自: https://www.journaldev.com/21536/spring-restcontroller

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/148565.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • python字典排序方法「建议收藏」

    python字典排序方法「建议收藏」字典是“键-值对”的无序可变序列在实际运用中,对字典进行排序是一个比较常见的操作,主要用到了python内置函数sorted(),该函数可以对所有可迭代的对象进行排序操作。语法(python3):sorted(iterable,key=None,reverse=False)参数说明:iterable:可迭代对象,即可以用for循环进行迭代的对象;key:主要是用来进行比较的元素,只有一个参数,具体的函数参数取自于可迭代对象中,用来指定可迭代对象中的一个元素来进行排序;reverse:排序规

    2022年6月18日
    26
  • Windows系统装机步骤以及常见专用名词汇总(实用)

    Windows系统装机步骤以及常见专用名词汇总(实用)一、装机流程(U盘安装或重装系统)注意:各个型号品牌的操作可能不同,但总体流程基本相同,实操注意查漏补缺。1.安装好主机(CPU,硬盘,内存,散热器,主板,电源,机箱,(显卡或者网卡使用的PCIE接口)),合上机箱。2.准备工作:将电源线(显示器、主机)插好,连接好显示器和主机之间的VGA线,插好键鼠的USB线。3.准备好一个启动U盘(百度“优启通”)。4.插入启动U盘并开启主机(按下电源键),根据电脑自己的装机BIOS快捷键(例如…

    2022年6月25日
    23
  • Java 安全之Weblogic 2018-2628&2018-2893分析

    Java安全之Weblogic2018-2628&2018-2893分析0x00前言续上一个weblogicT3协议的反序列化漏洞接着分析该补丁的绕过方式,根据weblogic的补

    2021年12月12日
    41
  • java中的 Set转List

    java中的 Set转List//构造Map数据 Map&lt;String,String&gt;map=newHashMap&lt;String,String&gt;(); map.put("ele1","小樱"); map.put("ele2","若曦"); map.put("ele3","晴川"); Set&lt;String&gt;s

    2022年10月18日
    0
  • Java Integer类型比较问题

    Java Integer类型比较问题JavaInteger类型比较问题【强制】所有整型包装类对象之间值的比较,全部使用equals方法比较。说明:对于Integervar=?在-128至127范围内的赋值,Integer对象是在IntegerCache.cache产生,会复用已有对象,这个区间内的Integer值可以直接使用==进行判断,但是这个区间之外的所有数据,都会在堆上产生,并不会复用已有对象,这是一个大坑,推荐使用equals方法进行判断。—-阿里巴巴Java开发手册抱着探索的精神我们来看

    2022年7月16日
    21
  • createprocess error=2_CreateProcess

    createprocess error=2_CreateProcessOpenProcess函数声明如下,失败则返回NULL(0,也就是false)#include<Windows.h>HANDLEOpenProcess(DWORDdesiredAccess,//读取权限BOOLblnheritHandle,//是否继承DWORDprocessId//想要读取的PID)代码示例,注意下面的代码可能运行失败,请按照如下设置VS右键项目名(例如ConsoleApplication123)->属性->配置属性(注意左上角是活动D

    2022年9月12日
    0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号