zoukankan      html  css  js  c++  java
  • shiro 基于springmvc中做登陆功能

    1.添加依赖

     1  <!-- shiro -->
     2         <dependency>
     3             <groupId>org.apache.shiro</groupId>
     4             <artifactId>shiro-core</artifactId>
     5             <version>1.4.0</version>
     6         </dependency>
     7         <dependency>
     8             <groupId>org.apache.shiro</groupId>
     9             <artifactId>shiro-spring</artifactId>
    10             <version>1.4.0</version>
    11         </dependency>
    View Code

     2.ApplicationContext-mvc.xml配置文件

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans"
     3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4        xmlns:mvc="http://www.springframework.org/schema/mvc"
     5        xmlns:context="http://www.springframework.org/schema/context"
     6        xmlns:task="http://www.springframework.org/schema/task"
     7        xsi:schemaLocation="http://www.springframework.org/schema/beans
     8         http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
     9         http://www.springframework.org/schema/mvc
    10         http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
    11         http://www.springframework.org/schema/context
    12         http://www.springframework.org/schema/context/spring-context-4.3.xsd
    13         http://www.springframework.org/schema/task
    14         http://www.springframework.org/schema/task/spring-task.xsd
    15         ">
    16 
    17     <mvc:annotation-driven/>
    18     <mvc:default-servlet-handler/>
    19 
    20     <context:component-scan base-package="com.wfd360.controller"/>
    21 
    22     <!-- 未认证或未授权时跳转必须在springmvc里面配,spring-shiro里的shirofilter配不生效 -->
    23     <bean   class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    24         <property name="exceptionMappings">
    25             <props>
    26                 <!--表示捕获的异常 -->
    27                 <prop key="org.apache.shiro.authz.UnauthorizedException">
    28                     <!--捕获该异常时跳转的路径 -->
    29                     /403
    30                 </prop>
    31                 <!--表示捕获的异常 -->
    32                 <prop key="org.apache.shiro.authz.UnauthenticatedException">
    33                     <!--捕获该异常时跳转的路径 -->
    34                     /403
    35                 </prop>
    36             </props>
    37         </property>
    38     </bean>
    39 
    40 
    41 
    42     <!-- 配置SpringMVC的视图解析器 -->
    43     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    44         <property name="prefix" value="/WEB-INF/jsp/"/>
    45         <property name="suffix" value=".jsp"/>
    46     </bean>
    47 
    48    <import resource="classpath:spring-shiro.xml"/>
    49 
    50 </beans>
    View Code

    3.spring-shiro.xml配置文件

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans"
     3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
     5     <!--开启shiro的注解-->
     6     <bean id="advisorAutoProxyCreator" class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator">
     7         <property name="proxyTargetClass" value="true"></property>
     8     </bean>
     9     <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"/>
    10     <!--注入自定义的Realm-->
    11     <bean id="customRealm" class="com.wfd360.shiro.CustomRealm"></bean>
    12     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    13         <property name="realm" ref="customRealm"></property>
    14     </bean>
    15 
    16     <!--配置ShiroFilter-->
    17     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    18         <property name="securityManager" ref="securityManager"></property>
    19         <!--登入页面-->
    20         <property name="loginUrl" value="/login.jsp"></property>
    21         <!--登入成功页面-->
    22         <property name="successUrl" value="/index.jsp"/>
    23        <!-- <property name="filters">
    24             <map>
    25                 &lt;!&ndash;退出过滤器&ndash;&gt;
    26                 <entry key="logout" value-ref="logoutFilter" />
    27             </map>
    28         </property>-->
    29         <!--URL的拦截-->
    30         <property name="filterChainDefinitions" >
    31             <value>
    32                 /share = authc
    33                 /logout = logout
    34             </value>
    35         </property>
    36 
    37     </bean>
    38     <!--自定义退出LogoutFilter-->
    39    <!-- <bean id="logoutFilter" class="com.test.filter.SystemLogoutFilter">
    40         <property name="redirectUrl" value="/login"/>
    41     </bean>-->
    42 </beans>
    View Code

    4.创建对象 CustomRealm.java

     1 package com.wfd360.shiro;
     2 
     3 import org.apache.shiro.authc.AuthenticationException;
     4 import org.apache.shiro.authc.AuthenticationInfo;
     5 import org.apache.shiro.authc.AuthenticationToken;
     6 import org.apache.shiro.authc.SimpleAuthenticationInfo;
     7 import org.apache.shiro.authz.AuthorizationInfo;
     8 import org.apache.shiro.authz.SimpleAuthorizationInfo;
     9 import org.apache.shiro.realm.AuthorizingRealm;
    10 import org.apache.shiro.subject.PrincipalCollection;
    11 
    12 import java.util.ArrayList;
    13 import java.util.List;
    14 
    15 /**
    16  * @author www.wfd360.com
    17  * @date 2018/2/26 14:05
    18  */
    19 public class CustomRealm extends AuthorizingRealm {
    20     /**
    21      * 授权
    22      * @param principalCollection
    23      * @return
    24      */
    25     @Override
    26     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    27         String userName = (String) principalCollection.getPrimaryPrincipal();
    28         List<String> permissionList=new ArrayList<String>();
    29         permissionList.add("user:add");
    30         permissionList.add("user:delete");
    31         if (userName.equals("zhou")) {
    32             permissionList.add("user:query");
    33         }
    34         SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
    35         info.addStringPermissions(permissionList);
    36         info.addRole("admin");
    37         return info;
    38     }
    39     /**
    40      * 认证
    41      * @param authenticationToken
    42      * @return
    43      * @throws AuthenticationException
    44      */
    45     @Override
    46     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    47         String userName = (String) authenticationToken.getPrincipal();
    48         if ("".equals(userName)) {
    49             return  null;
    50         }
    51         SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userName,"123456",this.getName());
    52         return info;
    53     }
    54 }
    View Code

    5.控制层ShiroController.java对象

     1 package com.wfd360.controller;
     2 
     3 import org.apache.shiro.SecurityUtils;
     4 import org.apache.shiro.authc.IncorrectCredentialsException;
     5 import org.apache.shiro.authc.UnknownAccountException;
     6 import org.apache.shiro.authc.UsernamePasswordToken;
     7 import org.apache.shiro.subject.Subject;
     8 import org.springframework.stereotype.Controller;
     9 import org.springframework.ui.Model;
    10 import org.springframework.web.bind.annotation.RequestMapping;
    11 import org.springframework.web.bind.annotation.RequestMethod;
    12 
    13 /**
    14  * Created by Administrator on 2018/10/29.
    15  */
    16 @Controller
    17 public class ShiroController {
    18 
    19     @RequestMapping(value = "/loginData", method = RequestMethod.POST)
    20     public String login(String userName, String passwd, Model model) {
    21         Subject subject = SecurityUtils.getSubject();
    22         UsernamePasswordToken token = new UsernamePasswordToken(userName, passwd);
    23         try {
    24             subject.login(token);
    25         } catch (UnknownAccountException e) {
    26             e.printStackTrace();
    27             model.addAttribute("userName", "用户名错误!");
    28             return "login";
    29         } catch (IncorrectCredentialsException e) {
    30             e.printStackTrace();
    31             model.addAttribute("passwd", "密码错误");
    32             return "login";
    33         }
    34         return "index";
    35     }
    36 
    37     @RequestMapping(value = "/index2")
    38     public String index() {
    39         System.out.println("------index-------");
    40         return "login";
    41     }
    42 }
    View Code

    6.登陆jsp页面login.jsp

     1 <%--
     2   Created by IntelliJ IDEA.
     3   User: Administrator
     4   Date: 2018/10/29
     5   Time: 11:51
     6   To change this template use File | Settings | File Templates.
     7 --%>
     8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
     9 <html>
    10 <head>
    11     <title>登陆界面</title>
    12 </head>
    13 <body>
    14 <h2>登陆界面</h2>
    15 <form action="/loginData" method="post">
    16     用户名:<input name="userName">
    17     密码:<input name="passwd">
    18     <input type="submit">
    19 </form>
    20 </body>
    21 </html>
    View Code

    7.web.xml配置

     1 <!-- shiro 过滤器 start -->
     2     <filter>
     3         <filter-name>shiroFilter</filter-name>
     4         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
     5         <!-- 设置true由servlet容器控制filter的生命周期 -->
     6         <init-param>
     7             <param-name>targetFilterLifecycle</param-name>
     8             <param-value>true</param-value>
     9         </init-param>
    10     </filter>
    11     <filter-mapping>
    12         <filter-name>shiroFilter</filter-name>
    13         <url-pattern>/*</url-pattern>
    14     </filter-mapping>
    15     <!-- shiro 过滤器 end -->
    View Code

    8.测试完成!

  • 相关阅读:
    DBA操作规范
    MySQL高可用之MHA
    Get MySQL这5个优化技巧,你将如虎添翼
    数据库的那些事
    Kubernetes
    nginx错误分析 `104: Connection reset by peer`
    kubernets资源预留
    kubernetes Pod亲和性
    kubernetes cpu限制参数说明
    zabbix 面板graph图上没有数据显示
  • 原文地址:https://www.cnblogs.com/newAndHui/p/9870383.html
Copyright © 2011-2022 走看看