Spring MVC筆記(八) 控制器類名稱處理映射
阿新 • • 發佈:2017-12-29
return https bst protect urn location utf-8 r.java 訪問
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,結果如下所示:
Spring MVC筆記(八) 控制器類名稱處理映射