spring mvc将所有的请求都经过一个servlet控制器-DispatcherServlet,这个servlet的工作就是将一个客户端的request请求分发给不同的springmvc控制器,既然是一个控制器Servlet就需要在web.xml中配置。
<servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
配置完以后,所有的请求都会被拦截到,根据上边的配置,DispatchServlet会载入springmvc-servlet.xml,在springmvc-servlet.xml中,我们需要配置springmvc的controller默认使用的是哪个视图,需要声明一个视图解析器bean:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean>
为了成功在代码中使用注解代码,需要在此xml中指定注解功能开启
<mvc:annotation-driven />
指定控制器所在的包
<context:component-scan base-package="com.springmvc.controller"/>
加上标签的声明,springmvc-servlet.xml的形式为:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <mvc:annotation-driven /> <context:component-scan base-package="com.springmvc.controller"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> </beans>