基於Maven搭建SSM+Shiro框架
圖片上傳真的很累,想看圖的可以訪問我的個人博客:
http://www.bestrivenlf.cn/note/getNoteList
一、環境選擇
**開發工具:**Eclipse
**系統環境:**Windows 10
**框架選型:**Spring+SpringMVC+Mybatis+Shiro
二、搭建過程
1、創建Maven工程
至此,我們的一個空的maven工程就創建完畢!
2、引入依賴
首先我們來看看eclipse中的maven如何快速引入依賴:
其次我們再來看看這個框架需要哪些依賴以及他們的作用
名稱 | 解釋 |
---|---|
**spring-aop ** | 這個jar 文件包含在應用中使用Spring 的AOP 特性時所需的類和源碼級元數據支持。使用基於AOP 的Spring特性,如聲明型事務管理(Declarative Transaction Management),也要在應用裏包含這個jar包。外部依賴spring-core。 |
spring-aspects | 提供對AspectJ的支持 |
spring-context | 這個jar 文件爲Spring 核心提供了大量擴展。可以找到使用Spring ApplicationContext特性時所需的全部類,JDNI 所需的全部類,instrumentation組件以及校驗Validation 方面的相關類。外部依賴spring-beans |
spring-context-support | 包含支持緩存Cache(ehcache)、JCA、JMX、 郵件服務(Java Mail、COS Mail)、任務計劃Scheduling(Timer、Quartz)方面的類。外部依賴spring-context |
spring-core | 這個jar 文件包含Spring 框架基本的核心工具類。Spring 其它組件要都要使用到這個包裏的類,是其它組件的基本核心,當然你也可以在自己的應用系統中使用這些工具類。外部依賴Commons Logging, (Log4J)。 |
spring-test | 對Junit等測試框架的簡單封裝。 |
spring-web | 這個jar 文件包含Web 應用開發時,用到Spring 框架時所需的核心類,包括自動載入Web ApplicationContext 特性的類、Struts 與JSF 集成類、文件上傳的支持類、Filter 類和大量工具輔助類。 |
spring-webmvc | 這個jar 文件包含Spring MVC 框架相關的所有類。包括框架的Servlets,Web MVC框架,控制器和視圖支持。當然,如果你的應用使用了獨立的MVC 框架,則無需這個JAR 文件裏的任何類。外部依賴spring-web |
mybatis | mybatis核心包 |
mybatis-spring | mybatis和spring整合包 |
log4j | 日誌 |
slf4j-api | 日誌 |
slf4j-log4j | 日誌 |
mysql-connector-java | mysql驅動包 |
jstl | jstl標籤 |
servlet-api | servlet支持 |
java.servlet-api | servlet支持 |
commons-dbcp | 主流數據庫連接池 |
3、編寫配置文件
web.xml
-
編碼過濾器
-
很簡單很實用的一個過濾器,當前臺JSP頁面和JAVA代碼中使用了不同的字符集進行編碼的時候就會出現表單提交的數據或者上傳/下載中文名稱文件出現亂碼的問題,這就是解決這個問題的。
<!-- 首先編碼過濾器 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <!-- 然後配置過濾去攔截地址 這裏選則/*表示將所有資源數據編碼都進行過濾--> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
-
-
spring監聽器
-
用來在web容器啓動時候自動加載spring的配置文件中的信息,其默認會掃描WEB-INF下的applicationContext.xml配置文件,所以一般spring的默認配置文件都是這個名字,如果將其改名並放到classpath下的話就需要進行一個配置了。奇怪的是,這個變量的配置並不需要在固定的位置,我在SpringMVC的servlet中配置它的路徑也生效了。
<!-- 首先加載listener --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener>
-
-
SpringMVC的servlet
-
該配置用來配置springMVC的路徑解析器,即DispatcherServlet。配置後,相應請求將會被springMVC攔截到。
<!-- Spring MVC servlet --> <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:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <!-- 當然同樣的要配置servlet的mapping地址來說明它攔截哪些路徑 --> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <!-- 放棄了.do和.action的風格 --> <url-pattern>/</url-pattern> </servlet-mapping>
-
-
Shiro的過濾器配置
-
實際上這是Filter的一個代理,默認情況下,spring會到IOC容器中查找與<filter-name>一致的Bean,也可以通過<init-param>的<param-name>來指定Bean。
<filter> <filter-name>shiroFilter</filter-name> <filter-class> org.springframework.web.filter.DelegatingFilterProxy </filter-class> <init-param> <!-- 該值缺省爲false,表示生命週期由SpringApplicationContext管理,設置爲true則表示由ServletContainer管理 --> <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配置靜態資源不攔截
-
默認情況下SpringMVC按照/將會攔截所有請求,包括靜態資源的請求。這是不對的,所以通過springMVC中的配置mvc:default-servlet-handler來配置一個default的servlet的mapping來指定一些靜態資源後綴的請求可以不被攔截。
<!-- 過濾靜態資源,從而不攔截 --> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> <url-pattern>*.css</url-pattern> <url-pattern>/imgs/*</url-pattern> <url-pattern>*.jpg</url-pattern> <url-pattern>*.woff</url-pattern> <url-pattern>*.tff</url-pattern> </servlet-mapping>
-
-
spring配置文件讀取
<!-- spring配置文件加載 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-*.xml</param-value> </context-param>
spring-mvc.xml
配置完web.xml中內容以後既可以來配置spring了,在項目路徑下創建一個spring-mvc.xml的文件,這裏名字怎麼取都可以,因爲我們在web.xml裏面要配置contextConfigLocation的值,其對應了spring的配置文件路徑,so,隨便取吧,這裏我根據我的web.xml裏面配的值創建文件。
-
首先引入命名空間
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" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"
-
靜態資源處理器
-
還記得web.xml配置的靜態資源不攔截的servlet麼,沒錯,那裏配置的就是這裏的servlet的參數。
<!-- 靜態資源處理 --> <mvc:default-servlet-handler/>
-
-
開啓各種註解方式
<!-- 配置註解的映射器和適配器 --> <mvc:annotation-driven ></mvc:annotation-driven>
-
開啓註解以後得發現各種註解呀對吧。
<context:component-scan base-package="父包名" />
-
開啓SpringMVC的註解功能和映射功能
<!-- 啓動SpringMVC的註解功能,完成請求和註解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> </bean>
-
配置視圖解析器解析模板文件地址
<!-- 定義跳轉的文件的前後綴 ,視圖模式配置--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 這裏的配置我的理解是自動給後面action的方法return的字符串加上前綴和後綴,變成一個 可用的url地址 --> <property name="prefix" value="/" /> <property name="suffix" value=".jsp" /> </bean>
spring-mybatis.xml
接下來就是配置數據持久層框架的配置,其實就是一些數據源等等的配置
-
命名空間
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" 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"
-
配置數據源
-
這裏我們推薦將數據源信息寫在一個properties文件中,直接加載進xml
<!--加載信息文件--> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <!--配置數據源--> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 初始化連接大小 --> <property name="initialSize" value="${jdbc.initialSize}"></property> <!-- 連接池最大數量 --> <property name="maxActive" value="${jdbc.maxActive}"></property> <!-- 連接池最大空閒 --> <property name="maxIdle" value="${jdbc.maxIdle}"></property> <!-- 連接池最小空閒 --> <property name="minIdle" value="${jdbc.minIdle}"></property> <!-- 獲取連接最大等待時間 --> <property name="maxWait" value="${jdbc.maxWait}"></property> </bean>
-
-
配置DAO接口所在包
-
我們知道mybatis是使用接口和mapping文件映射的方式進行CRUD的,當然也可以直接註解啥的,但是一定會有一個DAO的包,所以,這個配置就是讓spring可以發現它
<!-- DAO接口所在包名,Spring會自動查找其下的類 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="InterfaceDao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean>
-
-
配置mapping
-
其實還是建議大家使用mapping的方式去寫sql,所以這裏需要再配置一下mapping的路徑發現,以及其他的配置,相當於這是mybaits和spring的整合入口。
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自動掃描mapping.xml文件 --> <property name="mapperLocations" value="classpath:mapping/*.xml"/> </bean>
-
-
配置事務管理
<!-- (事務管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean>
spring-shiro.xml
-
sercurityManager
<!-- securityManager --> <bean id ="securityManager" class ="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <!-- <property name ="realm" ref ="customRealm" />--> <!-- <property name ="cacheManager" ref ="cacheManager" /> --> <!--<property name ="sessionManager" ref ="sessionManager"/> --> </bean>
-
lifecycle
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
-
shiro註解
<bean id="defaultAdvisorAutoProxyCreator" class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"> <!-- 必須改爲true,即使用cglib方式爲Action創建代理對象。默認值爲false,使用JDK創建代理對象,會造成問題 --> <property name="proxyTargetClass" value="true"></property> </bean> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"></bean>
-
shiroFilter
<bean id ="shiroFilter" class = "org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name ="securityManager" ref ="securityManager" /> <!-- loginUrl認證提交地址,如果沒有認證將會請求此地址進行認證,請求地址將由formAuthenticationFilter進行表單認證 --> <property name ="loginUrl" value ="/user/login"/> <property name ="unauthorizedUrl" value ="/error"/> <!-- 過濾器鏈定義:從上向下順序執行,一般將/**放在最下邊 <property name ="filters"> <map> <entry key ="authc" value-ref ="formAuthenticationFilter"/> </map> </property>--> <property name ="filterChainDefinitions"> <value> <!-- 對靜態資源設置匿名訪問 --> </value> </property> </bean>
最後成功跑通:
三、測試項目
1、測試Spring框架
編寫Controller和Service進行Hello world測試:
-
TestController.java
package cn.bestrivenlf.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import cn.bestrivenlf.service.SayHelloService; @Controller @RequestMapping("Test") public class TestController { @Autowired private SayHelloService sayHelloService; @RequestMapping("hello") @ResponseBody public String sayHello() { return sayHelloService.sayHello(); } }
-
SayHelloService.java
package cn.bestrivenlf.service; public interface SayHelloService { public String sayHello(); }
-
SayHelloServiceImpl.java
package cn.bestrivenlf.serviceImpl; import org.springframework.stereotype.Service; import cn.bestrivenlf.service.SayHelloService; @Service public class SayHelloServiceImpl implements SayHelloService { public String sayHello() { // TODO Auto-generated method stub return "hello world"; } }
項目啓動後訪問 localhost:8080/SSM-Shiro/Test/hello返回如下:
2、測試shiro和mybatis框架
詳情見shiro筆記