为了实现配置文件与配置文件之间的 单一职责 原则,所以 spring-mvc 的配置单独开一个文件,这样就实现了,spring-context.xml 处理除controller层之外的其他类,而spring-mvc.xml 单独处理controller层
一、创建 spring-mvc.xml 文件
右击 resources
文件夹,点击 New
-> File
如图:
二、配置 spring-mvc.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"
xsi:schemaLocation="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
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<description>Spring MVC Configuration</description>
<!-- 加载配置属性文件 -->
<context:property-placeholder ignore-unresolvable="true" location="classpath:ssm.properties"/><!--这里需要单独创建一个文件,用来存放配置信息-->
<!-- 使用 Annotation 自动注册 Bean,只扫描 @Controller -->
<context:component-scan base-package="com.piglegend.ssm" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 默认的注解映射的支持 -->
<mvc:annotation-driven />
<!-- 定义视图文件解析 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="${web.view.prefix}"/>
<property name="suffix" value="${web.view.suffix}"/><!--${}绑定的是.properties文件下的配置-->
</bean>
<!-- 静态资源映射 -->
<mvc:resources mapping="/static/**" location="/static/" cache-period="31536000"/>
</beans>
三、创建配置文件(ssm.properties)
右击 resources
文件夹,点击 New
-> File
如图:
四、配置 ssm.properties
#============================#
#==== Framework settings ====#
#============================#
web.view.prefix=/WEB-INF/views/
web.view.suffix=.jsp
上面两个变量就是刚刚 spring-mvc.xml 中的两个变量,用来确定ViewResolver将要返回的视图全名
五、测试 spring-mvc 见我的下篇博客