rspec/rules/S6833/java/rule.adoc

94 lines
2.4 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
Classes annotated as `@Controller` in Spring are responsible for handling incoming web requests.
When annotating methods or the entire controller with `@ResponseBody`, the return value of said methods will be serialized and set as the response body.
In other words, it tells the Spring framework that this method does not produce a view.
This mechanism is commonly used to create API endpoints.
Spring provides `@RestController` as a convenient annotation to replace the combination of `@Controller` and `@ResponseBody`.
The two are functionally identical, so the single annotation approach is preferred.
This rule will raise an issue on a class that is annotated with `@Controller` if:
* the class is also annotated with `@ResponseBody` or
* all methods in said class are annotated with `@ResponseBody`.
== How to fix it
Replace the `@Controller` annotation with the `@RestController` annotation and remove all `@ResponseBody` annotations from the class and its methods.
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
@Controller
@ResponseBody
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello World!";
}
}
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
@RestController
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello World!";
}
}
----
==== Noncompliant code example
[source,java,diff-id=2,diff-type=noncompliant]
----
@Controller
public class MyController {
@ResponseBody
@GetMapping("/hello")
public String hello() {
return "Hello World!";
}
@ResponseBody
@GetMapping("/foo")
public String foo() {
return "Foo";
}
}
----
==== Compliant solution
[source,java,diff-id=2,diff-type=compliant]
----
@RestController
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello World!";
}
@GetMapping("/foo")
public String foo() {
return "Foo";
}
}
----
== Resources
=== Articles & blog posts
* Spring Guides - https://spring.io/guides/gs/rest-service/[Building a RESTful Web Service]
* Baeldung - https://www.baeldung.com/spring-controller-vs-restcontroller[The Spring @Controller and @RestController Annotations]
* Baeldung - https://www.baeldung.com/spring-request-response-body[Spring's RequestBody and ResponseBody Annotations]