Shiro之整合SSM

本文介绍了如何在Spring、Struts2、MyBatis(SSM)框架下整合Apache Shiro,包括在pom.xml中添加Shiro依赖,配置web.xml中的过滤器,设置独立的Shiro配置文件,创建自定义Realm进行身份验证和授权,以及各层文件的实现,如service、dao、POJO和controller层,最后展示了登录与登出的页面逻辑。

在pom.xml中导入相关依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.zhouym</groupId>
	<artifactId>shiro-ssm</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<dependencies>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.3.2</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.4.6</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.3.21.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.21.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<!-- 导入shiro相关依赖 -->
		<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-spring</artifactId>
			<version>1.2.3</version>
		</dependency>
		<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-ehcache</artifactId>
			<version>1.2.3</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.47</version>
		</dependency>
		<dependency>
			<groupId>com.mchange</groupId>
			<artifactId>c3p0</artifactId>
			<version>0.9.5.2</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.25</version>
		</dependency>
		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>4.3.21.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.9.4</version>
		</dependency>
		<dependency>
			<groupId>com.zhouym.oracle</groupId>
			<artifactId>ojdbc6</artifactId>
			<version>1.0.0</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>4.3.21.RELEASE</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<!-- tomcat插件 -->
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
				<version>2.2</version>
				<configuration>
					<!-- 端口号 -->
					<port>8082</port>
					<!-- /表示访问路径 省略项目名 -->
					<path>/</path>
					<!-- 设置编码方式 -->
					<uriEncoding>utf-8</uriEncoding>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

在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"
	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">
	<!-- 配置spring -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext-*.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!--前端控制器dispatcherServlet-->
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-mvc.xml</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<!-- 注册shiro过虑器,DelegatingFilterProxy通过代理模式将spring容器中的bean和filter关联起来 -->
	<filter>
		<filter-name>shiroFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<!-- 设置true由servlet容器控制filter的生命周期 -->
		<init-param>
			<param-name>targetFilterLifecycle</param-name>
			<param-value>true</param-value>
		</init-param>
		<!-- 设置spring容器filter的bean id,如果不设置则找与filter-name一致的bean -->
		<init-param>
			<param-name>targetBeanName</param-name>
			<param-value>shiro</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>shiroFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!--设置编码格式-->
	<filter>
		<filter-name>encoding</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>forceRequestEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
		<init-param>
			<param-name>forceResponseEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- 配置防止springmvc对静态资源的拦截 -->
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.jpg</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.html</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.css</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.js</url-pattern>
	</servlet-mapping>
</web-app>

添加shiro的配置文件

shiro的配置是可以放在spring的配置文件中,但是为了方便管理,这里单独给shiro添加一个配置文件,里面的Schema约束规范还是spring的
在这里插入图片描述
shiro的配置文件

