ssm和shiro(2)

8 篇文章 0 订阅
5 篇文章 0 订阅

ssm和shiro框架的使用

步骤

创建maven的war项目

引入依赖

<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.sxt</groupId>
	<artifactId>shiro-11-ssm-rememberme</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>4.3.21.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.3.21.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.8.9</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.4.6</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.3.2</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.47</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.25</version>
		</dependency>
		<dependency>
			<groupId>com.mchange</groupId>
			<artifactId>c3p0</artifactId>
			<version>0.9.5.3</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</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>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>4.3.21.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>test</display-name>
  <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>
  <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:springmvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-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>
  <filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
      <param-name>targetFilterLifecycle</param-name>
      <param-value>true</param-value>
    </init-param>
    <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>
  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.jpg</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.js</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.css</url-pattern>
  </servlet-mapping>
</web-app>

配置文件

spring的配置文件(applicationContext-base.xml)

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" 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/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">

	<!-- 关联数据属性文件 -->
	<context:property-placeholder location="classpath:db.properties" />
	<!-- 开启扫描 -->
	<context:component-scan base-package="com.sxt.service.impl" />

	<!-- 配置数据源 -->
	<bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource">
		<property name="driverClass" value="${driver}"></property>
		<property name="jdbcUrl" value="${url}"></property>
		<property name="user" value="${names}"></property>
		<property name="password" value="${password}"></property>
	</bean>
	<!-- 整合mybatis -->
	<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactoryBean">
		<!-- 关联数据源 -->
		<property name="dataSource" ref="dataSource" />
		<!-- 关联mybatis的配置文件 -->
		<property name="configLocation" value="classpath:mybatis-config.xml" />
		<!-- 添加别名设置 -->
		<property name="typeAliasesPackage" value="com.sxt.pojo" />
	</bean>
	<!-- 配置扫描的路径 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.sxt.mapper" />
	</bean>


	<!-- shiro为集成springMvc 拦截异常 -->
	<bean
		class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		<property name="exceptionMappings">
			<props> <!-- 这里你可以根据需要定义N多个错误异常转发 -->
				<prop key="org.apache.shiro.authz.UnauthorizedException">redirect:/error.jsp</prop>
				<prop key="org.apache.shiro.authz.UnauthenticatedException">redirect:/login.jsp</prop> 
				<!--<prop key="java.lang.IllegalArgumentException">
				redirect:/error.jsp</prop> 
					参数错误(bizError.jsp) --> 
				<!--<prop key="java.lang.Exception">
				redirect:/error.jsp</prop> 其他错误为'未定义错误'(unknowError.jsp) -->
			</props>
		</property>
	</bean>

</beans>

