This example demonstrates how to use an implementation of Controller interface. The implementation will be invoked by SimpleControllerHandlerAdapter (an HandlerAdapter strategy, registered by default). Also, we will map the requested URL to our Controller by using BeanNameUrlHandlerMapping (check out HandlerMapping tutorial).
Example
Implementing Controller
public class MySimpleControllerHandler implements Controller {
@Override
public ModelAndView handleRequest (HttpServletRequest request,
HttpServletResponse response) throws Exception {
PrintWriter writer = response.getWriter();
writer.write("response from MySimpleControllerHandler, uri: "
+ request.getRequestURI());
return null;
}
}
Mapping URL
Using BeanNameUrlHandlerMapping strategy:
@EnableWebMvc
@Configuration
public class AppConfig {
@Bean(name = "/example")
public Controller simpleControllerHandler () {
return new MySimpleControllerHandler();
}
}
Note that BeanNameUrlHandlerMapping is registered by default when using @EnableMvc. All we have to do is to use bean name starting with a '/'; this name will be used as URI. Also our MySimpleControllerHandler#handleRequest will be invoked without any further configuration as corresponding SimpleControllerHandlerAdapter is registered by default as well.
To try examples, run embedded tomcat (configured in pom.xml of example project below):