大家好,又见面了,我是你们的朋友全栈君。
java拦截器实现功能类似于aop功能的实现,实现拦截部分方法,一般用于类似 登录进入A页面,未登录进入B页面
实现方法有两种 实现Interceptor 接口 或者 继承HandlerInterceptorAdapter类,实现接口需要实现其中所有方法,继承抽象类则一般实现preHandle方法即可。
首先配置拦截类
package net.parim.spark.portal.adapter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class HomeOpenHandlerConfigration extends WebMvcConfigurerAdapter {
//关键,将拦截器作为bean写入配置中
@Bean
public HomeOpenInterceptor myInterceptor(){
return new HomeOpenInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor()).addPathPatterns(“/api/open/portal/**”)
.excludePathPatterns(“/api/open/footerInfo”).excludePathPatterns(“/api/open/portal/template/default”);
super.addInterceptors(registry);
}
}
addPathPatterns()方法为需要拦截的api,excludePathPatterns()方法为不需要拦截的接口api
配置拦截逻辑
package net.parim.spark.portal.adapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import net.parim.spark.common.config.ApplicationProperties;
import net.parim.spark.common.exceptions.BusinessException;
import net.parim.spark.core.system.constant.Constants;
import net.parim.spark.core.system.entity.Site;
import net.parim.spark.core.system.security.UserToken;
import net.parim.spark.core.system.security.exceptions.UnauthenticatedException;
import net.parim.spark.portal.service.PortalCommonService;
/**
* 首页外放拦截器
* @author liweiqiang
*
*/
@Component
public class HomeOpenInterceptor extends HandlerInterceptorAdapter {
@Autowired
private PortalCommonService portalCommonService;
@Autowired
private ApplicationProperties applicationProperties;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
//判断是否需要拦截
Boolean flag = false;
if(flag){
//判断是否允许不登录的情况下 访问主页
//如果不允许匿名访问返回401
throw new UnauthenticatedException();
}
//否则允许直接放过,不进行任何拦截
return true;
}
}
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/132400.html原文链接:https://javaforall.cn