码迷,mamicode.com
首页 > 编程语言 > 详细

Springmvc+Mybatis+shiro整合

时间:2018-05-18 14:14:17      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:事务   pass   异常   mode   XML   def   span   字符串   ISE   

Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码学和会话管理。使用Shiro的易于理解的API,您可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。

Shiro 主要分为来个部分就是认证和授权,在个人感觉来看就是查询数据库做相应的判断而已,Shiro只是一个框架而已,其中的内容需要自己的去构建,前后是自己的,中间是Shiro帮我们去搭建和配置好的

 

项目:创建maven项目web项目

技术分享图片

 

pomx.xml配置好需要的jar包

<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>
  <groupId>com</groupId>
  <artifactId>oabyddh</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>oabyddh Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
     <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.1</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.39</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.21</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>c3p0</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.1.2</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.35</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>5.0.0</version>
    </dependency>
    <dependency>
          <groupId>org.apache.shiro</groupId>
          <artifactId>shiro-core</artifactId>
          <version>1.2.2</version>
      </dependency>
    
    <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-web -->
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-web</artifactId>
        <version>1.2.6</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring -->
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-spring</artifactId>
        <version>1.2.6</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.15</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.15</version>
    </dependency>
    <dependency>
        <groupId>org.csource</groupId>
        <artifactId>fastdfs_client</artifactId>
        <version>1.20</version>
    </dependency>  
  </dependencies>
  <build>
    <finalName>oabyddh</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <target>1.6</target>
                <source>1.6</source>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>
    </plugins>
  </build>
      <properties>  
        <!-- 文件拷贝时的编码 -->  
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>  
        <!-- 编译时的编码 -->  
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>  
    </properties>
</project>

web.xml配置文件:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>oa system</display-name>
    
    <!-- 定义全局变量 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:resources/spring.xml</param-value>
    </context-param>

    <!-- 编码过滤器 -->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <!-- 定义局部变量,只针对该filter有效 -->
        <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>
    
    <!-- shiro权限过滤器 -->
    <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <!-- 如果设置"targetFilterLifecycle"为true,则spring来管理Filter.init()和Filter.destroy();若为false,则这两个方法失效。 -->
        <!-- 这里的Filter是一个代理,交由spring的bean来处理 -->
        <init-param>
            <param-name>targetFilterLifecycle</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
   <!--  此监听器出用于主要为了解决java.beans.Introspector导致内存泄漏的问题. This listener should
        be registered as the first one in web.xml, before any application listeners
        such as Spring‘s ContextLoaderListener. -->
   <!--  此监听器应该配置在web.xml中与Spring相关监听器中的第一个位置(也要在ContextLoaderListener的前面) -->
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>
    
    <!-- 启动Web容器时,自动装配ApplicationContext的配置信息 -->
    <!-- ContextLoaderListener会读取这些XML文件并产生 WebApplicationContext对象,然后将这个对象放置在ServletContext的属性里 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <!-- 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:resources/springmvc.xml</param-value>
        </init-param>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <!-- 是拦截所有请求,包括视图解析后跳转的.jsp页面,/则不会拦截视图解析后的.jsp页面 -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

springmvc.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.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 />
    
    <!-- 配置Controller扫描的包 -->
    <context:component-scan base-package="com.oabyddh.controller" />
    
    <!-- 配置静态资源 -->
    <mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
    <mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
    
    <!-- 异常处理 -->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.Exception">/exceptions</prop>
            </props>
        </property>
        <property name="defaultErrorView" value="exceptions.jsp"></property>
        <property name="exceptionAttribute" value="ex"></property>
    </bean>
    
    <!-- 类型转换器,默认springmvc只有基本类型转换器 -->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
            <!--配置fastjson-->
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=utf-8</value>
                        <value>application/json</value>
                    </list>
                </property>
                <property name="features">
                    <list>
                        <value>WriteMapNullValue</value>
                        <value>QuoteFieldNames</value>
                    </list>
                </property>
            </bean>
            
        </mvc:message-converters>
    </mvc:annotation-driven> 
    
    <!-- jsp视图层配置 -->
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    
    <!-- 上传文件拦截,设置最大上传文件大小   10M=10*1024*1024(B)=10485760 bytes -->  
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="maxUploadSize" value="10485760" />
        <property name="maxInMemorySize" value="50000"></property>
        <property name="defaultEncoding" value="UTF-8"></property>  
    </bean>
    
    <!-- 开启shiro注解-->
    <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:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        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/aop
                            http://www.springframework.org/schema/aop/spring-aop.xsd
                            http://www.springframework.org/schema/tx
                            http://www.springframework.org/schema/tx/spring-tx.xsd">

