It's time to walk through a few Spring Web controller examples. After reading this lesson, you should be familiar with the following Spring Web annotations:
@Controller@RestController@RequestMapping
Example Location:com.codingnomads.springweb.springrestcontrollers.simpledemo
@RestController Annotation
As you learned in the previous lesson, the @RestController annotation:
- Marks the class as a "controller", and sets it up to handle web requests.
- Instructs Spring to write data returned from the methods within this class directly to the body of the HTTP response (rather than to an HTML view).
Interestingly, when you dig down into the interface (you can find it below) that defines the @RestController annotation, you find that it is actually a combination of both the @Controller annotation and the @ResponseBody annotation. In reality, it is these two annotations that take care of the tasks in the bulleted list above.
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
@AliasFor(annotation = Controller.class)
String value() default "";
}
@Controller is the annotation that tasks the class with responding to web requests, while marking a class with @ResponseBody means that method return data will be written to the HTTP response body.
Info: Keep in mind that this section will only explain how to use @RestController. In the next section, you will learn how to use @Controller on its own and exactly what it means to do so.
@RequestMapping Annotation
Before fully understanding an example RestController class, you must familiarize yourself with the @RequestMapping annotation. This annotation allows you to define an endpoint. When a request is received, whatever entity is marked with the matching @RequestMapping is used to generate a response. This allows you to set up a complex RESTful API with many hundreds of endpoints very quickly.
This annotation can be used on both the class level and method level. This not only allows you to direct a specific URL to a certain class, but also means a request can be directed to a method within a class. The @RequestMapping annotation takes the following parameters that help you to define your endpoint:
- path or value: the URL path being mapped
- method: indicates the HTTP method required (GET, POST, etc.)
- headers: this parameter can be used to specify required HTTP headers, passed in as an array of Strings in this format
"header-name=required-value" - consumes: the media type that this method will accept
- produces: indicates what media type the method produces.
Let's lay out a few examples, each one changing the mapping of the hello() method.
@RestController
@RequestMapping(path = "/api")
public class HelloWorldController {
public String hello() {
return "Hello Spring Developer!";
}
}
In the above code snippet, @RequestMapping is used only on the class level. This instructs Spring to direct any request with a URL whose path starts with /api to the HelloWorldController class. However, before a request can be forwarded to hello(), you have to indicate the type of request that the method accepts like so:
@RestController
@RequestMapping(path = "/api")
public class HelloWorldController {
@RequestMapping(method = RequestMethod.GET)
public String hello() {
return "Hello Spring Developer!";
}
}
Now, Spring understands that you want requests with the URL path /api with HTTP method GET to be forwarded to hello().
The next example changes the required path to reach the hello() method to /api/hello. Note how the /hello component of the path is specified at the method level. This means that /hello only applies to the hello() method, whereas /api applies to all the methods in the HelloWorldController class.
@RestController
@RequestMapping(path = "/api")
public class HelloWorldController {
@RequestMapping(path = "/hello", method = RequestMethod.GET)
public String hello() {
return "Hello Spring Developer!";
}
}
The following example adds a second method. Take a look and see if you can figure out the endpoint/URL path that will be mapped to this new method.
@RestController
@RequestMapping(path = "/api")
public class HelloWorldController {
@RequestMapping(path = "/hello", method = RequestMethod.GET)
public String hello() {
return "Hello Spring Developer!";
}
@RequestMapping(path = "/hello/{name}", method = RequestMethod.GET)
public String greeting(@PathVariable(name = "name") String name) {
return "Hello " + name + "!";
}
}
If you're stumped, here's some help: The greeting() method takes a path variable called name. It then uses this variable to create the return String. Start up the example for this lesson, and try hitting this endpoint in your browser and check the result:
http://localhost:8080/api/hello/Mandalorian
Learn by Doing
Package: springweb.springrestcontrollers.simpledemo.controller
- Using the two existing methods in HelloWorldController as a guide, create two additional endpoints.
- Have one return a List, and have one return a POJO (maybe the Task model from earlier examples?).
- Test your new endpoints using a web browser and Postman.
You will learn more about @PathVariable later in the course.
Fun Example
This example gets a bit more complicated, mainly because there is more logic inside the returnSomeBinary() method. But if you look closely, you can see the endpoints are clearly defined to accept GET requests. Try them out in your browser!
@RestController
public class ConversionController {
private final String text =
"this is the text that this is all based on.";
@RequestMapping(
path = "/binary",
method = RequestMethod.GET,
produces = MediaType.TEXT_PLAIN_VALUE
)
public String returnSomeBinary() {
StringBuilder binary = new StringBuilder();
char[] chars = text.toCharArray();
for (char c : chars) {
binary.append(" ").append(Integer.toBinaryString(c));
}
return binary.toString();
}
@RequestMapping(path = "/normal", method = RequestMethod.GET)
public String returnTheString() {
return text;
}
}
Info: Having trouble hitting these endpoints? Notice how the ConversionController does not have a @RequestMapping on the class level. As was just proven, this is in no way required. Compared to the previous example's endpoint /api/hello, these are simply /binary and /normal.
Also, the produces parameter is set on returnSomeBinary() to indicate that the method returns plain text. This changes the HTTP response header and helps applications using your web service understand what they are getting in return. Don't worry if this isn't making sense right away. These are big steps forward!
Learn by Doing
Package: springweb.springrestcontrollers.simpledemo.controller
It's time for some more fun practice!
- Inside ConversionController, create a new endpoint:
/backwards. - Have this method reverse the
textString before returning it.
Endpoint HTTP Methods
As you've learned, @RequestMapping allows you to handle all types of HTTP request methods, including GET, PUT, POST, DELETE, and PATCH.
@RestController
@RequestMapping("/home")
public class HomeController {
@RequestMapping(method = RequestMethod.GET)
String get() {
return "Hello from get";
}
@RequestMapping(method = RequestMethod.DELETE)
String delete() {
return "Hello from delete";
}
@RequestMapping(method = RequestMethod.POST)
String post() {
return "Hello from post";
}
@RequestMapping(method = RequestMethod.PUT)
String put() {
return "Hello from put";
}
@RequestMapping(method = RequestMethod.PATCH)
String patch() {
return "Hello from patch";
}
}
What you have defined here is a single endpoint (/home), but with separate methods to handle each type of incoming request type. This is very common, and you will learn more about this setup later.
Learn by Doing
Package: springweb.springrestcontrollers.simpledemo.controller
- Hit the endpoint
/homefor each defined request method using Postman. - Now, comment out the
post()method in HomeController and try to POST with Postman again. - This time, you should get the error "Method Not Allowed".
Please be sure to push your work to GitHub when you're done.
Multiple Endpoints - Single Method
It's helpful to note that most of the parameters that @RequestMapping accepts can be formatted as String[] arrays. If you only pass in a single term, you don't have to format the String as an array, the annotation takes care of that for you. However, passing in multiple terms looks a little different. This example shows you how to define multiple paths and HTTP methods for an endpoint:
@RestController
public class MultiplePathExampleController {
@RequestMapping(
path = {"/this-path", "/another-path" },
method = {RequestMethod.GET, RequestMethod.POST}
)
public String confirmation() {
return "this String confirms that the path you entered works!";
}
}
Here, the String returned from the confirmation() method will be returned to the user when they use either GET or POST and with path /this-path OR /another-path. The above endpoint does not however accept requests with the path /this-path/another-path.
Tip: Its generally a better practice to define a single method for each endpoint path and HTTP method. This makes the class more readable and easier to maintain.
Summary: @RestController
This lesson was a big one. It showed you how to use @RestController and @RequestMapping to define endpoints for your web application. Here are some of the highlights:
@RestControlleris a combination of@Controllerand@ResponseBody.@Controllertells Spring that this class will be used to respond to web requests.@ResponseBodytells Spring to write the data/objects returned from the methods within the class directly to the HTTP response body.@RequestMappingis used to define your endpoints. It can be used on the method or class level, and takes the following parameters as a String or an array of Strings:pathmethodheadersconsumesproduces
The elements listed here are essentially all you need to define and set up a complex API with many endpoints. A powerful coder you have become.