需要三个包spring2.5.jar spring-webmvc-2.5.jar commons-logging.jar
在web.xml添加spring监听器和DispatcherServlet:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
这里是处理后缀名为htm的servlet请求
然后在WEB-INF目录下创建dispatcher-servlet.xml,红色部分要与servlet-name配置的值一样。
配置如下:
<?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:p="http://www.springframework.org/schema/p "
xmlns:aop="http://www.springframework.org/schema/aop "
xmlns:tx="http://www.springframework.org/schema/tx "
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd ">
<!-- 这里配置ParameterMethodNameResolver -->
<bean id="paraMethodResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="paramName" value="servlet"/>
</bean>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<!-- 这里配置拦截器 -->
<!--
<property name="interceptors">
<list>
<ref bean="LogInter" />
</list>
</property>
-->
<property name="mappings">
<props>
<!-- 这里配置我们的Controller -->
<prop key="/MyController.htm">myController</prop>
</props>
</property>
</bean>
<!-- 这里配置Controller的bean,引用了前面定义的ParameterMethodNameResolver -->
<bean name="myController" class="controller.MyController">
<property name="methodNameResolver" ref="paraMethodResolver" />
</bean>
</beans>
我喜欢使用springmvc的MultiActionController,因为可以一个控制器多个请求啊。
public class MyController extends MultiActionController{
public ModelAndView welcome(HttpServletRequest request,
HttpServletResponse response){
//这里写业务逻辑代码,用法就与Servlet一样
//最return一个ModelAndView,这里返回/WEB-INF/jsp/welcomPage.jsp
return new ModelAndView("welcomePage");
}
}
当我们在浏览器输入http://localhost:8080/springmvcTest/ MyController.htm?servlet=welcome就会转到/WEB-INF/jsp/welcomPage.jsp
如果需要用到拦截器,那么只需要继承HandlerInterceptorAdapter类就可以。
要自己实现两个方法:
//调用Controller之前拦截
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception
//调用Controller之后拦截
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView modelAndView) throws Exception {
转帖地址:http://hi.baidu.com/coolcat_police/item/f46b43cacd7ee4300931c6d1