<!-- 注册JDBC属性文件 -->
<context:property-placeholder location="classpath:resources/oabyddh.properties"/>

<!-- 注册数据源:C3P0数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="${jdbc.driverClass}" />
    <property name="jdbcUrl" value="${jdbc.url}" />
    <property name="user" value="${jdbc.user}" />
    <property name="password" value="${jdbc.password}" />
</bean>

<!-- 注册SqlSessionFactory的bean 该bean来完成对mybatis的注入 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!-- 数据源 -->
    <property name="dataSource" ref="dataSource" />
    <!-- 指定mybatis主配置文件 -->
    <property name="configLocation" value="classpath:resources/mybatis.xml" />
    <!-- 指定Mapper文件所在包 -->
    <property name="mapperLocations" value="classpath:com/oabyddh/dao/impl/*.xml"></property>
    <!-- 配置分页插件 -->
     <property name="plugins">
        <array>
          <bean class="com.github.pagehelper.PageInterceptor">
            <property name="properties">
              <value>
                       helperDialect=mysql
              </value>
            </property>
          </bean>
        </array>
      </property>
</bean>

<!-- 注册Mapper扫描配置器, 改bean来完成把mapper转换成接口的注入 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    <!-- 指定接口和mapper所在的包,当接口和mapper在同一个包内,可以自动扫描到mapper.xml,
        如果不在,需要在sqlSessionFactory中配置mapperLocations来指定mapper所在的位置-->
    <property name="basePackage" value="com.oabyddh.dao" />
</bean>

<!-- 注册事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

<!-- 注册事务通知 -->
<tx:annotation-driven transaction-manager="transactionManager"/>

<!-- 扫描注入spring注解 -->
<context:component-scan base-package="com.oabyddh.service" />

<!-- 引入其他配置文件 -->
<import resource="classpath:resources/spring-shiro.xml"/>

</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"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">

    <!-- 对应于web.xml中配置的那个shiroFilter -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!-- Shiro的核心安全接口,这个属性是必须的 -->
        <property name="securityManager" ref="securityManager"/>
        <!-- 要求登录时的链接(登录页面地址),非必须的属性,默认会自动寻找Web工程根目录下的"/login.jsp"页面 
            相当于添加了/login.jsp=anon
        -->
        <property name="loginUrl" value="/login.jsp"/>
        <!-- 登录成功后要跳转的连接(本例中此属性用不到,因为登录成功后的处理逻辑在LoginController里硬编码) -->
        <!-- <property name="successUrl" value="/" ></property> -->
        <!-- 用户访问未对其授权的资源时,所显示的连接 -->
        <property name="unauthorizedUrl" value="/error/unauthorized"/>
        <property name="filterChainDefinitions">
            <value>
                <!-- 
                    /build/**=anon
                    /**=authc
                 -->
                 /css/**=anon
                 /js/**=anon
                 /fonts/**=anon
                 /auth/**=anon
                /**=authc
            </value>
        </property>

    </bean>


    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"></bean>
    <!-- 数据库保存的密码是使用MD5算法加密的,所以这里需要配置一个密码匹配对象 -->
    <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.Md5CredentialsMatcher"></bean>
    <!-- 缓存管理 -->
    <bean id="shiroCacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager"></bean>

    <!-- 使用Shiro自带的JdbcRealm类,指定密码匹配所需要用到的加密对象,指定存储用户、角色、权限许可的数据源及相关查询语句  -->
    <bean id="jdbcRealm" class="org.apache.shiro.realm.jdbc.JdbcRealm">
        <property name="credentialsMatcher" ref="credentialsMatcher"></property>
        <!-- permissionsLookupEnabled默认false。False时不会使用permissionsQuery的SQL去查询权限资源。设置为true才会去执行 -->
        <property name="permissionsLookupEnabled" value="true"></property>
        <property name="dataSource" ref="dataSource"></property>
        <property name="authenticationQuery"
                  value="select password from tbl_users where userName = ?"></property>
        <property name="userRolesQuery"
                  value="select ug.groupName from tbl_userGroups ug, tbl_users u where u.groupId = ug.id and u.userName = ?"></property>
        <property name="permissionsQuery"
                  value="select p.perName from tbl_userGroups ug, tbl_permissions p, tbl_groupMapPermission gmp 
                           where ug.id = gmp.groupId and p.id = gmp.permissionId and ug.groupName = ?"></property>
    </bean>

    <!-- Shiro安全管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="jdbcRealm"></property>
        <property name="cacheManager" ref="shiroCacheManager"></property>
    </bean>

    <!-- Shiro的注解配置一定要放在spring-mvc中 -->

</beans>

oabyddh.properties

#\u6570\u636E\u5E93\u914D\u7F6E
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://172.16.27.11:3306/oabyddh?useUnicode=true&characterEncoding=utf8
jdbc.user=oabyddh
jdbc.password=oabyddh

#\u56FE\u7247\u5B58\u50A8\u914D\u7F6E
imgServerAddress=172.16.27.11
imgServerPort=80

mybatis.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="logImpl" value="STDOUT_LOGGING" />
    </settings>
    
    <!-- POJO对象的所在包,可以解析为别名 -->
    <typeAliases>
        <package name="com.oabyddh.model"/>
    </typeAliases>
    
    <mappers>
        <package name="com.oabyddh.dao.impl"/>
    </mappers>
    


</configuration>

AuthController.java

package com.oabyddh.controller;


import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.oabyddh.model.User;

/**
 * 平台 登陆,退出控制器
 * @author djoker
 *
 */
