Java拦截器

package com.chz.ssm.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.chz.ssm.domain.Permission;
import com.chz.ssm.domain.Role;
import com.chz.ssm.domain.UserInfo;
import com.chz.ssm.service.UserService;

import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

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

/*
自定义拦截器
*/
public class MyInterceptor1 implements HandlerInterceptor {
private UserService userService;

@Autowired
public void setUserService(UserService userService) {
	this.userService = userService;
}

/**
 * 预处理:controller方法执行前 true放行,执行下一个拦截器,如果没有,执行controller中的方法 false不放行
 */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
		throws Exception {
	Set<String> set = new HashSet<String>();//hashset集合不重复
	List<String> newList = new ArrayList<String>();//用于去重处理
	String id = null;//用户id
	List<Permission> permissions = null;//权限集合
	List<String> pList = new ArrayList<>();//用于和set集合配合去重
	System.out.println("执行前");
	System.out.println("PowerInterceptor:" + request.getContextPath() + "," + request.getRequestURI() + ","
			+ request.getMethod());
	SecurityContext context = SecurityContextHolder.getContext();
	User user = (User) context.getAuthentication().getPrincipal();
	String username = user.getUsername();//利用spring-security获取当前登录用户的姓名
	List<UserInfo> userList = userService.findAll();//查询用户信息
	for (UserInfo users : userList) {
		if (users.getUsername().equals(username)) {
			id = users.getId();//获取用户id
			System.out.println(id);
		}
	}
	UserInfo userInfo = userService.findById(id);//调用id查询用户具体信息
	List<Role> roleList = userInfo.getRoles();//将当前用户的角色存入集合
	for (Role rolename : roleList) {
		permissions = rolename.getPermissions();//获取权限内容
		for (Permission p : permissions) {
			pList.add(p.getUrl());//将权限存入pList
		}
	}
	set.addAll(pList);
	newList.addAll(set);//去重
	System.out.println(newList);// 所有的权限列表
	System.out.println(username);// 当前用户名
	String url = request.getRequestURI();//获取请求路径
	String projectName = "/chz_ssm_web";
	url = url.substring(projectName.length(http://yes-esports.com/), url.length());//删除项目名
	System.out.println(url);
	//判断是否拦截
	boolean flag = false;
	//用户是否存在指定url权限
	if (newList.contains(url)) {
		flag = true;
	}
	System.out.println(flag);
	if (!flag) {
		request.getRequestDispatcher("/permissionfailer.jsp").forward(request, response);
	}

// for(String s:newList) {
// if(s.equals(url)) {
// flag=true;
// }
// }
// System.out.println(flag);
// if (flag == false) {
// request.getRequestDispatcher("/permissionfailer.jsp").forward(request, response);
// }
return flag;

}

/**
 * 后处理方法,controller方法执行后,success.jsp执行之前
 */
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
		ModelAndView modelAndView) throws Exception {
	System.out.println("执行后");

}

/**
 * success.jsp执行后,该方法会执行
 */
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
		throws Exception {
	System.out.println("执行最后");
}

}

拦截器类 需要两个配合使用这里只有一个 @Configuration public class ServletContextConfig extends WebMvcConfigurerAdapter { public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); registry.addResourceHandler("/templates/**").addResourceLocations("classpath:/templates/"); super.addResourceHandlers(registry); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new HandlerMyInterceptorAdapter()).addPathPatterns("/**") .excludePathPatterns("/") // .excludePathPatterns("/expressions/getExpressionsList") .excludePathPatterns("/loginInfo/getCordByIsPhone") .excludePathPatterns("/loginInfo/login11") //token失效跳轉 .excludePathPatterns("/loginInfo/insertLoginInfo") //注册 .excludePathPatterns("/loginInfo/login") //登录 .excludePathPatterns("/upload") //上传文件 .excludePathPatterns("/uploadListen") //上传文件 .excludePathPatterns("/admin/user/goLogin") //后台跳转登录 .excludePathPatterns("/admin/user/login") //后台登录 .excludePathPatterns("/loginInfo/getLoginInfo") //忘记密码 .excludePathPatterns("/loginInfo/getCord") //短信验证码 .excludePathPatterns("/loginInfo/getIsLoginInfo") //判断验证码&&登录 .excludePathPatterns("/loginInfo/getIsLoginInfo1") //判断验证码 .excludePathPatterns("/loginInfo/setPassWord") //设置密码 ; } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } } @Component public class HandlerMyInterceptorAdapter implements HandlerInterceptor { @Autowired private HeartbeatServiceImpl heartbeatService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { String url = request.getRequestURI(); if (url.contains("admin")) { User user = (User) request.getSession().getAttribute("user"); try { if (user.equals(null)) { response.sendRedirect(serverConfig.SERVER + "admin/user/goLogin"); return false; } else { return true; } }catch (Exception e){ response.sendRedirect(serverConfig.SERVER + "admin/user/goLogin"); return false; } }else { String token = request.getHeader("token"); if (token != null) { Jedis jedis = new Jedis(com.sevenSteps.util.RedisConfig.HOST, RedisConfig.PORT); String s = jedis.get(token); if(token.equals(s)) { heartbeatService = SpringUtil.getBean(HeartbeatServiceImpl.class); return heartbeatService.setOutDate(token); }else { response.sendRedirect(serverConfig.SERVER + "loginInfo/login11"); return true; } }else { response.sendRedirect(serverConfig.SERVER + "loginInfo/login11"); return true; } } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值