SSM+Shiro写的一个简单的登录验证

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bpqdwo/article/details/74940348

项目结构

这里写图片描述

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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    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>Archetype Created Web Application</display-name>

    <!-- 读取spring配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:config/spring.xml;
            classpath*:config/spring-mybatis.xml
        </param-value>
    </context-param>
    <!-- 设计路径变量值 -->
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>springmvc.root</param-value>
    </context-param>
    <!-- Spring字符集过滤器 -->
    <filter>
        <filter-name>SpringEncodingFilter</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>SpringEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
 <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> 
 </filter-mapping>
    <!-- 日志记录 -->
    <context-param>
        <!-- 日志配置文件路径 -->
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:config/log4j.properties</param-value>
    </context-param>
    <context-param>
        <!-- 日志页面的刷新间隔 -->
        <param-name>log4jRefreshInterval</param-name>
        <param-value>6000</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- springMVC核心配置 -->
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:config/spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <!-- 错误跳转页面 -->
    <error-page>
        <!-- 路径不正确 -->
        <error-code>404</error-code>
        <location>/WEB-INF/errorpage/404.jsp</location>
    </error-page>
    <error-page>
        <!-- 没有访问权限,访问被禁止 -->
        <error-code>405</error-code>
        <location>/WEB-INF/errorpage/405.jsp</location>
    </error-page>
    <error-page>
        <!-- 内部错误 -->
        <error-code>500</error-code>
        <location>/WEB-INF/errorpage/500.jsp</location>
    </error-page>
</web-app>

spring配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    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-3.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd">
    <import resource="config/spring-mybatis.xml"/>
        <import resource="config/shiro-context.xml"/>
    <!-- 引入jdbc配置文件 -->
    <context:property-placeholder location="classpath:config/jdbc.properties" />

    <!-- 扫描文件(自动将servicec层注入) -->
    <context:component-scan base-package="com.deng.serviceImp" />
</beans>

spring-mvc配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p" 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/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <!-- 扫描controller(controller层注入) -->
    <context:component-scan base-package="com.deng.controller" />

    <!-- 避免IE在ajax请求时,返回json出现下载 -->
    <bean id="jacksonMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>

    <!-- 对模型视图添加前后缀 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/" p:suffix=".jsp" />
</beans>

mybatis-config配置

<?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>
<!-- 主要目的是 配置 命名空间 -->
    <!-- 命名空间,使用别名 -->
    <typeAliases >
    </typeAliases>
    <!-- 映射map mapper下的xml文件 -->
    <mappers>
        <!-- <mapper resource="mapper/UserMapper.xml"/> -->
    </mappers>
</configuration>

spring-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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util-3.2.xsd">

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
        init-method="init" destroy-method="close">
        <property name="driverClassName">
            <value>${jdbc_driverClassName}</value>
        </property>
        <property name="url">
            <value>${jdbc_url}</value>
        </property>
        <property name="username">
            <value>${jdbc_username}</value>
        </property>
        <property name="password">
            <value>${jdbc_password}</value>
        </property>
        <!-- 连接池最大使用连接数 -->
        <property name="maxActive">
            <value>20</value>
        </property>
        <!-- 初始化连接大小 -->
        <property name="initialSize">
            <value>1</value>
        </property>
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait">
            <value>60000</value>
        </property>
        <!-- 连接池最大空闲 -->
        <property name="maxIdle">
            <value>20</value>
        </property>
        <!-- 连接池最小空闲 -->
        <property name="minIdle">
            <value>3</value>
        </property>
        <!-- 自动清除无用连接 -->
        <property name="removeAbandoned">
            <value>true</value>
        </property>
        <!-- 清除无用连接的等待时间 -->
        <property name="removeAbandonedTimeout">
            <value>180</value>
        </property>
        <!-- 连接属性 -->
        <property name="connectionProperties">
            <value>clientEncoding=UTF-8</value>
        </property>
    </bean>

    <!-- mybatis文件配置,扫描所有mapper文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
        p:dataSource-ref="dataSource" p:configLocation="classpath:config/mybatis-config.xml"
        p:mapperLocations="classpath:com/deng/mapper/*.xml" /><!-- configLocation为mybatis属性 
        mapperLocations为所有mapper -->

    <!-- spring与mybatis整合配置,扫描所有dao -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
        p:basePackage="com.deng.dao" p:sqlSessionFactoryBeanName="sqlSessionFactory">

    </bean>
    <!-- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:basePackage="com.imt.general.dao" 
        p:sqlSessionFactoryBeanName="sqlSessionFactory"> </bean> -->
    <!-- 对数据源进行事务管理 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
        p:dataSource-ref="dataSource" />
</beans>

shiro-context配置


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    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-3.2.xsd
                http://www.springframework.org/schema/context
                 http://www.springframework.org/schema/context/spring-context-3.2.xsd
                http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
                 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager" />
        <property name="loginUrl" value="/login.jsp" />
        <property name="successUrl" value="/home" />
        <property name="unauthorizedUrl" value="/403.do" />
        <property name="filterChainDefinitions">
<!--
/admin/**=anon :无参,表示可匿名访问
/admin/user/**=authc :无参,表示需要认证才能访问
/admin/user/**=authcBasic :无参,表示需要httpBasic认证才能访问
/admin/user/**=ssl :无参,表示需要安全的URL请求,协议为https
/home=user :表示用户不一定需要通过认证,只要曾被 Shiro 记住过登录状态就可以正常发起 /home 请求
/edit=authc,perms[admin:edit]:表示用户必需已通过认证,并拥有 admin:edit 权限才可以正常发起 /edit 请求
/admin=authc,roles[admin] :表示用户必需已通过认证,并拥有 admin 角色才可以正常发起 /admin 请求
/admin/user/**=port[8081] :当请求的URL端口不是8081时,跳转到schemal://serverName:8081?queryString
/admin/user/**=rest[user] :根据请求方式来识别,相当于 /admins/user/**=perms[user:get]或perms[user:post] 等等
/admin**=roles["admin,guest"] :允许多个参数(逗号分隔),此时要全部通过才算通过,相当于hasAllRoles()
/admin**=perms["user:add:*,user:del:*"]:允许多个参数(逗号分隔),此时要全部通过才算通过,相当于isPermitedAll()

    -->
            <value>
                /login = anon <!--anon表示不需要认证就可以访问的     -->
                /home = authc, perms[/home]  <!--authc 表示需要认证才能访问的页面 perms 表示需要该权限才能访问的页面 -->
                /** = authc 
            </value>
        </property> 
    </bean>

    <bean id="myShiroRealm" class="com.deng.shiro.myReam">
        <!-- businessManager 用来实现用户名密码的查询 -->
        <!-- <property name="userService" ref="accountService" /> -->
    </bean>

    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="myShiroRealm"></property>
    </bean>

    <!-- <bean id="accountService" class="com.deng.service.userService"></bean> -->
    <!-- <bean id="shiroCacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> 
        <property name="cacheManager" ref="cacheManager" /> </bean> -->
</beans>

shiro验证登录验证类

package com.deng.shiro;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
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.deng.entity.User;
import com.deng.entity.UserRole;
import com.deng.service.userService;

public class myReam extends AuthorizingRealm{
    /** 用户的业务类 **/
    @Autowired
    private userService ser;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pri) {
        // TODO Auto-generated method stub
        System.out.println("this  is  权限~~~~~~~");
        User user=(User) pri.getPrimaryPrincipal();
        Integer id = user.getId();
        if(id==1){
            System.out.println("this is   id====1");
            List<UserRole> qRole = ser.queryUserRole(id);
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            //获取能够访问的URL列表
            List<String> qu = ser.queryPermission(qRole.get(0).getRoleId());
            for(String r:qu){
                System.out.println("r==="+r);
                info.addStringPermission(r);
            }
            return info;
        }
        return null;
    }
    //登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken token1) throws AuthenticationException {
        // TODO Auto-generated method stub
        System.out.println("this is  登录shiro 验证·~~~~~~~~~~~~" );
        UsernamePasswordToken token=(UsernamePasswordToken)token1;
        String username = token.getUsername();
        char[] password = token.getPassword();
        String pass=new String(password);
        System.out.println(username);
        System.out.println(pass);
        System.out.println(22222222);

        if(username!=null){
            User user = ser.queryUserByUsername(username);
            System.out.println("user====="+user);
            //账号不存在
            if(user == null) {
                System.out.println("1账号或密码不正确");
                throw new UnknownAccountException("账号或密码不正确");
            }
            if(user!=null){
                //密码错误
                if(!pass.equals(user.getPassword())) {
                    System.out.println("2账号或密码不正确");
                    throw new IncorrectCredentialsException("账号或密码不正确");
                }
                System.out.println(user);
                return new SimpleAuthenticationInfo(user, user.getPassword(),getName());
            }
        }
        return null;
    }

}

logincontroller类

package com.deng.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
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.RequestMethod;

import com.deng.entity.User;
import com.deng.service.userService;

/****
 * 用户登录Controller
 * 
 * @author deng
 * 
 */
@Controller
public class LoginController {

    @Autowired
    private userService ser;

    /***
     * 实现用户登录
     * 
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String Login(String username, String password,HttpServletRequest req) {
          try {
                UsernamePasswordToken token = new UsernamePasswordToken(username,password);
                Subject subject = SecurityUtils.getSubject();
                subject.login(token);
            } catch (UnknownAccountException e) {
                e.printStackTrace();
             req.getSession().setAttribute("errorMessage", "用户名或密码错误");
                return "login";
            } catch (AuthenticationException e) {
                e.printStackTrace();
                req.getSession().setAttribute("errorMessage", "用户名或密码错误");
                return "login";
            }

            // 登录后存放进shiro token
            return "home";
    }
}

login.jsp

    <form action="login.do" method="post">
            username:<input type="text" name="username"><p>
            password:<input type="password" name="password">
            <input type="submit">
            <p>
            <span>${sessionScope.errorMessage}</span>
    </form>

密码错误

这里写图片描述

登录成功

这里写图片描述

猜你喜欢

转载自blog.csdn.net/bpqdwo/article/details/74940348