BeanNameUrlHandlerMapping maps requests by controller bean names. The handler treats the bean's name as the URI to match against the incoming request.
This handler mapping is registered by default. For it to work, all we have to do is give the controller bean a name that starts with "/".
BeanNameUrlHandlerMapping hands the matched bean straight to DispatcherServlet with no method-level resolution, so it needs a HandlerAdapter that can invoke a plain bean directly. Its paired adapter, SimpleControllerHandlerAdapter (registered by default), only invokes beans implementing org.springframework.web.servlet.mvc.Controller via its handleRequest(HttpServletRequest, HttpServletResponse) method — so the bean must implement that interface to be invocable.
Example
Registering the controller with a name
package com.logicbig.example;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@EnableWebMvc
@Configuration
public class AppConfig {
@Bean("/example")
public MyController exampleController () {
return new MyController();
}
}
The controller
package com.logicbig.example;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class MyController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response)
throws Exception {
response.getWriter().write("response from /example");
return null;
}
}
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 /example
Note that if we use @ComponentScan instead of @Bean factory methods, we instead have to supply the path via the 'value' element — for example, @Component("/example") — or via the JSR-330 @Named("/example") annotation on the controller class.
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
|