ControllerClassNameHandlerMapping
类是基于约定的处理程序映射类,它将URL请求映射到配置中提到的控制器的名称。这个类接受控制器名称并将其转换为带有前导“/
”的小写形式。 例如HelloController
映射到URL: “/hello*
”。
创建springMVC工程:
ControllerNameHandlerMapping-servlet.xml配置如下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="com.bwy" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" /> <bean class="com.bwy.controller.HelloController" /> <bean class="com.bwy.controller.WelcomeController" /> </beans>
根据如上配置,对于/hello*.*的URL,DispatcherServlet会将请求转发到HelloController类;对于/welcome*.*的URL,DispatcherServlet会将请求转发到WelcomeController类。
HelloController.java
package com.bwy.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class HelloController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("hello"); model.addObject("message", "Hello World!"); return model; } }
WelcomeController.java
package com.bwy.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class WelcomeController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("welcome"); model.addObject("message", "welcome!"); return model; } }
运行tomcat,并访问http://localhost:8080/ControllerNameHandlerMapping/welcome2.d,结果如下所示: