Shiro整合SpringMVC简单实例(一)

一、基于xml配置的shiro整合SpringMVC

项目结构图

所需要导入的包

 

1.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"
    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">

     <context:component-scan base-package="cn.lch"/>

</beans>

 

2.SpringMVC配置文件

<?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/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">
       
        <!-- 打开注解驱动 -->
     <mvc:annotation-driven />
     <!-- 放开静态资源拦截 -->
     <mvc:default-servlet-handler/>
     
     <!-- 视图解释器 -->
     <mvc:view-resolvers>
        <mvc:jsp prefix="/WEB-INF/views/" suffix=".jsp"/>
     </mvc:view-resolvers>

</beans>

 

 3.Shiro整合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.xsd">

    <!-- 第一步:指定Shiro的拦截过滤器 -->
    <bean name="shiroFilterBean" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
         <!-- 指定securityManager容器对象 -->
         <property name="securityManager" ref="securityManager"></property>
         <!-- 设置拦截器链 
                 说明:Shiro提供了很多拦截器,用于不同场景的路径拦截,我们就在拦截器链中设置拦截请求的场景
                 anon :指定不拦截的路径,如登录页面请求
                 /user/toLogin = anon
                 authc : 必须需要校验的路径
                 logout :注销拦截器。如果路径类型为logout就是一个注销路径
         -->
         <property name="filterChainDefinitions">
              <value>
                   /user/toLogin = anon
                   /logout = logout
                   /** = authc
              </value>
         </property>
         <!-- 配置自定义拦截器 -->
         <!-- 指定登录的请求路径 -->
         <property name="loginUrl" value="/user/login" />
         <!-- 指定登录成功后跳转的路径 -->
         <property name="successUrl" value="/index" />
    </bean>
    
    <!-- 第二步:创建securityManager对象 -->
    <bean name="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realms" ref="shiroRealm"></property>
    </bean>
    
    <!-- 第三步:创建自定义realm对象 -->
    <bean name="shiroRealm" class="cn.lch.realm.ShiroRealm">
        <property name="credentialsMatcher">
           <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
              <property name="hashAlgorithmName" value="md5"></property>
              <property name="hashIterations" value="1"></property>
           </bean>
        </property>
    </bean>
</beans>

 

4.shiroRealm的配置

package cn.lch.realm;

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

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.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

public class ShiroRealm extends AuthorizingRealm{
    
    /**
     * 用于权限校验的方法
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("-权限校验-");
        if ("admin".equals(token.getPrincipal())) {
            Map<String, Object> user=new HashMap<>();
            user.put("user_name", "admin");
            user.put("user_password", "879b208f9aa10d8a87d93c77b89419bc");
            user.put("user_id", 1);
            ByteSource salt = ByteSource.Util.bytes("abcd123");
            return new SimpleAuthenticationInfo(user,user.get("user_password"),salt,this.getName());
        }
        return null;
    }

    /**
     * 用于权限授予的方法
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addRole("role_admin");
        info.addStringPermission("user:add");
        info.addStringPermission("user:list");
        return info;
    }
}

 

5.跳转页面的配置

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
     <!-- 如果通过了校验,跳转到首页 -->
     <shiro:authenticated>
        <jsp:forward page="/index"></jsp:forward>
     </shiro:authenticated>
      <!-- 如果不通过了校验,跳转到登录页面-->
     <shiro:notAuthenticated>
        <jsp:forward page="/user/toLogin"></jsp:forward>
     </shiro:notAuthenticated>
</body>
</html>

6.Controller层的处理代码

package cn.lch.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {
    @RequestMapping(value="/index")
    public String toIndex() {
        return "index";
    }
}
package cn.lch.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.annotation.SessionScope;

@Controller
@SessionScope
@RequestMapping(value="/user")
public class UserController {
    
    @RequestMapping(value = "/toLogin")
    public String toLogin() {
        System.out.println("跳转到用户登录");
        return "login";
    }
    
    @RequestMapping(value = "/login")
    public String login(HttpServletRequest request) {
        System.out.println("用户登录");
        //需求:登录失败要返回出现信息
        Object shiroLoginFailure = request.getAttribute("shiroLoginFailure");
        System.out.println(shiroLoginFailure);
        if("org.apache.shiro.authc.UnknownAccountException".equals(shiroLoginFailure)) {
            request.setAttribute("user_login_msg", "用户名错误");
        }else if ("org.apache.shiro.authc.IncorrectCredentialsException".equals(shiroLoginFailure)) {
            request.setAttribute("user_login_msg", "密码错误");
        }
        return "login";
    }

}

 

7.登录页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
   <form action="${pageContext.request.contextPath }/user/login" method="post">
   ${requestScope.user_login_msg }<br/>
         用户名:<input name="username" type="text"><br/>
       密码:<input name="password" type="password"><br/>
       <input type="submit" value="登录">
   </form>
</body>
</html>

8.主页

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
  主页  <a href="${pageContext.request.contextPath }/logout">退出</a><br/>
  <shiro:hasPermission name="user:list">
  <!-- 如果有user:list权限才显示  用户列表 -->
   <a href="#"> 用户列表</a><br/>
 </shiro:hasPermission>
  <shiro:hasPermission name="user:add">
 <!-- 如果有user:add权限才显示  用户增加 -->
 <a href="#">  用户增加</a><br/>
 </shiro:hasPermission>
 <shiro:hasPermission name="user:edit">
   <!-- 如果有user:edit权限才显示  用户编辑 -->
  <a href="#"> 用户编辑</a><br/>
  </shiro:hasPermission>
</body>
</html>

 

运行结果(从跳转页面index.xml运行)

 

posted @ 2019-05-12 21:16  茁壮成长的菜鸡  阅读(1463)  评论(0编辑  收藏  举报