尚筹网:登录检查拦截器【拦截器不生效,待解决】

仅仅是临时使用,练习拦截器。将来使用SpringSecurity后将取消。

拦截器类

所在工程:atcrowdfunding-admin-2-component
全类名:com.atguigu.crowd.funding.interceptor.LoginInterceptor

package com.atguigu.crowd.funding.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.atguigu.crowd.funding.entity.Admin;
import com.atguigu.crowd.funding.util.CrowdFundingConstant;

public class LoginInterceptor extends HandlerInterceptorAdapter {
	
	// 在操作之前请登录, 但是不要拦截登录页面,登出页面
	public boolean preHandler(HttpServletRequest request,
			HttpServletResponse response,
			Object handler) throws Exception{
		// 通过request对象获取HttpSession对象
				HttpSession session = request.getSession();
				
				// 从Session域尝试获取已登录用户对象
				Admin admin = (Admin) session.getAttribute(CrowdFundingConstant.ATTR_NAME_LOGIN_ADMIN);
				
				// 如果没有获取到Admin对象
				if(admin == null) {
					
					// 将提示消息存入request域
					request.setAttribute(CrowdFundingConstant.ATTR_NAME_MESSAGE, CrowdFundingConstant.MESSAGE_ACCESS_DENIED);
					
					// 转发到登录页面
					request.getRequestDispatcher("/WEB-INF/admin-login.jsp").forward(request, response);
					
					return false;
				}
				
				// 如果admin对象有效,则放行继续执行后续操作
				return true;
	}
}

注册拦截器类

所在工程:atcrowdfunding-admin-1-webui
配置文件:spring-web-mvc.xml

<!-- 配置拦截器 -->
<mvc:interceptors>
	<mvc:interceptor>
		<!-- 设置当前拦截器要拦截的路径 -->
		<mvc:mapping path="/**"/>
		
		<!-- 设置要拦截的路径中的例外,也就是不拦截的路径 -->
		<mvc:exclude-mapping path="/admin/to/login/page.html"/>
		<mvc:exclude-mapping path="/admin/do/login.html"/>
		<mvc:exclude-mapping path="/admin/logout.html"/>
		
		<!-- 拦截器的bean -->
		<bean class="com.atguigu.crowd.funding.interceptor.LoginInterceptor"/>
	</mvc:interceptor>
</mvc:interceptors>

检查拦截器是否生效
1、在拦截器方法中添加打印
2、配置拦截所有

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值