@Controller
@RequestMapping("/auth")
public class AuthController {

    /**
     * 登陆控制器
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping("/ajaxLogin")
        public Object login(User user) {
        Map<String, String> res = new HashMap<String, String>();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            if(subject.isAuthenticated()) {
                res.put("code", "0");
                res.put("msg", "登陆成功!");
            }
        }catch(Exception e) {
            res.put("code", "-1");
            res.put("msg", e.getMessage());
        }
        return res;
    }
    
    /**
     * 退出控制器
     * @return
     */
    @ResponseBody
    @RequestMapping("/ajaxLogout")
    public Object logout() {
        SecurityUtils.getSubject().logout();
        Map<String, String> res = new HashMap<String, String>();
        res.put("code", "0");
        res.put("msg", "退出成功!");
        return res;
    }
}

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ page isELIgnored="false"%>    
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    
%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <base href="<%=basePath %>">
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <div class="row">
            <form>
                <div class="col-md-4 col-md-offset-4">
                    <div class="form-group">
                        <label>账号:</label>
                        <input class="form-control" name="userName" id="userName" type="text">
                    </div>
                    <div class="form-group">
                        <label>密码:</label>
                        <input class="form-control" name="password" id="password" type="password">
                    </div>
                    <div>
                        <button class="btn btn-primary" type="button" onclick="login()">登陆</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
    
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="js/oabyddh.js"></script>
</body>
</html>

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>   
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %> 
<%@ page isELIgnored="false"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    
%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <base href="<%=basePath %>">
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
</head>
<body>
<div>
    <button type="button" class="btn btn-primary" onclick="logout()">退出</button>
</div>
<!-- 只有具有管理员查看权限才可以看到 -->
<shiro:hasPermission name="manager:view">
    <div>
        你好管理员,属于manager组成员
    </div>
</shiro:hasPermission>
<!-- 认证成功后才可以看到 -->
<shiro:authenticated>
    <div>
        新的一天,工作努力,工作加油!
    </div>
</shiro:authenticated>
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="js/oabyddh.js"></script>
</body>
</html>

数据库:

-- MySQL dump 10.13  Distrib 5.1.73, for redhat-linux-gnu (x86_64)
--
-- Host: localhost    Database: oabyddh
-- ------------------------------------------------------
-- Server version       5.1.73

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE=‘+00:00‘ */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE=‘NO_AUTO_VALUE_ON_ZERO‘ */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `tbl_groupMapPermission`
--

