標籤:dap def dha oca div model simple 使用 beans
- 根據controller的name名稱來映射尋找controller:BeanNameUrlHandlerMapping (預設)
1.1開啟該映射:預設是開啟的<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>1.2定義bean的name屬性:<bean id="helloController" name="/hello1.do" class="com.controller.HelloController"></bean>1.3介面訪問URL:與bean的name屬性值一致http://localhost:5080/springmvc/hello1.do
- 根據URL來映射尋找controller:推薦使用:SimpleUrlHandlerMapping
2.1開啟該映射:<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"><property name="mappings"><props><prop key="/hello2.do">HelloController</prop></props></property></bean>2.2定義bean:<bean id="helloController" class="com.controller.HelloController"></bean>2.3介面URL訪問:與prop的key屬性值一致http://localhost:5080/springmvc/hello2.do優點:將controller定義與映射分離開,耦合性低。
- 根據controller的類名來映射尋找controller: ControllerClassNameHandlerMapping
3.1開啟類名映射處理器:<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"></bean>3.2定義bean<bean id="hello3Controller" class="com.controller.Hello2Controller"></bean>3.3介面URL訪問:與bean的id屬性值無關。http://localhost:5080/springmvc/hello2.do 正確http://localhost:5080/springmvc/hello2Controller.do 正確http://localhost:5080/springmvc/hello21111.do 正確http://localhost:5080/springmvc/hello3.do 錯誤注意點:使用類名來訪問一個Controller,
- 使用註解來映射尋找controller: DefaultAnnotationHandlerMapping
DefaultAnnotationHandlerMapping和RequestMappingHandlerMapping都是處理requestMapping的註解,
前者以廢棄,不建議使用,後者用來代替前者
1.開啟註解掃描組件:作用:當我載入設定檔時,到我們指定的包下掃描(讀取)Java檔案,尋找標註註解的地方(介面,類,方法或者其他),進行完成初始化。<beans><!--配置掃描使用註解的包路徑 --><context:component-scan base-package="com"></context:component-scan><!--開啟springMVC註解 --><bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean> </beans>2.在類上標記:@Controller 聲明該類是一個springMVC Controller3.在方法上使用:@RequestMapping("/login") 聲明該方法處理哪一個請求eg:@Controllerpublic class Login {@RequestMapping("/login")public ModelAndView login(){ModelAndView mv = new ModelAndView(); mv.setViewName("login"); return mv;}}
springMVC--4種映射處理器handlerMapping