10) Spring Web Lesson

Spring Controllers

4 min to complete · By Ryan Desmond, Jared Larsen

The previous two lessons gave you an overview of the Java servlet mechanism. As mentioned before, Spring takes much of that work off your hands. It does this through a number of annotations.

This lesson will give you an idea of what Spring does in the background, but it does not go into detail on the annotations used. These will be covered with examples and in much more detail later.

Spring Controllers

When creating servlets, you had to extend Servlet classes, implement a bunch of methods, register your servlets with the ServletContext, and add filters. It was a lot of work to set up and a relatively complex system to understand. Now how would you feel if we told you that all of this work is done automatically by marking a class with @Controller?

What do we mean by automatically? When a class is marked with @Controller, Spring understands that you want this class to be in charge of responding to web requests. Keep in mind it's not like Spring just magically starts responding to requests. Instead, Spring layers its own system on top of the existing servlet architecture.

Front Controller

The core of this system is the "Front Controller". The Front Controller is tasked with forwarding requests to the correct classes marked with @Controller. It does this using the incoming request URL. If Spring finds a class marked to deal with that specific URL, the request is forwarded through the servlet system to your controller class. If it can't find the corresponding controller, a 404 Not Found error is returned to the user.

Depending on how you set up your controller, the request will be sent to a specific method within the controller whose return object or value will be written directly to the HTTP Response body. The image below may help you visualize what all of this looks like.

Understanding servlet flow

Rest Controller

Spring also offers a specialized form of the @Controller annotation: @RestController. While the former typically returns HTML pages, aka "views", @RestController ties the method return value to the body of the response. This makes @RestController ideal for creating RESTful web services.

Colorful illustration of a light bulb

Tip: This doesn't need to make complete sense right now, just be aware that you will encounter both forms of controller annotation moving forward.

Summary: Spring Controllers

When a class is marked with @Controller (or @RestController), Spring creates a path from the outside world to that class based on the URL you assigned to it. You can almost completely ignore the world of servlets running the show behind this and focus on the important stuff.

  • @Controller is used for web controllers where the logic involves selecting a "view", like an HTML page.
  • @RestController ties the method return value to the response's body. This makes it perfect for creating RESTful web services.