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

项目结构

SSM+Shiro写的一个简单的登录验证_第1张图片

web.XML配置


<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 Applicationdisplay-name>

    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath*:config/spring.xml;
            classpath*:config/spring-mybatis.xml
        param-value>
    context-param>
    
    <context-param>
        <param-name>webAppRootKeyparam-name>
        <param-value>springmvc.rootparam-value>
    context-param>
    
    <filter>
        <filter-name>SpringEncodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
        <init-param>
            <param-name>forceEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>SpringEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
 <filter> 
   <filter-name>shiroFilterfilter-name> 
   <filter-class> 
      org.springframework.web.filter.DelegatingFilterProxy 
   filter-class> 
 filter> 
 <filter-mapping> 
   <filter-name>shiroFilterfilter-name> 
   <url-pattern>/*url-pattern> 
 filter-mapping>
    
    <context-param>
        
        <param-name>log4jConfigLocationparam-name>
        <param-value>classpath:config/log4j.propertiesparam-value>
    context-param>
    <context-param>
        
        <param-name>log4jRefreshIntervalparam-name>
        <param-value>6000param-value>
    context-param>
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListenerlistener-class>
    listener>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>

    
    <servlet>
        <servlet-name>springservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath*:config/spring-mvc.xmlparam-value>
        init-param>
        <load-on-startup>2load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>springservlet-name>
        <url-pattern>*.dourl-pattern>
    servlet-mapping>

    
    <error-page>
        
        <error-code>404error-code>
        <location>/WEB-INF/errorpage/404.jsplocation>
    error-page>
    <error-page>
        
        <error-code>405error-code>
        <location>/WEB-INF/errorpage/405.jsplocation>
    error-page>
    <error-page>
        
        <error-code>500error-code>
        <location>/WEB-INF/errorpage/500.jsplocation>
    error-page>
web-app>

spring配置


<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"/>
    
    <context:property-placeholder location="classpath:config/jdbc.properties" />

    
    <context:component-scan base-package="com.deng.serviceImp" />
beans>

spring-mvc配置


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

    
    <context:component-scan base-package="com.deng.controller" />

    
    <bean id="jacksonMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8value>
            list>
        property>
    bean>

    
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/" p:suffix=".jsp" />
beans>

mybatis-config配置



<configuration>

    
    <typeAliases >
    typeAliases>
    
    <mappers>
        
    mappers>
configuration>

spring-mybatis配置


<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>20value>
        property>
        
        <property name="initialSize">
            <value>1value>
        property>
        
        <property name="maxWait">
            <value>60000value>
        property>
        
        <property name="maxIdle">
            <value>20value>
        property>
        
        <property name="minIdle">
            <value>3value>
        property>
        
        <property name="removeAbandoned">
            <value>truevalue>
        property>
        
        <property name="removeAbandonedTimeout">
            <value>180value>
        property>
        
        <property name="connectionProperties">
            <value>clientEncoding=UTF-8value>
        property>
    bean>

    
    <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" />

    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
        p:basePackage="com.deng.dao" p:sqlSessionFactoryBeanName="sqlSessionFactory">

    bean>
    
    
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
        p:dataSource-ref="dataSource" />
beans>

shiro-context配置



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

            <value>
                /login = anon 
                /home = authc, perms[/home]  
                /** = authc 
            value>
        property> 
    bean>

    <bean id="myShiroRealm" class="com.deng.shiro.myReam">
        
        
    bean>

    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="myShiroRealm">property>
    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 qRole = ser.queryUserRole(id);
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            //获取能够访问的URL列表
            List 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>

密码错误

SSM+Shiro写的一个简单的登录验证_第2张图片

登录成功

SSM+Shiro写的一个简单的登录验证_第3张图片

你可能感兴趣的:(shiro)