springMVC处理流程如下:
通过配置DispacherServlet拦截指定的url,让后经HanddlerMapping来决定调用我自定义的Controller,在Controller中经过业务处理后,返回ModelAndView,包含数据模型和视图,经过ViewResovler视图解析器解析后,返回相应的结果。
实例如下:
①创建一个web工程,配置服务器,导入相关的jar包。
②配置web.xml文件。如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<description>指定配置文件路径</description>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<!-- 服务器启动时创建该servlet实例 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>testController.do</welcome-file>
</welcome-file-list>
</web-app>
Dispatcherservlet拦截以.do结尾的url,将welcome-file改成了testController.do,让服务器启动时,默认访问。
③编写Controller,如下:
//实现Controller接口或者继承AbstractController
public class TestController implements Controller{
@Override
public ModelAndView handleRequest(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
System.out.println("hahaah");
return new ModelAndView("hello");
}
}
④配置applicationContext.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
classpath:/org/springframework/beans/factory/xml/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
classpath:/org/springframework/context/config/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
classpath:/org/springframework/web/servlet/config/spring-mvc-3.2.xsd "> <!-- 根据我们请求的不同来选择调用相对应的controller -->
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="testController.do">testController</prop>
</props>
</property>
</bean> <bean id="testController" class="com.zhongqian.controller.TestController"></bean> <!-- 视图解析器,用来指定返回后的页面 .如返回aa,则对于的页面为/WEB-INF/jsp/aa.jsp -->
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<!-- 返回的视图模型数据需要经过jstl来处理 -->
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
⑤创建hello.jsp页面
项目结构如下:
运行项目效果:控制台打印hahaah
页面显示: