Shiro框架04(shiro结合SSM框架案例及rbac完成登录)

Shiro框架04

本文源码资源:https://pan.baidu.com/s/16gHZdudm4KF6BXL7mdbbjw 提取码:dfya
数据库找小标题 2.SSMS的代码实现 下的数据库文件,复制下来粘贴到查询中执行
补充:在登录时把用户对象绑定到session

SecurityUtils.getSubject().getSession().setAttribute();

1.SSMS小项目的功能

该项目由spring、springmvc和shiro等框架构成并结合rbac实现的用户登录、shiro对其进行认证、授权等。
登录完成后系统会根据用户的角色,出现其对应的功能菜单
Shiro框架04(shiro结合SSM框架案例及rbac完成登录)_第1张图片

2.SSMS的代码实现

数据库文件

CREATE DATABASE /*!32312 IF NOT EXISTS*/`rbac` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `rbac`;

/*Table structure for table `admin` */

DROP TABLE IF EXISTS `admin`;

CREATE TABLE `admin` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `username` varchar(5) DEFAULT NULL,
  `password` varchar(55) DEFAULT NULL,
  `salt` varchar(55) DEFAULT NULL,
  `rid` int(5) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

/*Data for the table `admin` */

insert  into `admin`(`id`,`username`,`password`,`salt`,`rid`) values (1,'zs','d51d083a3a9ee3281ae4d51de866d995','sxt',2),(2,'lisi','d51d083a3a9ee3281ae4d51de866d995','sxt',3),(3,'ww','d51d083a3a9ee3281ae4d51de866d995','sxt',1);

/*Table structure for table `menu` */

DROP TABLE IF EXISTS `menu`;

