转载自:(http://blog.csdn.net/madun/article/details/7660582)
使用CoC,惯例优先原则(convention over configuration)的方式来配置SpringMVC可以帮我们声明Controller的时候省下很多功夫。
只要我们的Controller是以XXXController的方式命名的话就可以使用到CoC带来的好处。
例如,对于普通的Controller(非MultiActionController),CoC帮我们做以下的映射:
HomeController映射到/home*请求URL
DisplayShoppingCartController映射到/displayshoppingcart*请求URL
注意:应该映射成使用全部小写的请求URL,一定要注意 。
对与MultiActionController,映射规则如下:
例如,我有一个UserInfoController,里面有一个方法valid,那么就会映射成/userinfo/valid.do(.do对应你设置的dispatcher-servlet的url-pattern)。
使用CoC带来的好处就是我们不需要再忍受必须先定义它们,然后还要维护冗长的SimpleUrlHandlerMapping的枯燥。
规则就这么多,以下是配置。
1.dispatcher-servlet.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
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 ">
<!-- 扫描该包下的使用注解的Controller -->
<context:component-scan base-package="com.wangBeat.module"/>
<!-- 使用处理器映射器 -->
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<!-- 处理器适配器 -->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<!-- 这个类用于Spring MVC视图解析 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"/>
</beans>
2.编写我们的Controller:
package com.wangBeat.module;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
@org.springframework.stereotype.Controller
public class simple2Controller implements Controller {
@RequestMapping
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView ModelAndView=new ModelAndView();
ModelAndView.addObject("param", "wzs");
ModelAndView.setViewName("/WEB-INF/test.jsp");
return ModelAndView;
}
}
这里我们可以看到,我们只需要在class前面声明@Controller,方法前面声明@RequestMapping就可以了,其他什么都不需要自己配置,最后使用地址/simple2/handleRequest.action就可以调用了。
另外,如果你想对这些使用 ControllerClassNameHandlerMapping 匹配的Controller使用拦截器的话,只需要为 ControllerClassNameHandlerMapping bean 的 interceptors list 注入拦截器就可以了:
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<property name="interceptors">
<list>
<ref bean="myInter" />
</list>
</property>
</bean>
<bean id="myInter" class="test.MyInter" />