Spring+SpringMVC+Mybatis+Shiro框架整合-yellowcong

来源:互联网 发布:淘宝商城女童装秋装 编辑:程序博客网 时间:2024/06/05 08:38

说实话,Spring+Spring+Mybatis整合过程中,我觉得最坑的一点是1、Maven的项目聚合与继承,编译的jdk版本不一致
2、还有一个问题是项目是WEb2.5,Maven的生成框架是WEB2.3的问题,Maven之Cannot change version of project facet Dynamic Web Module to 2.5.-yellowcong
3、单独点击Junit单元测试,找不到配置文件的问题(这个是父类Junit 的scope的设置为Test,导致子类打死都不能 spring.xml和类,发现maven项目目录下的test-classes连个 类都没有,问题就处在scope上)
4、Mybatis的坑,返回的集合类型数据,多条集合类型是ResultMap,单条model是ResultType

项目地址:https://gitee.com/yellowcong/shior-dmeo.git

项目目录结构

这个目录有一个parent(普通j2ee的项目),用于父类的pom.xml配置文件,同时打包的时候,直接使用父类项目打包,这样也挺方便的,分包的策略,可以快速定位错误位置

web目录,是所有的目录操作,没有将web目录拆分成 util,dao,service这三个子包,只做了一个web的

这里写图片描述

parent项目pom.xml

parent项目是一个简单的j2ee项目,没有web的类容
父类项目相当于将整个项目的环境都配置了,这样子类项目自需要继承父类项目,就可以完成环境的配置

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <description>父类依赖类</description>    <groupId>yellowcong</groupId>    <artifactId>parent</artifactId>    <version>0.0.1-SNAPSHOT</version>    <packaging>pom</packaging>    <name>parent</name>    <url>http://maven.apache.org</url>    <!-- 配置子类的项目 -->     <modules>          <module>../web</module>       </modules>     <!-- 配置国内比较快的 阿里云的Maven仓库 -->    <repositories>        <repository>            <id>aliyunmaven</id>            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>        </repository>    </repositories>    <!-- 共用的配置说明,比如spring版本, 项目名称, jdk版本等 -->    <properties>        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>        <spring.version>4.2.5.RELEASE</spring.version>    </properties>    <dependencies>        <!-- 导入jsp -->        <dependency>            <groupId>javax.servlet.jsp</groupId>            <artifactId>jsp-api</artifactId>            <version>2.2.1-b03</version>            <scope>provided</scope>        </dependency>        <!-- 导入servlet -->        <dependency>            <groupId>javax.servlet</groupId>            <artifactId>servlet-api</artifactId>            <version>2.4</version>            <scope>provided</scope>        </dependency>        <dependency>            <groupId>javax.servlet</groupId>            <artifactId>jstl</artifactId>            <version>1.2</version>        </dependency>        <!-- Spring  BEGIN-->        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-core</artifactId>            <version>${spring.version}</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-context</artifactId>            <version>${spring.version}</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-beans</artifactId>            <version>${spring.version}</version>        </dependency>        <!-- 导入Spring的orm -->        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-orm</artifactId>            <version>${spring.version}</version>        </dependency>        <!-- Slf4j -->        <dependency>            <groupId>org.slf4j</groupId>            <artifactId>slf4j-api</artifactId>            <version>1.7.5</version>        </dependency>        <!-- 配置切面 -->        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-aop</artifactId>            <version>${spring.version}</version>        </dependency>        <!---aspectj 面向切向 -->        <dependency>            <groupId>aspectj</groupId>            <artifactId>aspectjrt</artifactId>            <version>1.5.3</version>        </dependency>        <dependency>            <groupId>org.aspectj</groupId>            <artifactId>aspectjweaver</artifactId>            <version>1.8.5</version>        </dependency>        <!-- Spring需要的注解 -->        <dependency>            <groupId>javax.annotation</groupId>            <artifactId>javax.annotation-api</artifactId>            <version>1.2</version>        </dependency>        <!-- Spring 的测试类 -->        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-test</artifactId>            <version>${spring.version}</version>        </dependency>        <!-- Spring  END-->        <!-- 配置Spring mvc -->        <dependency>          <groupId>org.springframework</groupId>          <artifactId>spring-webmvc</artifactId>          <version>${spring.version}</version>        </dependency>        <!-- 文件上传 -->        <dependency>            <groupId>commons-fileupload</groupId>            <artifactId>commons-fileupload</artifactId>            <version>1.2.2</version>        </dependency>        <dependency>            <groupId>commons-io</groupId>            <artifactId>commons-io</artifactId>            <version>2.4</version>        </dependency>         <!-- 测试类 -->        <dependency>            <groupId>junit</groupId>            <artifactId>junit</artifactId>            <version>4.10</version>            <scope>test</scope>        </dependency>        <!-- JSON解析 -->        <dependency>            <groupId>org.codehaus.jackson</groupId>            <artifactId>jackson-mapper-asl</artifactId>            <version>1.9.11</version>        </dependency>        <!-- 日志 -->        <dependency>            <groupId>log4j</groupId>            <artifactId>log4j</artifactId>            <version>1.2.16</version>        </dependency>        <!-- 添加Shiro权限控制 -->        <dependency>            <groupId>org.apache.shiro</groupId>            <artifactId>shiro-all</artifactId>            <version>1.2.5</version>        </dependency>        <!-- ################################################ -->        <!-- ########### 数据库配置 BEGIN     ###################-->        <!-- ################################################ -->        <!-- mybatis -->        <dependency>            <groupId>org.mybatis</groupId>            <artifactId>mybatis</artifactId>            <version>3.1.0</version>        </dependency>        <dependency>            <groupId>org.mybatis</groupId>            <artifactId>mybatis-spring</artifactId>            <version>1.1.1</version>        </dependency>        <!-- 数据库连接池 -->        <dependency>            <groupId>com.alibaba</groupId>            <artifactId>druid</artifactId>            <version>1.0.18</version>        </dependency>        <!-- 数据库驱动 -->        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>            <version>5.1.21</version>        </dependency>        <!-- ################################################ -->        <!-- ########### 数据库配置 END       ###################-->        <!-- ################################################ -->    </dependencies>    <build>        <plugins>             <plugin>                  <artifactId>maven-compiler-plugin</artifactId>                  <version>2.3.2</version>                  <configuration>                      <source>1.7</source>                      <target>1.7</target>                      <encoding>UTF-8</encoding>                  </configuration>              </plugin>          </plugins>    </build></project>

