Class Level Controller Annotations
Controller Classes - Video
The starter code for this video is found in the forms branch
of the hello-spring
repo. The final code presented in this video is found on the class-annotations branch
. As always, code along to the videos on your own hello-spring
project.
Have you been tracking your app progress in your own git branches
? Saving your progress in branches for each video tutorial means you can always go back to a certain spot in the app development. We will be returning to the forms
branch in the next lesson, so track your class-annotations
in a new branch with git checkout -b <branch-name>
.
Controller Classes - Text
Once you have written several controller methods within a class, you may notice some similar behavior across handlers. This is an opportunity to DRY your code. Some of the annotations we use at the method level can also be used on the whole controller classes.
We mentioned this earlier. If all of the methods in a controller class begin with the same root path, @RequestMapping
can be added above the class.
@Controller
@RequestMapping(value="hello")
public class HelloController {
// responds to /hello
@GetMapping("")
@ResponseBody
public String hello() {
return "Hello";
}
// responds to /hello/goodbye
@GetMapping("goodbye")
@ResponseBody
public String helloGoodbye() {
return "Hello, Goodbye";
}
}
Note that we use @RequestMapping
on the class. @GetMapping
and @PostMapping
cannot be applied at the class level.
In a related fashion, if you find that each of your methods in a controller class use @ResponseBody
to return plain text, this annotation may be added at the top of the class, rather than at each method declaration.
Check Your Understanding
True/False:
No one controller method can handle several request types.
True
False
We want the method hello
to take another parameter, @RequestParam String friend
, that will add a friend’s name to the returned greeting. The user should also be able to enter this name via a text field. What needs to be added to the form?
Another
input
tag with afriend
attribute.Another
input
tag with aname
attribute.Another
form
tag with amethod
attribute.Another
submit
tag with afriend
value.