Spring、Spring MVC、MyBatis、shiro整合配置

一、web.xml的配置

web.xml是整个项目最重要的配置文件。本文主要针对配置内容,相关路径不对请自行更正。

1、配置spring容器:


<context-param>
        <param-name>contextConfigLocation</param-name>
        <!-- 配置文件路径,也可使用classpath:spring/spring-*.xml形式 -->
        <param-value>WEB-INF/classes/spring/spring-*.xml</param-value>
</context-param>
<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

2、springMVC前端控制器(DispatcherServlet)。即配置springMVC容器:

<servlet>
      <servlet-name>spring</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <!-- ContextconfigLocation配置springmvc加载的配置文件适配器、处理映射器等-->
          <param-name>contextConfigLocation</param-name>
          <param-value>WEB-INF/classes/spring/springmvc.xml</param-value>
      </init-param>
</servlet>
<servlet-mapping>
      <servlet-name>spring</servlet-name>
      <!-- 
          1、.action,访问以.action结尾的  由DispatcherServlet进行解析
          2、/,所有访问都由DispatcherServlet进行解析
       -->
      <url-pattern>/</url-pattern>
</servlet-mapping>

3、综合其它配置的完整配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
	http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">
	
	<!--以下配置的加载顺序:先 ServletContext>>context-param>>listener>>filter>>servlet>> spring-->
	<!-- 错误拦截 -->
	<error-page>
		<error-code>404</error-code>
		<location>/error404.jsp</location>
	</error-page>
	<error-page>
		<error-code>500</error-code>
		<location>/error500.jsp</location>
	</error-page>

	<!-- 加载spring容器 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring/spring-*.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- 字符编码过滤器,注意,此段编码设置必须在所有filter的前面,否则过滤器有可能不起作用。-->
	<filter>
		<filter-name>CharacterEncoding</filter-name>
			<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
			<init-param>
				<param-name>encoding</param-name>
				<param-value>UTF-8</param-value>
			</init-param>
			<init-param>
				<param-name>forceEncoding</param-name>
				<param-value>true</param-value>
			</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- shiro过滤器 -->
	<filter>
		<filter-name>shiroFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<init-param>
			<param-name>targetFilterLifecycle</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>shiroFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<!-- springMVC分配器 -->
	<servlet>
		<servlet-name>springMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springMVC-config.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springMVC</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<!-- 欢迎页 -->
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

       Spring容器的启动是先于SpringMVC容器的,所以spring容器是不知道springMVC容器的存在的。也就是说父spring容器无法使用子springMVC容器的bean。但是,子springMVC容器在初始化时,就能得到父spring容器的存在,子容器可以使用父容器的bean。在找controller时,默认是不会从父容器中找的,所以扫描controller时要在子容器中进行。

        扫描包中注解时,要避免spring容器和springMVC容器两个的重复扫描,否则会出现意想不到的错误。

二、springMVC-config.xml的配置

此文件在springMVC容器中读取。重点配置视图解析器、静态资源处理、扫描相关controller的包,其它内容看注释。

<?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: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-4.3.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-4.3.xsd">

<!-- 配置SpringMVC -->
	
	<!-- 1.开启SpringMVC注解模式 -->
	<!-- 简化配置:
		(1)自动注册DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter
		(2)提供一些列:数据绑定,数字和日期的format @NumberFormat, @DateTimeFormat, xml,json默认读写支持
	-->
	<mvc:annotation-driven></mvc:annotation-driven>
    
    <!-- @ResponseBody注解支持 用来返回JSON数据 适用ajax请求 依赖jackson包 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/html; charset=UTF-8</value>
                            <value>application/json;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/html; charset=UTF-8</value>
                            <value>application/json;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
            </list>
        </property>
    </bean>
	
	<!-- 定义/的视图映射 -->
	<mvc:view-controller path="/" view-name="index"/>
	
	<!-- 2.静态资源默认servlet配置
		(1)加入对静态资源的处理:js,gif,png
		(2)允许使用"/"做整体映射
	-->
	<mvc:default-servlet-handler/>
	<!-- <mvc:resources mapping="/resources/**" location="/resources/" /> -->
    	
	<!-- 3.配置ViewResolver -->
	<!-- FreeMarker配置 -->
	<bean id="freeMarkerConfigurer"
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath" value=""></property>
        <property name="defaultEncoding" value="utf-8" />
        <property name="freemarkerSettings">
            <props>
                <prop key="template_update_delay">1</prop>
                <prop key="locale">zh_CN</prop>
                <prop key="datetime_format">yyyy-MM-dd</prop>
                <prop key="date_format">yyyy-MM-dd</prop>
                <prop key="number_format">#.##</prop>
            </props>
        </property>
    </bean>
    <!-- FreeMarker视图解析 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
    	<property name="viewClass" value="com.yf.basic.MyFreeMarkerView" /> 
        <property name="prefix" value="/WEB-INF/views/"/>  
        <property name="suffix" value=".html"/>  
        <property name="contentType" value="text/html; charset=UTF-8"/>
        <property name="exposeRequestAttributes" value="true" />
	    <property name="exposeSessionAttributes" value="true" />
	    <property name="exposeSpringMacroHelpers" value="true" />
	    <property name="requestContextAttribute" value="request" />
        <property name="order" value="0" />
    </bean>
    
    <!-- jsp视图解析 -->
	 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	 	<property name="prefix" value="/WEB-INF/jsp/" />
	 	<property name="suffix" value=".jsp" />
	 	<property name="order" value="1" />
	 </bean>
	 
	 <!-- 4.扫描web相关的bean -->
	 <context:component-scan base-package="com.yf.controller" />
</beans>

三、spring-dao.xml的配置。

此配置文件在spring容器加载时读取。主要配置数据访问层相关内容,配置数据库连接池,spring和mybatis整合配置,扫描mapper接口,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"
	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-4.3.xsd">
	<!-- 配置整合mybatis过程 -->
	<!-- 1.引入数据库相关参数的属性文件:-->
	<context:property-placeholder location="classpath:jdbc.properties" />

	<!-- 2.数据库连接池 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
		<!-- 配置连接池属性 -->
		<property name="driverClass" value="${jdbc.driver}" />
		<property name="jdbcUrl" value="${jdbc.url}" />
		<property name="user" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>

	<!-- 3.配置SqlSessionFactory对象 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 注入数据库连接池 -->
		<property name="dataSource" ref="dataSource" />
		<!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
		<property name="configLocation" value="classpath:mybatis-config.xml" />
		<!-- 扫描entity包 使用别名 -->
		<property name="typeAliasesPackage" value="com.yf.entity" />
		<!-- 扫描sql配置文件:mapper需要的xml文件 -->
		<property name="mapperLocations" value="classpath:mapper/*Mapper.xml" />
	</bean>

	<!-- 4.配置扫描mapper接口包,动态实现mapper接口,注入到spring容器中 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 注入sqlSessionFactory -->
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
		<!-- 给出需要扫描Dao接口包 -->
		<property name="basePackage" value="com.yf.mapper" />
	</bean>
</beans>

其中jdbc.properties文件的内容如下:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/ssm?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

四、spring-service.xml的配置。

此配置文件在spring容器加载时读取。主要配置业务逻辑层相关内容,配置要扫描的service包、事务控制。

<?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:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
	
	<!-- 扫描service包下所有使用注解的类型 -->
	<context:component-scan base-package="com.yf.service" />

	<!-- 配置事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<!-- 注入数据库连接池 -->
		<property name="dataSource" ref="dataSource" />
	</bean>

	<!-- 配置基于注解的声明式事务 -->
	<tx:annotation-driven transaction-manager="transactionManager" />
</beans>

五、spring-shiro.xml的配置。

此配置文件在spring容器加载时读取。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
       
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <property name="loginUrl" value="/loginForm/login"/>
        <property name="unauthorizedUrl" value="/loginForm/error" />
        <!-- 自定义多角色权限过滤器 -->
        <property name="filters">
			<map>			
				<entry key="roles">  
                    <bean class="com.yf.shiro.AnyRolesAuthorizationFilter" />  
                </entry>  
			</map>
		</property>
        <property name="filterChainDefinitions">
            <value>
            	/ =anon
            	/loginForm/error = anon
            	/loginForm/loginsubmit = anon
                /loginForm/login = anon
                /resources/** = anon
                /article/add =roles["1,2"]
                /logout = logout
                /** = authc
            </value>
        </property>
    </bean>
    
     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="myRealm"/>
        <property name="cacheManager" ref="cacheManager" />
    </bean>
    
    <bean id="myRealm" class="com.yf.shiro.MyRealm">
    	<property name="cacheManager" ref="cacheManager" /> 
    </bean>
    
    <!-- 用户授权信息Cache -->  
    <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" /> 
    
    <!-- 保证实现了Shiro内部lifecycle函数的bean执行 --> 
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
    
    <!-- AOP式方法级权限检查 -->  
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"  
        depends-on="lifecycleBeanPostProcessor">  
        <property name="proxyTargetClass" value="true" />  
    </bean>  

    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
        <property name="securityManager" ref="securityManager" />  
    </bean>  
</beans>

六、mybatis-config.xml的配置。

此配置文件在spring-dao.xml文件中读取。配置SqlSessionFactory对象时需要加载MyBaties全局配置文件:mybatis-config.xml。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<!-- 配置全局属性 -->
	<settings>
		<!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 -->
		<setting name="useGeneratedKeys" value="true" />

		<!-- 使用列别名替换列名 默认:true -->
		<setting name="useColumnLabel" value="true" />

		<!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} -->
		<setting name="mapUnderscoreToCamelCase" value="true" />
		
	</settings>
</configuration>

至此,spring+springMVC+mybatis+shiro框架配置基本完成。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值