web 的pom.xml

子类web的pom配置,没有太多东西,只需要继承父类就可以了, 同时也要和父类一样将packing的方式改为pom,才可以

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">    <modelVersion>4.0.0</modelVersion>    <artifactId>web</artifactId>    <packaging>war</packaging>    <name>test Maven Webapp</name>    <url>http://maven.apache.org</url>    <!-- 共用的配置说明,比如spring版本, 项目名称, jdk版本等 -->    <properties>        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>        <spring.version>4.2.5.RELEASE</spring.version>    </properties>    <parent>        <groupId>yellowcong</groupId>        <artifactId>parent</artifactId>        <version>0.0.1-SNAPSHOT</version>         <relativePath>../parent/pom.xml</relativePath>    </parent>    <build>        <finalName>test</finalName>        <plugins>             <plugin>                  <artifactId>maven-compiler-plugin</artifactId>                  <version>2.3.2</version>                  <configuration>                      <source>1.7</source>                      <target>1.7</target>                      <encoding>UTF-8</encoding>                  </configuration>              </plugin>          </plugins>    </build></project>

web的配置文件

web配置中主要有 jdbc,mybatis,shiro的配置操作

这里写图片描述

jdbc配置

jdbc.properties数据库的连接配置,我这个是本地的数据库,使用的是阿里的druid,常用的数据库连接池有dbcp,c3p0,druid