CREATE TABLE `menu` (
  `mmid` int(5) NOT NULL AUTO_INCREMENT,
  `mname` varchar(55) DEFAULT NULL,
  `url` varchar(55) DEFAULT NULL,
  `pid` int(5) DEFAULT NULL,
  PRIMARY KEY (`mmid`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8;

/*Data for the table `menu` */

insert  into `menu`(`mmid`,`mname`,`url`,`pid`) values (1,'管理员功能',NULL,0),(2,'学生功能',NULL,0),(3,'课程功能',NULL,0),(4,'老师功能',NULL,0),(5,'查看个人信息',NULL,1),(6,'新增管理员',NULL,1),(7,'添加学生',NULL,2),(8,'获得所有学生',NULL,2),(9,'添加课程',NULL,3),(10,'查询课程',NULL,3),(11,'添加老师',NULL,4),(12,'查询老师',NULL,4),(13,'查看个人信息',NULL,2),(14,'选课',NULL,2),(15,'查询已选课程',NULL,2),(16,'查询个人信息',NULL,4),(17,'评分',NULL,4),(18,'查看任课课程',NULL,4);

/*Table structure for table `role` */

DROP TABLE IF EXISTS `role`;

CREATE TABLE `role` (
  `rid` int(5) NOT NULL AUTO_INCREMENT,
  `rname` varchar(55) DEFAULT NULL,
  PRIMARY KEY (`rid`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

/*Data for the table `role` */

insert  into `role`(`rid`,`rname`) values (1,'管理员'),(2,'学生'),(3,'老师');

/*Table structure for table `role_menu` */

DROP TABLE IF EXISTS `role_menu`;

CREATE TABLE `role_menu` (
  `rmid` int(5) NOT NULL AUTO_INCREMENT,
  `rid` int(5) DEFAULT NULL,
  `mmid` int(5) DEFAULT NULL,
  PRIMARY KEY (`rmid`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8;

/*Data for the table `role_menu` */

insert  into `role_menu`(`rmid`,`rid`,`mmid`) values (1,1,1),(2,1,2),(3,1,3),(4,1,4),(5,1,5),(6,1,6),(7,1,7),(8,1,8),(9,1,9),(10,1,10),(11,1,11),(12,1,12),(13,2,2),(14,2,13),(15,2,14),(16,2,15),(17,3,4),(18,3,16),(19,3,17),(20,3,18);

A、导包

Shiro框架04(shiro结合SSM框架案例及rbac完成登录)_第2张图片

B、项目结构

Shiro框架04(shiro结合SSM框架案例及rbac完成登录)_第3张图片

C、web.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--使用过滤器设置字符编码格式-->
    <filter>
        <filter-name>enc</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>
    </filter>
    <filter-mapping>
        <filter-name>enc</filter-name>
        <!--  url范围:表示所有以servlet/开头的请求  具体范围根据项目情况编写 -->
        <url-pattern>/*
    

    
    
        shiro
        org.springframework.web.servlet.DispatcherServlet
        
        
            contextConfigLocation
            classpath:springmvc.xml
        
    
    
        shiro
        /
    
    
    
        contextConfigLocation
        classpath:applicationContext-*.xml
    
    
        org.springframework.web.context.ContextLoaderListener
    


    
    
    
        shiro
        org.springframework.web.filter.DelegatingFilterProxy
        
        
            targetFilterLifecycle
            true
        
        
        
            targetBeanName
            shiroFilter
        
    
    
        shiro
        /*
    

D、Spring及SpringMVC配置文件

(1).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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:mve="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        <!--扫描@Controller 注解-->
        <context:component-scan base-package="cn.qt.controller"></context:component-scan>
        <!--扫描@RequestMappering-->
        <mvc:annotation-driven></mvc:annotation-driven>

        <!--静态资源放行-->
        <mve:resources mapping="/js/**" location="/js/"></mve:resources>

        <!--自定义视图解析器-->
       <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/"></property>
            <property name="suffix" value=".jsp"></property>
        </bean>
</beans>

(2).applicationContext-mybatis.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.xsd">

    <!--连接数据库获得数据源-->
    <bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/rbac"></property>
        <property name="username" value="root"></property>
        <property name="password" value="1111"></property>
    </bean>
    <!--获得sessionFactory工厂-->
    <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="ds"></property>
        <property name="typeAliasesPackage" value="cn.qt.pojo"></property>
    </bean>
    <!--扫描mapper文件-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="factory"></property>
        <property name="basePackage" value="cn.qt.mapper"></property>
    </bean>

</beans>

(3)applicationContext-service.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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:mve="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--扫描实体类注解-->
    <context:component-scan base-package="cn.qt.pojo"></context:component-scan>

    <!--扫描Service层注解-->
    <context:component-scan base-package="cn.qt.service"></context:component-scan>
</beans>

(4)applicationContext-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"
       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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--A、注册凭证匹配器-->
    <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
        <!--配置加密方式-->
        <property name="hashAlgorithmName" value="md5"></property>
        <!--配置迭代次数-->
        <property name="hashIterations" value="2"></property>
    </bean>
    <!--B、注册自定义Realm-->
    <bean id="userRealm" class="cn.qt.realm.UserRealm">
        <property name="credentialsMatcher" ref="credentialsMatcher"></property>
    </bean>
    <!--C、注册securityManager-->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <!--设置自定义realm-->
        <property name="realms" ref="userRealm"></property>
        <!--设置会话管理器-->
        <property name="sessionManager" ref="sessionManager"></property>
    </bean>
    <!--D、注册ShiroFliterFactoryBean对象-->
    <!--注意:id必须和web.xml中  使用过滤器连接filter  的targetBeanName保持一致-->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"></property>
        <!--登录URL-->
        <property name="loginUrl" value="/adminlogin"></property>
        <!--登录成功地址-->
        <property name="successUrl" value="findMoreMenus"></property>
        <!--登录失败地址-->
        <property name="unauthorizedUrl" value="error"></property>

        <!--设置过滤器链的属性-->
        <property name="filterChainDefinitions">
            <!--authc:拦截指定路径   anon:放行-->
            <value>
                /adminlogin=authc
                <!--配置退出的过滤器 如果没有配置退出的页面,默认是退到项目默认网页中index.jsp-->

                <!--记住我的路径-->
                /findMoreMenus=user

                /loginOut=logout
                /**=anon
            
        
    

    
    
        
    
    
    
        
        
        
        
        
    
    
    
        
        
        
        
    
    
    
        
        
        
        
    
    
    
        
    


(5)applicationContext-tx.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: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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">


     <!--【E】声明式事务的管理-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >

        <property name="dataSource" ref="ds"></property>

    </bean>

    <!--扫描的是@Transactional-->
    <tx:annotation-driven></tx:annotation-driven>

</beans>

E、poji层

(a)Admin类

package cn.qt.pojo;

import java.io.Serializable;
import java.util.List;

public class Admin implements Serializable {

    private String uname;
    private String pwd;
    private String salt;
    private int rid;
    //保存角色
    private Role role;
    //保存菜单的集合
    private List<Menu> list;

    public Admin(String uname, String pwd, String salt) {
        this.uname = uname;
        this.pwd = pwd;
        this.salt = salt;
    }


    public Admin() {
    }

    public Role getRole() {
        return role;
    }

    public void setRole(Role role) {
        this.role = role;
    }

    public List<Menu> getList() {
        return list;
    }

    public int getRid() {
        return rid;
    }

    public void setRid(int rid) {
        this.rid = rid;
    }

    public void setList(List<Menu> list) {
        this.list = list;
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getSalt() {
        return salt;
    }

    public void setSalt(String salt) {
        this.salt = salt;
    }

    @Override
    public String toString() {
        return "Admin{" +
                "uname='" + uname + '\'' +
                ", pwd='" + pwd + '\'' +
                ", salt='" + salt + '\'' +
                ", rid=" + rid +
                ", role=" + role +
                ", list=" + list +
                '}';
    }
}

(b)Menu类

package cn.qt.pojo;

import java.io.Serializable;
import java.util.List;

public class Menu implements Serializable {
    private Integer mmid;
    private String mname;
    private String url;
    private int pid;
    private List<Menu> list;

    public Menu(Integer mmid, String mname, String url, int pid) {
        this.mmid = mmid;
        this.mname = mname;
        this.url = url;
        this.pid = pid;
    }

    public Menu() {
    }

    public List<Menu> getList() {
        return list;
    }

    public void setList(List<Menu> list) {
        this.list = list;
    }

    public Integer getMmid() {
        return mmid;
    }

    public void setMmid(Integer mmid) {
        this.mmid = mmid;
    }

    public String getMname() {
        return mname;
    }

    public void setMname(String mname) {
        this.mname = mname;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public int getPid() {
        return pid;
    }

    public void setPid(int pid) {
        this.pid = pid;
    }

    @Override
    public String toString() {
        return "Menu{" +
                "mmid=" + mmid +
                ", mname='" + mname + '\'' +
                ", url='" + url + '\'' +
                ", pid=" + pid +
                '}';
    }
}

©Role类

package cn.qt.pojo;

import java.io.Serializable;

public class Role implements Serializable {
    private int rid;
    private String rname;

    public Role(int rid, String rname) {
        this.rid = rid;
        this.rname = rname;
    }

    public Role() {}

    public int getRid() {
        return rid;
    }

    public void setRid(int rid) {
        this.rid = rid;
    }

    public String getRname() {
        return rname;
    }

    public void setRname(String rname) {
        this.rname = rname;
    }

    @Override
    public String toString() {
        return "Role{" +
                "rid=" + rid +
                ", rname='" + rname + '\'' +
                '}';
    }
}

F、mapper层

(1)AdminMapper .java

package cn.qt.mapper;

import cn.qt.pojo.Admin;

public interface AdminMapper {
    //根据用户名和密码查找
    public Admin selectOne(String uname,String pwd);
    //获取用户的盐值
    public Admin selectPwd(String uname);
}

AdminMapper .xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.qt.mapper.AdminMapper">
    <select id="selectOne" resultType="admin">
        select * from admin where uname=#{0} and pwd=#{1}
    </select>
    <select id="selectPwd" resultType="admin">
        select * from  admin where uname=#{0}
    </select>
</mapper>

(2)MenuMapper.java

package cn.qt.mapper;

import cn.qt.pojo.Menu;

import java.util.List;

public interface MenuMapper {
    //菜单的查询
    public List<Menu> selectMenu(int rid,int pid);
}

MenuMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.qt.mapper.MenuMapper">
    <select id="selectMenu" resultType="menu">
        select * from menu where mmid in(select mmid from role_menu where rid=#{0}) and pid =#{1}
    </select>
</mapper>

(3)RoleMapper.java

package cn.qt.mapper;

import cn.qt.pojo.Role;

public interface RoleMapper {
    //查询Role信息
    public Role selectRole(int rid);
}

RoleMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.qt.mapper.RoleMapper">
    <select id="selectRole" resultType="role">
        select * from role where rid=#{0}
    </select>
</mapper>

G、service层

(1)AdminService.java

package cn.qt.service;

import cn.qt.pojo.Admin;

public interface AdminService {
    public Admin getPwd(String uname);
}

(2)MenuService.java

package cn.qt.service;

import cn.qt.pojo.Menu;

import java.util.List;

public interface MenuService {
    //查询多级菜单
    public List<Menu> findMenus(int rid);
}

(3)AdminServiceImpl.java

package cn.qt.service.Impl;

import cn.qt.mapper.AdminMapper;
import cn.qt.mapper.RoleMapper;
import cn.qt.pojo.Admin;
import cn.qt.pojo.Menu;
import cn.qt.pojo.Role;
import cn.qt.service.AdminService;
import cn.qt.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    MenuService menuService;
    @Autowired
    RoleMapper roleMapper;
   

    @Override
    public Admin getPwd(String uname) {
        Admin admin = adminMapper.selectPwd(uname);
        System.out.println(admin);
        List<Menu> list = menuService.findMenus(admin.getRid());
        //把菜单保存到执行的admin对象中
        admin.setList(list);
        //把用户的身份保存到admin中
        admin.setRole(roleMapper.selectRole(admin.getRid()));
        System.out.println(list);
        return admin;
    }
}

(4)MenuServiceImpl.java

package cn.qt.service.Impl;

import cn.qt.mapper.MenuMapper;
import cn.qt.pojo.Menu;
import cn.qt.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    MenuMapper menuMapper;
    @Override
    public List<Menu> findMenus(int rid) {
        //获得一级菜单
        List<Menu> list = menuMapper.selectMenu(rid, 0);

        for (Menu menu:list) {
            //获得一级菜单的mmid
            Integer mmid=menu.getMmid();
            //指定一级菜单下对应的二级菜单
            List<Menu> list2 = menuMapper.selectMenu(rid, mmid);
            //把二级菜单保存到指定的一级菜单对象
            menu.setList(list2);
        }
        return list;
    }
}

H、Realm层

UserRealm.java

package cn.qt.realm;

import cn.qt.pojo.Admin;
import cn.qt.service.AdminService;
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;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.*;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    AdminService adminService;
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String uname = authenticationToken.getPrincipal().toString();
        Admin admin = adminService.getPwd(uname);
        if (admin!=null){
            //把数据给SimpleAuthenticationInfo,用于认证     uname  pwd  salt realName
            SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(admin,admin.getPwd(), ByteSource.Util.bytes(admin.getSalt()), "userRealm");
            return  info;
        }

        return null;
    }
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Admin admin = (Admin)principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        //把角色名称保存到SimpleAuthorizationInfo
        info.addRole(admin.getRole().getRname());
        return info;
    }

}

I、Controller层

(1)GetPath.java

package cn.qt.controller;

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

@Controller
public class GetPath {
    @RequestMapping("/{path}")
    public String getPath(@PathVariable String path){
        return path;
    }
}

(2)AdminController.java

package cn.qt.controller;

import cn.qt.pojo.Admin;
import cn.qt.service.AdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;

@Controller
public class AdminController {
    @Autowired
    AdminService adminService;

    @RequestMapping("findMoreMenus")
    public String findMoreMenus(HttpServletRequest req){
        //获得验证成功后的admin对象
        Admin admin =(Admin)SecurityUtils.getSubject().getPrincipal();
        req.setAttribute("list",admin.getList());
        return "success";
    }
    @RequestMapping("adminlogin")
    public String adminlogin(Admin admin,HttpServletRequest req){
        //查看具体的异常信息,获得异常信息名称
        Object ex = req.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
        System.out.println(ex);
        if (UnknownAccountException.class.getName().equals(ex)){
            req.setAttribute("msg","用户名错误");
        }else if(IncorrectCredentialsException.class.getName().equals(ex)){
            req.setAttribute("msg","密码错误");
        }else {
            req.setAttribute("msg","未知异常");
        }
        return "error";
    }
}

J、/WEB-INF/jsp/

(1)login.jxp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
</head>
<body>
<form action="adminlogin" method="post">
    <%--
        注意:用户名和密码的name属性必须必须和applicationContext-shiro.xml中的authc的属性保持一致
        若未配置authc对象,则使用其默认属性名username和password。
        应为底层走的是FormAuthenticationFilter过滤器,它封装的是username和password。
    --%>
    <p>
        用户名:<input type="text" name="uname" />${msg}
    </p>
    <p>
        密码:<input type="text" name="pwd" />
    </p>
    <p>
        记住我:<input type="checkbox" name="rm"/>
    </p>
    <p>
        <input type="submit" value="登录" />
    </p>
</form>
</body>
</html>

(2)success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<c:forEach items="${list}" var="menu">
    <h4>${menu.mname}</h4><br/><br/>
    <c:forEach items="${menu.list}" var="menu2">
       &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="${menu2.url}">${menu2.mname}</a>
    </c:forEach>
</c:forEach>

<br/><br/><br/>
<a href="loginOut">退出</a>


</body>
</html>

©error.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录失败</title>
</head>
<body>
${msg}
</body>
</html>

你可能感兴趣的:(Shiro框架)