DROP TABLE IF EXISTS `tbl_groupMapPermission`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tbl_groupMapPermission` (
  `id` int(255) NOT NULL AUTO_INCREMENT,
  `groupId` int(255) DEFAULT NULL,
  `permissionId` int(255) DEFAULT NULL,
  `state` int(255) DEFAULT 0,
  PRIMARY KEY (`id`),
  KEY `groupId` (`groupId`),
  KEY `permissionId` (`permissionId`),
  CONSTRAINT `tbl_groupMapPermission_ibfk_1` FOREIGN KEY (`groupId`) REFERENCES `tbl_userGroups` (`id`),
  CONSTRAINT `tbl_groupMapPermission_ibfk_2` FOREIGN KEY (`permissionId`) REFERENCES `tbl_permissions` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `tbl_groupMapPermission`
--

LOCK TABLES `tbl_groupMapPermission` WRITE;
/*!40000 ALTER TABLE `tbl_groupMapPermission` DISABLE KEYS */;
INSERT INTO `tbl_groupMapPermission` VALUES (1,1,1,0),(2,1,2,0),(3,1,3,0),(4,1,4,0);
/*!40000 ALTER TABLE `tbl_groupMapPermission` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `tbl_permissions`
--

DROP TABLE IF EXISTS `tbl_permissions`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tbl_permissions` (
  `id` int(255) NOT NULL AUTO_INCREMENT,
  `perName` varchar(255) NOT NULL,
  `description` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `perName` (`perName`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `tbl_permissions`
--

LOCK TABLES `tbl_permissions` WRITE;
/*!40000 ALTER TABLE `tbl_permissions` DISABLE KEYS */;
INSERT INTO `tbl_permissions` VALUES (1,manager:view,查看管理员权限),(2,manager:add,添加管理员权限),(3,manager:del,删除管理员权限),(4,m
anager:modify,修改管理员权限);
/*!40000 ALTER TABLE `tbl_permissions` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `tbl_userGroups`
--

DROP TABLE IF EXISTS `tbl_userGroups`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tbl_userGroups` (
  `id` int(255) NOT NULL AUTO_INCREMENT,
  `groupName` varchar(255) NOT NULL,
  `description` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `groupName` (`groupName`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `tbl_userGroups`
--

LOCK TABLES `tbl_userGroups` WRITE;
/*!40000 ALTER TABLE `tbl_userGroups` DISABLE KEYS */;
INSERT INTO `tbl_userGroups` VALUES (1,管理员组,管理员所属组),(2,经理组,经理职务所属组),(3,主管组,主管职务所属组),(4,财务组,财务职务
所属组),(5,人事组,人事职务所属组),(6,员工组,普通员工所属组);
/*!40000 ALTER TABLE `tbl_userGroups` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `tbl_users`
--

DROP TABLE IF EXISTS `tbl_users`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tbl_users` (
  `id` int(255) NOT NULL AUTO_INCREMENT,
  `userName` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `realName` varchar(255) NOT NULL,
  `groupId` int(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `userName` (`userName`),
  KEY `groupId` (`groupId`),
  CONSTRAINT `tbl_users_ibfk_1` FOREIGN KEY (`groupId`) REFERENCES `tbl_userGroups` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `tbl_users`
--

LOCK TABLES `tbl_users` WRITE;
/*!40000 ALTER TABLE `tbl_users` DISABLE KEYS */;
INSERT INTO `tbl_users` VALUES (1,admin,9003d1df22eb4d3820015070385194c8,超级管理员,1),(2,user01,9003d1df22eb4d3820015070385194c8,张楚岚
,6);
/*!40000 ALTER TABLE `tbl_users` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2018-04-28 23:18:42

使用到的js文件:oabyddh.js

/*************登陆与退出***************/
//登陆平台
function login(){
    var userName = $("#userName").val();
    var password = $("#password").val();
    $.ajax({
        url:"auth/ajaxLogin",
        type:"post",
        dataType:‘json‘,
        //不使用contentType,data可以是对象,如果使用contentType,则data只能是字符串
        //contentType:"application/json; charset=utf-8",
        data:{userName: userName, password: password},
        success:function(data){
            var code = data.code;
            if(code == 0){
                location.href="index.jsp";
            }else{
                alert(data.msg);
            }
            
        },
        error:function(){
            
        }
    });
}

//退出平台
function logout(){
    $.ajax({
        url:"auth/ajaxLogout",
        type:"post",
        dataType:"json",
        success:function(data){
            var code = data.code;
            location.href="login.jsp";
        },
        error:function(){
            
        }
    });
}

 

测试效果:

使用admin pwd登陆时可以看到管理员信息,而使用user01 pwd登陆,看不到管理员才能看到的信息

Springmvc+Mybatis+shiro整合

标签:事务   pass   异常   mode   XML   def   span   字符串   ISE   

原文地址:https://www.cnblogs.com/djoker/p/9055500.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!