#Defined jdbc configjdbc.driverClassName=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql:///yellowcongjdbc.username=rootjdbc.password=rootjdbc.initialSize=3 jdbc.minIdle=2jdbc.maxActive=60jdbc.maxWait=60000jdbc.timeBetweenEvictionRunsMillis=60000jdbc.minEvictableIdleTimeMillis=30000jdbc.validationQuery=SELECT 'x'jdbc.testWhileIdle=truejdbc.testOnBorrow=falsejdbc.testOnReturn=falsejdbc.poolPreparedStatements=truejdbc.maxPoolPreparedStatementPerConnectionSize=20jdbc.removeAbandoned=truejdbc.removeAbandonedTimeout=120jdbc.logAbandoned=falsejdbc.filters=stat

spring-mybatis.xml

mybatis配置文件,配置了事务操作

<?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:aop="http://www.springframework.org/schema/aop"    xmlns:tx="http://www.springframework.org/schema/tx"    xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"            >    <!-- 自动扫描(自动注入) -->    <context:annotation-config/>    <context:component-scan base-package="com.yellowcong.service.impl.*"/>    <!-- 配置日志输出 -->    <bean id="log-filter" class="com.alibaba.druid.filter.logging.Log4jFilter">        <property name="resultSetLogEnabled" value="true" />    </bean>    <!-- 配置数据源 -->    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">        <property name="driverClassName" value="${jdbc.driverClassName}" />         <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 name="minIdle" value="${jdbc.minIdle}" />         <property name="maxActive" value="${jdbc.maxActive}" />         <property name="maxWait" value="${jdbc.maxWait}" />         <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" />         <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}" />         <property name="validationQuery" value="${jdbc.validationQuery}" />         <property name="testWhileIdle" value="${jdbc.testWhileIdle}" />         <property name="testOnBorrow" value="${jdbc.testOnBorrow}" />         <property name="testOnReturn" value="${jdbc.testOnReturn}" />         <property name="removeAbandoned" value="${jdbc.removeAbandoned}" />         <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" />        <!--  <property name="logAbandoned" value="${jdbc.logAbandoned}" />  -->        <property name="filters" value="${jdbc.filters}" />        <!-- 关闭abanded连接时输出错误日志 -->        <property name="logAbandoned" value="true" />        <property name="proxyFilters">            <list>                <ref bean="log-filter"/>            </list>        </property>        <!-- 监控数据库 -->        <!-- <property name="filters" value="stat" /> --><!--        <property name="filters" value="mergeStat" />-->    </bean>    <!-- 配置Session factory -->    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">        <property name="dataSource" ref="dataSource" />        <property name="configLocation" value="classpath:mybatis-config.xml"/>        <property name="mapperLocations"  >            <list>                <value>classpath*:com/yellowcong/mapper/*.xml</value>            </list>        </property>    </bean>    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">        <constructor-arg index="0" ref="sqlSessionFactory" />    </bean>    <!--这个是定义的一个Base的操作类 -->    <!-- <bean id="baseMybatisDao" class="com.yellowcong.core.mybatis.BaseMybatisDao" >        <property name="sqlSessionFactory" ref="sqlSessionFactory" />    </bean>  -->    <!-- 定义用户的Dao的位置 -->    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">        <!-- 定义我们需要查找的Dao的位置 -->         <property name="basePackage" value="com.yellowcong.dao" />        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />    </bean>    <!-- 事物管理 -->     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">         <property name="dataSource" ref="dataSource" />     </bean>    <tx:advice id="txAdvice" transaction-manager="transactionManager">        <tx:attributes>            <tx:method name="publish*" />            <tx:method name="save*" />            <tx:method name="add*" />            <tx:method name="update*" />            <tx:method name="insert*" />            <tx:method name="create*" />            <tx:method name="del*" />            <tx:method name="load*" />            <tx:method name="init*" />            <tx:method name="*"  read-only="true"/>        </tx:attributes>    </tx:advice>    <!-- AOP配置,设定织入的位置-->     <aop:config>        <aop:pointcut id="dbPointcut"            expression="execution(public * com.yellowcong.*.service.impl.*.*(..))" />        <aop:advisor advice-ref="txAdvice" pointcut-ref="dbPointcut" />    </aop:config></beans>

mybatis-config.xml

上面的spring-mybatis.xml,调用到了这个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>            <setting name="defaultExecutorType" value="REUSE" />  </settings>  <typeAliases>  </typeAliases> <!--  <mappers>    <mapper resource="mapper/StudentMapper.xml"/> </mappers>    <plugins>         <plugin interceptor="net.wenyifan.common.mybatis.plugin.PageInterceptor">           </plugin>      </plugins>    --></configuration>

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: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-3.1.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-3.1.xsd">    <mvc:default-servlet-handler/>    <!-- 通过Annotation 来控制Controller -->    <mvc:annotation-driven></mvc:annotation-driven>    <context:component-scan base-package="com.yellowcong"></context:component-scan>    <!-- 将静态文件夹制定到某个特别的文件夹中统一处理        ** 表示的是文件夹中的子文件夹中的所有类容        其中location 需要两个 正斜杠     -->    <mvc:resources location="/resources/" mapping="/resources/**"/>        <!-- 配置权限拦截器 -->        <!-- 当我们的数据访问到 amdin的时候,就会直接调用admin对象 --> <!--   <mvc:interceptors>        <mvc:interceptor>            <mvc:mapping path="/user/**"/>            <mvc:mapping path="/role/**"/>            <mvc:mapping path="/group/**"/>            <mvc:mapping path="/attachment/**"/>            <mvc:mapping path="/reply/**"/>            <mvc:mapping path="/tabel/**"/>            <mvc:mapping path="/image/**"/>            <mvc:mapping path="/info/**"/>            <mvc:mapping path="/login/stu"/>            <mvc:mapping path="/admin/**"/>            <bean class="com.yellowcong.interceptor.UserInterceptor"/>        </mvc:interceptor>    </mvc:interceptors>  -->     <!-- 设定访问的名称 和对应的Servlet -->        <!-- 配置Multipart,只有设定了才能完成文件上传 -->    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">        <property name="maxUploadSize" value="5000000"></property>    </bean>    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <!-- 3.0.5后默认加上了jstl的属性配置.这个就是默认的配置 -->        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>        <!-- 设定前缀 -->        <property name="prefix" value="/WEB-INF/jsp/"></property>        <!-- 设定后缀 -->        <property name="suffix" value=".jsp"></property>    </bean>    <!-- 配置全局异常 -->    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">        <property name="exceptionMappings">            <props>            <!--                 <prop key="com.yellowcong.exception.UserException">error</prop>                <prop key="java.lang.RuntimeExceptio">error</prop>                <prop key="com.yellowcong.exception.ChannelException">error</prop>                <prop key="com.yellowcong.exception.GroupException">error</prop>                <prop key="com.yellowcong.exception.RoleException">error</prop>             -->            </props>        </property>    </bean></beans>

spring-shiro.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:aop="http://www.springframework.org/schema/aop"    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"    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/tx http://www.springframework.org/schema/tx/spring-tx.xsd       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">    <description>== Shiro Components ==</description>    <!-- 会话Session ID生成器 -->    <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"/>    <!-- 安全管理器 -->    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">          <!--领域(Realm)-->        <property name="realm" ref="sampleRealm" />          <!-- 缓存管理器 -->        <property name="cacheManager" ref="cacheManager" />      </bean>      <!-- 授权 认证 ,自己定义的,领域(Realm),shiro需要配置一个领域(Realm),以便我们可以访问用户-->    <bean id="sampleRealm" class=" com.yellowcong.shior.realm.SampleRealm" ></bean>    <!-- 给予shior的内存缓存系统 -->    <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />      <!-- Shior的过滤器配置 -->    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">         <property name="securityManager" ref="securityManager" />         <!-- 用户登录地址 -->       <property name="loginUrl" value="/user/login" />         <!-- 登录成功 -->       <property name="successUrl" value="/user/list" />         <!-- 未授权的钦奎光 -->       <property name="unauthorizedUrl" value="/user/error" />         <property name="filterChainDefinitions">             <value>                  <!-- 设置访问用户list页面需要授权操作 -->               /user/list = authc                /user/error =  anon               /users/user/login = anon                <!-- 配置js和img这些静态资源被任何人访问到 -->               /resources/img/** = anon                 /resources/js/** = anon             </value>         </property>     </bean>    <!-- Shiro生命周期处理器-->   <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>

spring.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"    xmlns:mvc="http://www.springframework.org/schema/mvc"    xsi:schemaLocation="    http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd    http://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context-4.0.xsd    http://www.springframework.org/schema/mvc    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd    ">    <!-- 自动扫描(自动注入) -->    <context:annotation-config/>    <context:component-scan base-package="com.yellowcong.*"/>    <!-- 引入属性文件 -->     <bean id="propertyConfigurer"        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">        <!-- 除了支持配置的properties文件外,还支持系统属性        SYSTEM_PROPERTIES_MODE_OVERRIDE   //系统属性可以被覆盖        SYSTEM_PROPERTIES_MODE_NEVER  //不检测系统属性        SYSTEM_PROPERTIES_MODE_FALLBACK  // 这个是默认的配置        -->        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />         <!-- 里面配置的properties文件如果找不到的话,就可以忽略找不到的文件 -->        <property name="ignoreResourceNotFound" value="true" />        <property name="locations">            <list>                <value>classpath:jdbc.properties</value>            </list>        </property>    </bean>     <!--导入mybatis的配置-->    <import resource="spring-mybatis.xml"/>    <import resource="spring-shiro.xml"/></beans>

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"    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"    id="WebApp_ID" version="2.5"> <display-name>spring_springmvc_hibernate</display-name>    <welcome-file-list>        <welcome-file>index.jsp</welcome-file>    </welcome-file-list>    <!-- Spring mvc -->    <servlet>        <servlet-name>config</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <!-- 配置Spring mvc,如果不配置,就会默认在wWEB-INF/config-servlet.xml -->        <init-param>            <description>spring mvc 配置文件</description>            <param-name>contextConfigLocation</param-name>            <param-value>classpath:spring-mvc.xml</param-value>        </init-param>        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>config</servlet-name>        <url-pattern>/</url-pattern>    </servlet-mapping>    <!-- 设定shiro过滤器 -->    <filter>        <filter-name>shiroFilter</filter-name>        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>    </filter>    <filter-mapping>        <filter-name>shiroFilter</filter-name>        <url-pattern>/*</url-pattern>        <dispatcher>REQUEST</dispatcher>        <dispatcher>FORWARD</dispatcher>        <dispatcher>INCLUDE</dispatcher>        <dispatcher>ERROR</dispatcher>    </filter-mapping>    <!-- 设定字符编码 -->    <filter>        <filter-name>CharacterFilter</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>    </filter>    <filter-mapping>        <filter-name>CharacterFilter</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>    <!-- spring的监听器,可以通过上下文来获取参数 -->    <listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>    <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>classpath:spring.xml</param-value>    </context-param></web-app>

代码

com.yellowcong.controller –>控制层
com.yellowcong.dao –>dao层
com.yellowcong.mapper
com.yellowcong.service –>service层
com.yellowcong.service.impl
com.yellowcong.model –>模型层
com.yellowcong.shiro.realm –>shiro的验证

这里写图片描述

Shiro验证

SampleRealm 这个类需要继承AuthorizingRealm 这个类,然后复写里面的方法

package com.yellowcong.shior.realm;import java.util.HashSet;import java.util.Set;import javax.annotation.Resource;import org.apache.shiro.authc.AuthenticationException;import org.apache.shiro.authc.AuthenticationInfo;import org.apache.shiro.authc.AuthenticationToken;import org.apache.shiro.authc.SimpleAuthenticationInfo;import org.apache.shiro.authc.UsernamePasswordToken;import org.apache.shiro.authz.AuthorizationInfo;import org.apache.shiro.authz.SimpleAuthorizationInfo;import org.apache.shiro.realm.AuthorizingRealm;import org.apache.shiro.subject.PrincipalCollection;import org.springframework.beans.factory.annotation.Autowired;import com.yellowcong.model.User;import com.yellowcong.service.UserService;/** * 创建日期:2017年9月23日 <br/> * 创建用户:yellowcong <br/> * 功能描述:用于授权操作 */public class SampleRealm extends AuthorizingRealm {    /**     * 没有写后台,直接写死的用户和用户密码     */    private static final String USER_NAME = "yellowcong";    private static final String USER_PASSWORD = "yellowcong";    private UserService userService;    @Resource(name="userService")    public void setUserService(UserService userService) {        this.userService = userService;    }    /**     * 用户授权     */    @Override    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection paramPrincipalCollection) {        SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();        // 根据用户ID查询角色(role),放入到Authorization里。        Set<String> roles = new HashSet<String>(); // 添加用户角色        roles.add("administrator");        info.setRoles(roles);        // 根据用户ID查询权限(permission),放入到Authorization里。        Set<String> permissions = new HashSet<String>(); // 添加权限        permissions.add("/role/**");        info.setStringPermissions(permissions);        return info;    }    /**     * 认证,用户登录     */    @Override    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken paramAuthenticationToken) throws AuthenticationException {        UsernamePasswordToken token = (UsernamePasswordToken) paramAuthenticationToken;        User user = userService.login(token.getUsername());        // token返回的是一个数组,将char类型转化为String类型        String pswDate = new String(token.getPassword());        // 当用户名 和密码都满足的情况,返回登陆信息        if(user.getPassword().equals(pswDate)){            return new SimpleAuthenticationInfo(token.getUsername(), token.getPassword(), getName());        } else {            // 当没有用户的时候,抛出异常            throw new AuthenticationException();        }    }}

UserMapper

用户对象操作,

package com.yellowcong.dao;import java.util.List;import com.yellowcong.model.User;/** * 创建日期:2017年9月23日 <br/> * 创建用户:yellowcong <br/> * 功能描述:用户的操作类 */public interface UserMapper {    /**     *      * 创建日期:2017年9月23日<br/>     * 创建用户:yellowcong<br/>     * 功能描述:来获取用户大于 这个 age的人     * @param age     * @return     */    List<User> list();    Integer getCount();    /**     * 用户登录操作     * 创建日期:2017年9月23日<br/>     * 创建用户:yellowcong<br/>     * 功能描述:     * @param username 用户名     * @return     */    User login(String username);}

UserMapper.xml

写这个UserMapper的时候,一定要注意
1、namespace 是否和类名对应 上了
2、resultMap 返回填的是 id属性(User)
3、resultType 填写的才是type属性(com.yellowcong.model.User)

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" ><mapper namespace="com.yellowcong.dao.UserMapper" >    <!-- 配置映射字段 -->      <resultMap type="com.yellowcong.model.User" id="User">          <result property="id" column="id"/>          <result property="age" column="age"/>          <result property="nickname" column="nick_name"/>          <result property="password" column="password"/>          <result property="username" column="user_name"/>      </resultMap>      <!-- 获取用户列表     resultMap 这个是返回的是ResultMap的id,    -->    <select id="list" resultMap="User">        SELECT * FROM YELLOWCONG_USERS     </select>    <!-- 用户登录操作 -->    <!-- resultType 返回的是 type -->    <select id="login" parameterType="java.lang.String" resultType="com.yellowcong.model.User">        SELECT USER FROM YELLOWCONG_USERS  WHERE user_name = #{username}    </select>    <!-- 查询用户条数 -->    <select id="getCount" resultType="java.lang.Integer">        SELECT COUNT(id) FROM YELLOWCONG_USERS     </select></mapper>

余下的,就没有必要贴了,就是实体类了,我把项目丢在码云上,大家可以下载查看

原创粉丝点击