- 浏览: 1115971 次
文章分类
- 全部博客 (379)
- S2SH (16)
- stuts2 (0)
- java语言 (81)
- JSP (17)
- <html>元素 (11)
- javaweb (4)
- web容器 (3)
- ext (23)
- javaScript (48)
- ant (1)
- liferay (1)
- sql (9)
- css (42)
- 浏览器设置 (3)
- office_world (1)
- eclipse (4)
- 其它 (28)
- 操作系统 (5)
- android (6)
- Struts2 (11)
- RegEx (3)
- mysql (5)
- BigDATA (1)
- Node.js (1)
- Algorithm (10)
- Apache Spark (1)
- 数据库 (5)
- linux (2)
- git (1)
- Adobe (3)
- java语言,WebSocket (1)
- Maven (3)
- SHELL (1)
- XML (2)
- 数学 (2)
- Python (2)
- Java_mysql (1)
- ReactJS (6)
- 养生 (4)
- Docker (1)
- Protocols (3)
- java8 (2)
- 书籍 (1)
- Gradle (2)
- AngularJS (5)
- SpringMVC (2)
- SOAP (1)
- BootstrapCSS (1)
- HTTP协议 (1)
- OAuth2 (1)
最新评论
-
Lixh1986:
Java并发编程:自己动手写一把可重入锁https://blo ...
Java之多线程之Lock与Condition -
Lixh1986:
http://win.51apps.com.cn/https: ...
temp -
ztwsl:
不错,支持很好
HttpServletRequest和ServletRequest的区别 -
guodongkai:
谢谢您能将知识精华汇编总结,让初学者们从原理中学会和提高。
javaScript之function定义 -
kangwen23:
谢谢了,顶顶
struts2中的ValueStack学习
01 -Spring Framework: @RestController vs. @Controller
- 博客分类:
- S2SH
Spring MVC Framework and REST
Spring’s annotation-based MVC framework simplifies the process of creating RESTful web services. The key difference between a traditional Spring MVC controller and the RESTful web service controller is the way the HTTP response body is created. While the traditional MVC controller relies on the View technology, the RESTful web service controller simply returns the object and the object data is written directly to the HTTP response as JSON/XML. For a detailed description of creating RESTful web services using the Spring framework, click http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/mvc.html.
Figure 1: Spring MVC traditional workflow
Spring MVC REST Workflow
The following steps describe a typical Spring MVC REST workflow:
1. The client sends a request to a web service in URI form.
2. The request is intercepted by the DispatcherServlet which looks for Handler Mappings and its type.
2.1 The Handler Mappings section defined in the application context file tells DispatcherServlet which strategy to use to find controllers based on the incoming request.
2.2 Spring MVC supports three different types of mapping request URIs to controllers: annotation, name conventions, and explicit mappings.
3. Requests are processed by the Controller and the response is returned to the DispatcherServlet which then dispatches to the view.
In Figure 1, notice that in the traditional workflow the ModelAndView object is forwarded from the controller to the client. Spring lets you return data directly from the controller, without looking for a view, using the @ResponseBody annotation on a method. Beginning with Version 4.0, this process is simplified even further with the introduction of the @RestController annotation. Each approach is explained below.
Using the @ResponseBody Annotation
When you use the @ResponseBody annotation on a method, Spring converts the return value and writes it to the http response automatically. Each method in the Controller class must be annotated with @ResponseBody.
Figure 2: Spring 3.x MVC RESTful web services workflow
Behind the Scenes
Spring has a list of HttpMessageConverters registered in the background. The responsibility of the HTTPMessageConverter is to convert the request body to a specific class and back to the response body again, depending on a predefined mime type. Every time an issued request hits @ResponseBody, Spring loops through all registered HTTPMessageConverters seeking the first that fits the given mime type and class, and then uses it for the actual conversion.
Code Example
Let’s walk through @ResponseBody with a simple example.
Project Creation and Setup
1. Create a Dynamic Web Project with Maven support in your Eclipse or MyEclipse IDE.
2. Configure Spring support for the project.
• If you are using Eclipse IDE, you need to download all Spring dependencies and configure your pom.xml to contain those dependencies.
• In MyEclipse, you only need to install the Spring facet and the rest of the configuration happens automatically.
3. Create the following Java class named Employee. This class is our POJO.
Then, create the following @Controller class:
Notice the @ResponseBody added to each of the @RequestMapping methods in the return value.
After that, it's a two-step process:
1. Add the <context:component-scan> and <mvc:annotation-driven /> tags to the Spring configuration file.
- <context:component-scan> activates the annotations and scans the packages to find and register beans within the application context.
- <mvc:annotation-driven/> adds support for reading and writing JSON/XML if the Jackson/JAXB libraries are on the classpath.
- For JSON format, include the jackson-databind jar and
- For XML include the jaxb-api-osgi jar to the project classpath.
2. Deploy and run the application on any server (e.g., Tomcat). If you are using MyEclipse, you can run the project on the embedded Tomcat server.
JSON—Use the URL:
http://localhost:8080/SpringRestControllerExample/rest/employees/Bob
and the following output displays:
XML — Use the URL:
http://localhost:8080/SpringRestControllerExample/rest/employees/Bob.xml
and the following output displays:
Using the @RestController Annotation
Spring 4.0 introduced @RestController, a specialized version of the controller which is a convenience annotation that does nothing more than add the @Controller and @ResponseBody annotations. By annotating the controller class with @RestController annotation, you no longer need to add @ResponseBody to all the request mapping methods. The @ResponseBody annotation is active by default.
Click http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RestController.html to learn more.
To use @RestController in our example, all we need to do is modify the @Controller to @RestController and remove the @ResponseBody from each method. The resultant class should look like the following:
Note that we no longer need to add the @ResponseBody to the request mapping methods. After making the changes, running the application on the server again results in same output as before.
Conclusion
As you can see, using @RestController is quite simple and is the preferred method for creating MVC RESTful web services starting from Spring v4.0. I would like to extend a big thank you to my co-author, Swapna Sagi, for all of her help in bringing you this information!
-------------------------------------------------------------------
Spring 4.0 Restful 系列文章:
01 -Spring Framework: @RestController vs. @Controller
http://lixh1986.iteye.com/blog/2394351
02 - Difference between spring @Controller and @RestController annotation
http://lixh1986.iteye.com/blog/2394354
03 - SpringBoot: Building a RESTful Web Service
http://lixh1986.iteye.com/blog/2394363
- refered to:
https://dzone.com/articles/spring-framework-restcontroller-vs-controller
-
Spring’s annotation-based MVC framework simplifies the process of creating RESTful web services. The key difference between a traditional Spring MVC controller and the RESTful web service controller is the way the HTTP response body is created. While the traditional MVC controller relies on the View technology, the RESTful web service controller simply returns the object and the object data is written directly to the HTTP response as JSON/XML. For a detailed description of creating RESTful web services using the Spring framework, click http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/mvc.html.
Figure 1: Spring MVC traditional workflow
Spring MVC REST Workflow
The following steps describe a typical Spring MVC REST workflow:
1. The client sends a request to a web service in URI form.
2. The request is intercepted by the DispatcherServlet which looks for Handler Mappings and its type.
2.1 The Handler Mappings section defined in the application context file tells DispatcherServlet which strategy to use to find controllers based on the incoming request.
2.2 Spring MVC supports three different types of mapping request URIs to controllers: annotation, name conventions, and explicit mappings.
3. Requests are processed by the Controller and the response is returned to the DispatcherServlet which then dispatches to the view.
In Figure 1, notice that in the traditional workflow the ModelAndView object is forwarded from the controller to the client. Spring lets you return data directly from the controller, without looking for a view, using the @ResponseBody annotation on a method. Beginning with Version 4.0, this process is simplified even further with the introduction of the @RestController annotation. Each approach is explained below.
Using the @ResponseBody Annotation
When you use the @ResponseBody annotation on a method, Spring converts the return value and writes it to the http response automatically. Each method in the Controller class must be annotated with @ResponseBody.
Figure 2: Spring 3.x MVC RESTful web services workflow
Behind the Scenes
Spring has a list of HttpMessageConverters registered in the background. The responsibility of the HTTPMessageConverter is to convert the request body to a specific class and back to the response body again, depending on a predefined mime type. Every time an issued request hits @ResponseBody, Spring loops through all registered HTTPMessageConverters seeking the first that fits the given mime type and class, and then uses it for the actual conversion.
Code Example
Let’s walk through @ResponseBody with a simple example.
Project Creation and Setup
1. Create a Dynamic Web Project with Maven support in your Eclipse or MyEclipse IDE.
2. Configure Spring support for the project.
• If you are using Eclipse IDE, you need to download all Spring dependencies and configure your pom.xml to contain those dependencies.
• In MyEclipse, you only need to install the Spring facet and the rest of the configuration happens automatically.
3. Create the following Java class named Employee. This class is our POJO.
package com.example.spring.model; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "Employee") public class Employee { String name; String email; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Employee() { } }
Then, create the following @Controller class:
package com.example.spring.rest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.example.spring.model.Employee; @Controller @RequestMapping("employees") public class EmployeeController { Employee employee = new Employee(); @RequestMapping(value = "/{name}", method = RequestMethod.GET, produces = "application/json") public @ResponseBody Employee getEmployeeInJSON(@PathVariable String name) { employee.setName(name); employee.setEmail("employee1@genuitec.com"); return employee; } @RequestMapping(value = "/{name}.xml", method = RequestMethod.GET, produces = "application/xml") public @ResponseBody Employee getEmployeeInXML(@PathVariable String name) { employee.setName(name); employee.setEmail("employee1@genuitec.com"); return employee; } }
Notice the @ResponseBody added to each of the @RequestMapping methods in the return value.
After that, it's a two-step process:
1. Add the <context:component-scan> and <mvc:annotation-driven /> tags to the Spring configuration file.
- <context:component-scan> activates the annotations and scans the packages to find and register beans within the application context.
- <mvc:annotation-driven/> adds support for reading and writing JSON/XML if the Jackson/JAXB libraries are on the classpath.
- For JSON format, include the jackson-databind jar and
- For XML include the jaxb-api-osgi jar to the project classpath.
2. Deploy and run the application on any server (e.g., Tomcat). If you are using MyEclipse, you can run the project on the embedded Tomcat server.
JSON—Use the URL:
http://localhost:8080/SpringRestControllerExample/rest/employees/Bob
and the following output displays:
XML — Use the URL:
http://localhost:8080/SpringRestControllerExample/rest/employees/Bob.xml
and the following output displays:
Using the @RestController Annotation
Spring 4.0 introduced @RestController, a specialized version of the controller which is a convenience annotation that does nothing more than add the @Controller and @ResponseBody annotations. By annotating the controller class with @RestController annotation, you no longer need to add @ResponseBody to all the request mapping methods. The @ResponseBody annotation is active by default.
Click http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RestController.html to learn more.
To use @RestController in our example, all we need to do is modify the @Controller to @RestController and remove the @ResponseBody from each method. The resultant class should look like the following:
package com.example.spring.rest; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.example.spring.model.Employee; @RestController @RequestMapping("employees") public class EmployeeController { Employee employee = new Employee(); @RequestMapping(value = "/{name}", method = RequestMethod.GET, produces = "application/json") public Employee getEmployeeInJSON(@PathVariable String name) { employee.setName(name); employee.setEmail("employee1@genuitec.com"); return employee; } @RequestMapping(value = "/{name}.xml", method = RequestMethod.GET, produces = "application/xml") public Employee getEmployeeInXML(@PathVariable String name) { employee.setName(name); employee.setEmail("employee1@genuitec.com"); return employee; } }
Note that we no longer need to add the @ResponseBody to the request mapping methods. After making the changes, running the application on the server again results in same output as before.
Conclusion
As you can see, using @RestController is quite simple and is the preferred method for creating MVC RESTful web services starting from Spring v4.0. I would like to extend a big thank you to my co-author, Swapna Sagi, for all of her help in bringing you this information!
-------------------------------------------------------------------
Spring 4.0 Restful 系列文章:
01 -Spring Framework: @RestController vs. @Controller
http://lixh1986.iteye.com/blog/2394351
02 - Difference between spring @Controller and @RestController annotation
http://lixh1986.iteye.com/blog/2394354
03 - SpringBoot: Building a RESTful Web Service
http://lixh1986.iteye.com/blog/2394363
- refered to:
https://dzone.com/articles/spring-framework-restcontroller-vs-controller
-
发表评论
-
Spring之Interceptor之path patterns路径匹配规则
2018-12-26 11:20 8794Spring之Interceptor之path pattern ... -
Spring4.X之Constructor Injection 构造方法注入
2018-12-24 17:37 1582Spring4.X之Constructor Injection ... -
SpringMVC之@RequestMapping @ResponseBody 和 @RequestBody 注解的用法
2018-05-30 10:55 15861、@RequestMapping @RequestMappi ... -
Spring4.X之Bean的Scope
2017-11-06 16:29 1205https://docs.spring.io/spring/d ... -
Spring4.X之基于Java注解的配置(与SpringBoot的诞生)
2017-11-02 16:57 4157最近项目用到了SpringBoot,对其没有xml配置就可以运 ... -
03 - SpringBoot: Building a RESTful Web Service
2017-09-25 17:47 1032Building a RESTful Web Service ... -
02 - Difference between spring @Controller and @RestController annotation
2017-09-25 17:04 893Difference between spring @Con ... -
Spring - MVC 思维导图,让Spring不再难懂
2017-08-09 03:21 1082引用: http://www.iteye.com/news/3 ... -
hibernate merge与update区别
2017-04-18 15:38 2200今天做了个测试,写了 ... -
Struts2拦截器原理以及实例
2017-02-15 12:49 480Struts2拦截器原理以及实例 http://www.cnb ... -
SSH之Struts2 VS. SpringMVC
2017-02-07 10:26 1000Struts 2 vs SpringMVC - Battl ... -
Maven之POM之SSH之libs之configuration
2017-02-05 08:56 789Maven repo libs: Servlet API, ... -
Hibernate自定义查询
2014-02-24 16:29 1590public void addCarmera(Carmera ... -
Hibernate对象的生命周期
2013-07-10 16:32 1840一、情景描述 鉴于:hibernate是面向对象(实体、en ... -
通过配置struts.xml解决 struts2和 dwr兼容的问题
2012-11-20 10:20 2085众所周知,strust2 通过在 web.xml中配置 fil ...
相关推荐
import org.springframework.web.bind.annotation.RestController; // @RestController返回的是json @RestController public class HelloWorldController { // http://localhost:8080/hello 返回的是文本"Hello ...
在Java的Web开发领域,Spring框架是不可或缺的重要工具,其中`org.springframework.web.jar`文件是Spring框架的核心组成部分,主要用于处理Web应用程序的相关功能。这个JAR(Java Archive)文件包含了Spring Web模块...
《Spring Framework 4.3.3.RELEASE:构建高效企业级应用的核心技术解析》 Spring Framework,作为Java领域最广泛使用的轻量级框架之一,以其模块化、易扩展的特性深受开发者喜爱。4.3.3版本是Spring Framework的一...
Spring MVC(Model-View-Controller)作为Spring Framework 中的Web层组件,5.0 版本也得到了显著优化。它支持了HTTP/2协议,提高了网络传输效率。此外,ModelAndView对象的处理更加灵活,支持更多的视图技术,如...
import org.springframework.web.bind.annotation.RestController; @RestController public class SpringRestControllerDemo { @GetMapping("/users/{id}") public UserDetails getUserDetails(@PathVariable(...
<groupId>org.springframework.boot <artifactId>spring-boot-starter-data-jpa <groupId>org.mybatis.spring.boot <artifactId>mybatis-spring-boot-starter <version>2.2.2 ``` 2. **配置MyBatis**:...
<groupId>org.springframework.boot <artifactId>spring-boot-starter-data-jpa <groupId>org.mybatis.spring.boot <artifactId>mybatis-spring-boot-starter <version>1.3.5 ``` 接着,配置MyBatis的相关...
《深入剖析Spring Framework 4.3.4 Release》 Spring Framework是Java开发中的核心框架,以其模块化、可扩展性和广泛的功能集而闻名。4.3.4版本是该框架的一个稳定版本,提供了许多增强特性和修复了许多已知问题。...
27.1. The “Spring Web MVC Framework” 27.1.1. Spring MVC Auto-configuration 27.1.2. HttpMessageConverters 27.1.3. Custom JSON Serializers and Deserializers 27.1.4. MessageCodesResolver 27.1.5. Static...
3. New Features and Enhancements in Spring Framework 4.0 ............................................ 17 3.1. Improved Getting Started Experience .........................................................
import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @GetMapping("/user") public ResponseEntity<User> getUser() { User user = new User(); ...
Spring Framework 是一个全面的Java应用开发框架,由Pivotal Software公司开发,它极大地简化了企业级Java应用程序的构建过程。在Spring Framework 4.3.12.RELEASE这个版本中,我们看到了许多关键特性和改进,使得它...
import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @RequestMapping("/model1") public Model1 getModel1() { Model1 model1 = new Model1(); //...
import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/mydb") public class DBController { @Autowired private JdbcTemplate jdbcTemplate; @RequestMapping(...
import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") public class RestController { @GetMapping("/hello") public ResponseEntity<String> hello() { ...
import org.springframework.web.bind.annotation.RestController; @Controller public class MyController { @GetMapping("/hello") public String hello() { return "hello"; } } ``` 在这个例子中,当用户...
<groupId>org.springframework.boot <artifactId>spring-boot-starter-web <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter 最新版本号 ``` 确保使用的是Mybatis-Plus的最新稳定...
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/appServlet/servlet-context...
import org.springframework.web.bind.annotation.RestController; import com.belerweb.easypoi.base.util.ExcelImportUtil; @RestController public class ExcelController { @PostMapping("/import") public ...