<?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:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
		
		<!-- 配置凭证匹配器 -->
	<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"
		id="credentialsMatcher">
		<property name="hashAlgorithmName" value="md5" />
		<property name="hashIterations" value="1024" />
	</bean>

	<!-- 配置自定义的Realm -->
	<bean class="com.zhouym.realm.MySecurityRealm" id="myRealm">
		<!-- 关联凭证匹配器 -->
		<property name="credentialsMatcher" ref="credentialsMatcher" />
	</bean>

	<!-- 配置SecurityManager -->
	<bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"
		id="securityManager">
		<!-- 关联自定义的realm -->
		<property name="realm" ref="myRealm" />
	</bean>

	<bean class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"
		id="shiro">
		<!-- 注册SecurityManager -->
		<property name="securityManager" ref="securityManager" />
		<!-- 登录地址 如果用户请求的的地址是 login.do 那么会对该地址认证 -->
		<property name="loginUrl" value="/login.do" />
		<!-- 登录成功的跳转地址 -->
		<property name="successUrl" value="/success.jsp" />
		<!-- 访问未授权的页面跳转的地址 -->
		<property name="unauthorizedUrl" value="/jsp/refuse.jsp" />
		<!-- 设置过滤器链 -->
		<property name="filterChainDefinitions">
			<value>
				<!--加载顺序从上往下。 authc需要认证  anon可以匿名访问的资源 -->
				/login.do=authc
				/login.jsp=anon
				/**=authc
			</value>
		</property>
	</bean>
</beans>

创建自定义的realm

在这里插入图片描述

package com.zhouym.realm;

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.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.apache.shiro.util.SimpleByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.zhouym.pojo.UserBean;
import com.zhouym.service.UserService;

public class MySecurityRealm extends AuthorizingRealm {
	@Autowired
	private UserService service;
	//授权方法
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		UserBean user = (UserBean)principals.getPrimaryPrincipal();
		System.out.println("登录的账号:"+user.getName());
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addRole("role1");
		info.addRole("role2");
		info.addStringPermission("user:query");
		info.addStringPermission("user:delete");
		return info;
	}
	
	//认证方法
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//获取账号信息
		UsernamePasswordToken uptoken = (UsernamePasswordToken)token;
		//获取用户名
		String username = uptoken.getUsername();
		System.out.println(username);
		//根据用户名从数据库中查询信息
		UserBean user = service.queryByName(username);
		if (user == null) {
			return null;
		}
		AuthenticationInfo info = 
				new SimpleAuthenticationInfo(user, user.getPassword(), new SimpleByteSource(user.getSalt().getBytes()), "abc");
		return info;
	}

}

完成各层的文件

在这里插入图片描述

service层的接口及实现类

接口

package com.zhouym.service;

import java.util.List;

import com.zhouym.pojo.UserBean;

public interface UserService {
public List<UserBean> query();
	
	public UserBean queryByName(String userName);
	
	public UserBean queryByNameSHA(String userName);
	
	public void addUser(UserBean user);
	
	public void updateUser(UserBean user);
	
	public void deleteUser(Integer id);
}

实现类

package com.zhouym.service.Impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.zhouym.dao.UserBeanMapper;
import com.zhouym.pojo.UserBean;
import com.zhouym.pojo.UserBeanExample;
import com.zhouym.service.UserService;

@Service
public class UserServiceImpl implements UserService {
	
	@Resource
	private UserBeanMapper dao;
	
	@Override
	public List<UserBean> query() {
		UserBeanExample example = new UserBeanExample();
		List<UserBean> list = dao.selectByExample(example);
		return list;
	}

	@Override
	public UserBean queryByName(String userName) {
		UserBeanExample example = new UserBeanExample();
		example.createCriteria().andNameEqualTo(userName);
		List<UserBean> list = dao.selectByExample(example);
		if (list != null && list.size() == 1) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public void addUser(UserBean user) {
		dao.insert(user);
		
	}

	@Override
	public void updateUser(UserBean user) {
		dao.updateByPrimaryKey(user);
		
	}

	@Override
	public void deleteUser(Integer id) {
		dao.deleteByPrimaryKey(id);
		
	}

	@Override
	public UserBean queryByNameSHA(String userName) {
		List<UserBean> list = dao.selectByNameSHA(userName);
		if (list != null && list.size() == 1) {
			return list.get(0);
		}
		return null;
	}

}

dao层接口和映射文件

这里是通过逆向过程生成的接口及接口的映射文件
dao层接口

package com.zhouym.dao;

import com.zhouym.pojo.UserBean;
import com.zhouym.pojo.UserBeanExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;

public interface UserBeanMapper {
    long countByExample(UserBeanExample example);

    int deleteByExample(UserBeanExample example);

    int deleteByPrimaryKey(Integer id);

    int insert(UserBean record);

    int insertSelective(UserBean record);

    List<UserBean> selectByExample(UserBeanExample example);
    
    List<UserBean> selectByNameSHA(@Param("name") String username);

    UserBean selectByPrimaryKey(Integer id);

    int updateByExampleSelective(@Param("record") UserBean record, @Param("example") UserBeanExample example);

    int updateByExample(@Param("record") UserBean record, @Param("example") UserBeanExample example);

    int updateByPrimaryKeySelective(UserBean record);

    int updateByPrimaryKey(UserBean record);
}

dao层映射文件

<?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="com.zhouym.dao.UserBeanMapper">
  <resultMap id="BaseResultMap" type="com.zhouym.pojo.UserBean">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="age" jdbcType="INTEGER" property="age" />
    <result column="address" jdbcType="VARCHAR" property="address" />
    <result column="hobby" jdbcType="VARCHAR" property="hobby" />
    <result column="password" jdbcType="VARCHAR" property="password" />
    <result column="salt" jdbcType="VARCHAR" property="salt" />
  </resultMap>
  <sql id="Example_Where_Clause">
    <where>
      <foreach collection="oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause">
    <where>
      <foreach collection="example.oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List">
    id, name, age, address, hobby, password, salt
  </sql>
  <select id="selectByExample" parameterType="com.zhouym.pojo.UserBeanExample" resultMap="BaseResultMap">
    select
    <if test="distinct">
      distinct
    </if>
    <include refid="Base_Column_List" />
    from tb_user
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null">
      order by ${orderByClause}
    </if>
  </select>
  <!-- 在tb_user1表中查询sha加密的信息 -->
  <select id="selectByNameSHA" resultMap="BaseResultMap">
  	select 
  	id,
  	name,
  	age,
  	address,
  	hobby,
  	password,
  	salt 
  		from tb_user1
  			where name=#{name}
  </select>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from tb_user
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from tb_user
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <delete id="deleteByExample" parameterType="com.zhouym.pojo.UserBeanExample">
    delete from tb_user
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.zhouym.pojo.UserBean">
    insert into tb_user (id, name, age, 
      address, hobby, password, 
      salt)
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, 
      #{address,jdbcType=VARCHAR}, #{hobby,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
      #{salt,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.zhouym.pojo.UserBean">
    insert into tb_user
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="name != null">
        name,
      </if>
      <if test="age != null">
        age,
      </if>
      <if test="address != null">
        address,
      </if>
      <if test="hobby != null">
        hobby,
      </if>
      <if test="password != null">
        password,
      </if>
      <if test="salt != null">
        salt,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
      <if test="name != null">
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="age != null">
        #{age,jdbcType=INTEGER},
      </if>
      <if test="address != null">
        #{address,jdbcType=VARCHAR},
      </if>
      <if test="hobby != null">
        #{hobby,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="salt != null">
        #{salt,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.zhouym.pojo.UserBeanExample" resultType="java.lang.Long">
    select count(*) from tb_user
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map">
    update tb_user
    <set>
      <if test="record.id != null">
        id = #{record.id,jdbcType=INTEGER},
      </if>
      <if test="record.name != null">
        name = #{record.name,jdbcType=VARCHAR},
      </if>
      <if test="record.age != null">
        age = #{record.age,jdbcType=INTEGER},
      </if>
      <if test="record.address != null">
        address = #{record.address,jdbcType=VARCHAR},
      </if>
      <if test="record.hobby != null">
        hobby = #{record.hobby,jdbcType=VARCHAR},
      </if>
      <if test="record.password != null">
        password = #{record.password,jdbcType=VARCHAR},
      </if>
      <if test="record.salt != null">
        salt = #{record.salt,jdbcType=VARCHAR},
      </if>
    </set>
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map">
    update tb_user
    set id = #{record.id,jdbcType=INTEGER},
      name = #{record.name,jdbcType=VARCHAR},
      age = #{record.age,jdbcType=INTEGER},
      address = #{record.address,jdbcType=VARCHAR},
      hobby = #{record.hobby,jdbcType=VARCHAR},
      password = #{record.password,jdbcType=VARCHAR},
      salt = #{record.salt,jdbcType=VARCHAR}
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.zhouym.pojo.UserBean">
    update tb_user
    <set>
      <if test="name != null">
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="age != null">
        age = #{age,jdbcType=INTEGER},
      </if>
      <if test="address != null">
        address = #{address,jdbcType=VARCHAR},
      </if>
      <if test="hobby != null">
        hobby = #{hobby,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        password = #{password,jdbcType=VARCHAR},
      </if>
      <if test="salt != null">
        salt = #{salt,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.zhouym.pojo.UserBean">
    update tb_user
    set name = #{name,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER},
      address = #{address,jdbcType=VARCHAR},
      hobby = #{hobby,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      salt = #{salt,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

POJO普通java对象

package com.zhouym.pojo;

public class UserBean {
    private Integer id;

    private String name;

    private Integer age;

    private String address;

    private String hobby;

    private String password;

    private String salt;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address == null ? null : address.trim();
    }

    public String getHobby() {
        return hobby;
    }

    public void setHobby(String hobby) {
        this.hobby = hobby == null ? null : hobby.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public String getSalt() {
        return salt;
    }

    public void setSalt(String salt) {
        this.salt = salt == null ? null : salt.trim();
    }
}

以及对应的UserBeanExample类,这里不做展示

controller层

package com.zhouym.controller;

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

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.zhouym.service.UserService;

@Controller
public class UserController {
	
	@Resource
	private UserService service;
	
	@RequestMapping("/login.do")
	public String login(Model m,HttpServletRequest request) {	
		Object object = request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
		if (UnknownAccountException.class.getName().equals(object)) {
			m.addAttribute("msg", "账号错误");
			return "login.jsp";
		}else if (IncorrectCredentialsException.class.getName().equals(object)) {
			m.addAttribute("msg", "密码错误");
			return "login.jsp";
		}else {
			m.addAttribute("msg","未知错误");
			return "login.jsp";
		}		
	}
	//当我们第一次登录成功后,点后退再次登录会报错,此时需要显式退出,再次登录即可
	@RequestMapping("/logout.do")
	public String logout() {
		SecurityUtils.getSubject().logout();
		return "redirect:login.jsp";
	}
	
	@RequiresRoles("role1")
	@RequestMapping("/query")
	public String query(Model m) {
		m.addAttribute("list",service.query());
		return "/user.jsp";
	}
	@RequiresRoles("role2")
	@RequestMapping("/query1")
	public String query1(Model m) {
		m.addAttribute("list",service.query());
		return "/user.jsp";
	}
	
	@RequestMapping("/query2")
	public String query2(Model m) {
		m.addAttribute("list",service.query());
		return "/user.jsp";
	}
}

创建对应的jsp文件

在这里插入图片描述
login.jsp文件

<%@ 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>
	<h1>用户登陆:${msg} </h1>
	<form action="login.do" method="post">
		账号:<input type="text" name="username"><br>
		密码:<input type="text" name="password"><br>
		<input type="submit" value="提交">
	</form>
</body>
</html>

当我们点击提交后,根据action中的值找到对应的处理器,即controller,获取用户输入的用户名及密码,由于login.do在shiro的配置文件中被拦截了,所以先去我们自定义的realm类中进行认证,在认证方法中根据获取的用户名,带这个用户名的条件进行查询这个用户名下的信息,将信息保存到AuthenticationInfo中,然后再进入授权的方法中,查看对应用户名的权限,返回授权后的信息

在这里插入图片描述
输入用户名和密码
在这里插入图片描述
执行logout.do直接返回登录页面
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值