This example demonstrates how to use an implementation of the Controller interface. The implementation is invoked by SimpleControllerHandlerAdapter (an HandlerAdapter strategy, registered by default). We will also map the requested URL to our controller using BeanNameUrlHandlerMapping (check out the HandlerMapping tutorial).
Example
Implementing Controller
package com.logicbig.example;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
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:
package com.logicbig.example;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.mvc.Controller;
@EnableWebMvc
@Configuration
public class AppConfig {
@Bean(name = "/example")
public Controller simpleControllerHandler () {
return new MySimpleControllerHandler();
}
}
Note that BeanNameUrlHandlerMapping is registered by default when using @EnableWebMvc. All we have to do is use a bean name starting with a '/'; this name will be used as the URI. Our MySimpleControllerHandler#handleRequest method is then invoked without any further configuration, since the corresponding SimpleControllerHandlerAdapter is registered by default too.
To try examples, run embedded Jetty (configured in pom.xml of example project below):
mvn jetty:run
Output
 $ curl -s "http://localhost:8080/example" response from MySimpleControllerHandler, uri: /example
Example ProjectDependencies and Technologies Used: - spring-webmvc 7.0.6 (Spring Web MVC)
Version Compatibility: 3.2.9.RELEASE - 7.0.6 Version compatibilities of spring-webmvc with this example: Versions in green have been tested.
- jakarta.servlet-api 6.1.0 (Jakarta Servlet API documentation)
- JDK 25
- Maven 3.9.11
|