shiro配置文件

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" 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/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.sxt.realm.MyRealm" id="myRealm">
		<!-- 配置凭证匹配器 -->
		<property name="credentialsMatcher" ref="credentialsMatcher" />
	</bean>

	<!-- 配置自定义的表单过滤器 -->
	<bean id="customFormAuthenticationFilter" class="com.sxt.filter.CustomFormAuthenticationFilter">
		<!-- 可以修改表单接收的参数名称 -->
		<property name="usernameParam" value="username" />
		<property name="passwordParam" value="password" />
	</bean>


	<!-- 配置缓存管理器 -->
	<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
		<!-- 关联配置文件 -->
		<property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml" />
	</bean>


	<!-- remenberMe配置 -->
	<bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
		<constructor-arg value="rememberMe" />
		<property name="httpOnly" value="true" />
		<!-- 默认记住7天(单位:秒) -->
		<property name="maxAge" value="604800" />
	</bean>
	<!-- rememberMe管理器 -->
	<bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
		<property name="cipherKey"
			value="#{T(org.apache.shiro.codec.Base64).decode('4AvVhmFLUs0KTA3Kprsdag==')}" />
		<property name="cookie" ref="rememberMeCookie" />
	</bean>


	<!-- 注册SecurityManager -->
	<bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"
		id="securityManager">
		<!-- 配置自定义Realm -->
		<property name="realm" ref="myRealm" />
		<property name="cacheManager" ref="cacheManager" />
		<!-- 注册rememberMe -->
		<property name="rememberMeManager" ref="rememberMeManager"/>
	</bean>



	<!-- 注册rememberMe的过滤器 -->
	<bean class="com.sxt.filter.RememberFormAuthenticationFilter" id="rememberFormAuthenticationFilter">
	</bean>
	
	<!-- 注册ShiroFilterFactoryBean 注意id必须和web.xml中注册的targetBeanName的值一致 -->
	<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="/error.jsp" />
		<!-- 配置过滤器 -->
		<property name="filters">
			<map>
				<entry key="authc" value-ref="customFormAuthenticationFilter" />
				<entry key="rememberMe" value-ref="rememberFormAuthenticationFilter" />
			</map>
		</property>
		<!-- 设置 过滤器链 -->
		<property name="filterChainDefinitions">
			<value>
				<!--加载顺序从上往下。 authc需要认证 anon可以匿名访问的资源 -->
				/login.do=authc
				/login.jsp=anon
				/error.jsp=anon
				/**=rememberMe,user <!-- 必须设置为user级别,authc级别的rememberMe的没有效果 -->
			</value>
		</property>
	</bean>
</beans>

db.properties配置

#mysql \u5F00\u53D1\u73AF\u5883
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/again?characterEncoding=utf-8
names=root
password=root

# \u6D4B\u8BD5\u73AF\u5883
#driver=com.mysql.jdbc.Driver
#url=jdbc:mysql://192.168.88.101:3306/1227?characterEncoding=utf-8
#username=root
#password=123456

# \u751F\u4EA7\u73AF\u5883
#driver=com.mysql.jdbc.Driver
#url=jdbc:mysql://192.168.88.102:3306/1227?characterEncoding=utf-8
#username=root
#password=123456

日志文件(log4j.properties)

log4j.rootCategory=DEBUG, stdout , R
 
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[QC] %p [%t] %C.%M(%L) | %m%n
 
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=C:\\Tomcat 5.5\\logs\\qc.log
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d-[TS] %p %t %c - %m%n

mybatis配置文件(mybatis-config.xml)

<?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>
	<settings>
		 <!-- 开启延迟加载 -->
		<setting name="lazyLoadingEnabled" value="true"/>
		<setting name="aggressiveLazyLoading" value="false"/>
	</settings>
</configuration>
 

shiro缓存配置文件(shiro-ehcache.xml)

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
	<!--diskStore:缓存数据持久化的目录 地址  -->
	<diskStore path="C:\tools\ehcache" />
	<!--   
	eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。  
	maxElementsInMemory:缓存中允许创建的最大对象数  
	overflowToDisk:内存不足时,是否启用磁盘缓存。  
	timeToIdleSeconds:缓存数据的钝化时间,也就是在一个元素消亡之前,  两次访问时间的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是 0 就意味着元素可以停顿无穷长的时间。  
	timeToLiveSeconds:缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。  
	memoryStoreEvictionPolicy:缓存满了之后的淘汰算法。  
	diskPersistent:设定在虚拟机重启时是否进行磁盘存储,默认为false
	diskExpiryThreadIntervalSeconds: 属性可以设置该线程执行的间隔时间(默认是120秒,不能太小
	1 FIFO,先进先出  
	2 LFU,最少被使用,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。  
	3 LRU,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。  
	--> 
	<defaultCache 
		maxElementsInMemory="1000" 
		maxElementsOnDisk="10000000"
		eternal="false" 
		overflowToDisk="false" 
		diskPersistent="false"
		timeToIdleSeconds="120"
		timeToLiveSeconds="120" 
		diskExpiryThreadIntervalSeconds="120"
		memoryStoreEvictionPolicy="LRU">
	</defaultCache>
</ehcache>

springmvc配置文件(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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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">

	<!-- 开启扫描 -->
	<context:component-scan base-package="com.sxt.controller"
		use-default-filters="false">
		<context:include-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>

	<!-- 开启SpringMVC注解的方式 -->
	<mvc:annotation-driven>
		<!-- <mvc:message-converters> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"></bean> 
			</mvc:message-converters> -->
	</mvc:annotation-driven>

	<!-- 开启Shiro注解 -->
	<aop:config proxy-target-class="true"></aop:config>
	<bean
		class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
		<property name="securityManager" ref="securityManager" />
	</bean>

</beans>

实体类(User)

public class User implements Serializable{

	private static final long serialVersionUID = 1L;
	
	private Integer id;
	
	private String username;
	
	private String password;
	
	private String salt;
 

dao层的代码

接口(UserMapper.java)

public interface UserMapper {

	public List<User> query(String username);
}
 

映射文件(UserMapper.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="com.sxt.mapper.UserMapper">
	<select id="query" resultType="user">
		select * from users where username=#{param1}
	</select>
</mapper>

service层

实现类(UserServiceImpl.java)

@Service
public class UserServiceImpl implements UserService {
	
	@Resource
	private UserMapper mapper;

	@Override
	public List<User> login(String userName) {
		return mapper.query(userName);
	}

}

controller层

登陆(LoginController.java)

package com.sxt.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
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 org.springframework.web.bind.annotation.SessionAttributes;

@Controller
//@SessionAttributes("msg")
public class LoginController {

	/**
	 * 设定登录失败跳转的资源以及获取失败的信息
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/login.do")
	public String login(Model model, HttpServletRequest request) {
		Object ex = request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
		if (ex != null) {
			System.out.println(ex.toString() + "----------");
		}
		if (UnknownAccountException.class.getName().equals(ex)) {
			System.out.println("----账号不正确----->");
			model.addAttribute("msg", "账号不正确");
		} else if (IncorrectCredentialsException.class.getName().equals(ex)) {
			System.out.println("----密码不正确----->");
			model.addAttribute("msg", "密码不正确");
		} else {
			System.out.println("----其他错误----->");
			model.addAttribute("msg", "其他错误");
		}
		return "/login.jsp";
	}
}

权限验证(UserController.java)

package com.sxt.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
	
	
	@RequiresPermissions("query")
	@RequestMapping(value="/query",produces = "text/html; charset=utf-8")
	public String query(){
		Session session = SecurityUtils.getSubject().getSession();
		System.out.println(session.getAttribute("message"));
		return "query ------ "+session.getAttribute("message");
	}
	
	
	@RequiresPermissions("insert")
	@RequestMapping("/insert")
	public String insert(){
		
		return "insert------";
	}
	
	@RequiresPermissions("update")
	@RequestMapping("/update")
	public String update(){
		
		return "update------";
	}
	
	
	@RequiresPermissions("delete")
	@RequestMapping("/delete")
	public String delete(){
		
		return "delete------";
	}
}

Realm域 (MyRealm.java) 验证和授权

package com.sxt.realm;

import java.util.List;

import javax.annotation.Resource;

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.SimpleByteSource;

import com.sxt.pojo.User;
import com.sxt.service.UserService;

public class MyRealm extends AuthorizingRealm {

	@Resource
	private UserService userService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		System.out.println("授权操作...");
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addStringPermission("query");
		info.addStringPermission("insert");
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
		String userName = (String) arg0.getPrincipal();

		  List<User> list = userService.login(userName);
		if (list == null || list.size() != 1) {

			return null;
		}

		User u = list.get(0);
		// 获取密码
		String pwd = u.getPassword();
		 
		// 验证密码
		SimpleAuthenticationInfo  info = new SimpleAuthenticationInfo(
				userName 
				, pwd
				, new SimpleByteSource(u.getSalt())
				, "myrealm");
		// return info;
		return info;
	}

}
 

过滤器

CustomFormAuthenticationFilter.java 登陆成功过滤

package com.sxt.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

public class CustomFormAuthenticationFilter extends FormAuthenticationFilter{

 
	@Override
	protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
			ServletResponse response) throws Exception {
		//获取登陆信息
		String username = (String)subject.getPrincipal(); 
		System.out.println("登录账户:"+username);
		
		Session session = subject.getSession();
		session.setAttribute("message","自定义FormFilter传递的信息...");
		
		return super.onLoginSuccess(token, subject, request, response);
	}

	
	
}

RememberFormAuthenticationFilter.java 记住登陆的过滤器

package com.sxt.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

public class RememberFormAuthenticationFilter extends FormAuthenticationFilter{

	
	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
		 Subject subject = getSubject(request, response);
		 Session session = subject.getSession();
		 if (!subject.isAuthenticated()
				 &&subject.isRemembered()
				 &&session.getAttribute("msg")==null) {
			System.out.println("记住的用户是:"+subject.getPrincipal());
			session.setAttribute("msg", "remember中保存的信息");
		}
		
		return subject.isAuthenticated()||subject.isRemembered();
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值