共计 2242 个字符,预计需要花费 6 分钟才能阅读完成。
顺手记录一下。
import org.springframework.context.annotation.Import;
import java.lang.annotation.*;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({RoleCheckConfig.class})
public @interface EnableRoleCheck {}
import com.cx.demo_role_check.filter.RoleCheckFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import javax.servlet.Filter;
public class RoleCheckConfig {public RoleCheckConfig() { }
// 注入 filter
@Bean
public RoleCheckFilter roleCheckFilter(){return new RoleCheckFilter();
}
// 将 Filter 注册到 web
@Bean
public FilterRegistrationBean<Filter> roleCheckFilterRegistration(RoleCheckFilter roleCheckFilter){FilterRegistrationBean<Filter> filterFilterRegistrationBean = new FilterRegistrationBean<>();
filterFilterRegistrationBean.setFilter(roleCheckFilter);
filterFilterRegistrationBean.setName("roleCheckFilter");
return filterFilterRegistrationBean;
}
}
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class RoleCheckFilter implements Filter {
private String excludeURLRole;
@Override
public void init(FilterConfig filterConfig) throws ServletException {System.out.println("init");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {HttpServletRequest httpServletRequest = (HttpServletRequest)request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
System.out.println(httpServletRequest.getRequestURI());
// 实现过滤器的性能
if (false){// 条件判断 未通过校验 不能够拜访
httpServletResponse.setStatus(403);
}else{// 间接拜访接口
filterChain.doFilter(request,response);
}
}
@Override
public void destroy() {System.out.println("destroy");
}
}
在其余的我的项目外面援用相干的 jar,启动类上加上相干的注解,性能即可失效。
<dependency>
<groupId>com.cx</groupId>
<artifactId>demo_role_check</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
import com.cx.demo_role_check.config.EnableRoleCheck;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableRoleCheck
public class DemoRoleCheckTestApplication {public static void main(String[] args) {SpringApplication.run(DemoRoleCheckTestApplication.class, args);
}
}
正文完