Expert Spring MVC and Web Flow

(Dana P.) #1

Enforcing HTTP Methods


By default, an AbstractControllersupports HEAD, GET, and POST methods. If an HTTP
method is used for the request that is not in that list, a RequestMethodNotSupportedException
will be thrown. Note that the AbstractControllerdoesn’t define what should happen for each
type of request, but that other subclasses do make the distinction between different methods.
Setting the list of supported methods is often a good idea, enforcing the contract for a particu-
lar Controller. For example, some Controllers may display only read-only data, so setting its
supported methods to only GET enforces this usage.


■NoteThe HTTP RFC,http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html,defines each
method, its semantics, and its intended usage.


For example, you can set the supported methods via the bean definition (Listing 6-3) or
simply inside the Controller’s constructor (Listing 6-2).


■Tip Set the supported methods to only those that the Controllerspecifically supports. When a client
attempts a non-supported HTTP method, the correct error message and status will be generated, creating
helpful error messages. Plus, your Controllerwill be protected against incorrect (and potentially damag-
ing) usage.


Listing 6-2.Setting Supported Methods via the Constructor


public SimpleController() {
setSupportedMethods(new String[]{"GET","POST"});
}


Listing 6-3.Setting Supported Methods via the Bean Definition



class="com.apress.expertspringmvc.chap4.SimpleAbstractController">



These two examples are identical, so choose the method that best works for you.

CHAPTER 6 ■THE CONTROLLER MENAGERIE 119
Free download pdf