1.利用注解配置 web.xml
package com.hivescm.webconfig;
import java.util.EventListener;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.jasig.cas.client.authentication.AuthenticationFilter;
import org.jasig.cas.client.session.SingleSignOutFilter;
import org.jasig.cas.client.session.SingleSignOutHttpSessionListener;
import org.jasig.cas.client.util.AssertionThreadLocalFilter;
import org.jasig.cas.client.util.HttpServletRequestWrapperFilter;
import org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.hivescm.disconf.config.SsoConfig;
import com.hivescm.filter.UserAuthFilter;
import com.hivescm.logcenter.client.AcessLogFilter;
@EnableWebMvc
@ComponentScan
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Resource
private SsoConfig ssoConfig;
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//设置首页
registry.addViewController( "/" ).setViewName( "forward:WEB-INF/index.jsp" );
registry.setOrder( Ordered.HIGHEST_PRECEDENCE );
super.addViewControllers(registry);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/").addResourceLocations("/**");
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
}
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
/**
* filter日志demo
* @return
*/
@Bean
public FilterRegistrationBean indexFilterRegistration() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean(new AcessLogFilter());
registrationBean.addUrlPatterns("/");
registrationBean.setOrder(6);
return registrationBean;
}
/**
* 认证过滤
* @return
*/
@Bean
public FilterRegistrationBean userFilterRegistration() {
FilterRegistrationBean registrationBean=new FilterRegistrationBean();
registrationBean.setName("userAuthFilter");
registrationBean.setFilter(new UserAuthFilter());
Map initParameters = new HashMap();
initParameters.put("filterUrls", "/WEB-INF/views/loginSuccess.jsp");
initParameters.put("interfaceClasses", "com.hivescm.filter.interfaceDo.ValidatePhoneInterface,com.hivescm.filter.interfaceDo.ValidatePasswordInterface");
registrationBean.setInitParameters(initParameters);
registrationBean.addUrlPatterns("/*");
registrationBean.setOrder(7);
return registrationBean;
}
/**
@Bean
public FilterRegistrationBean getCasSingleSignOutFilter(){
FilterRegistrationBean registrationBean=new FilterRegistrationBean();
registrationBean.setName("casSingleSignOutFilter");
registrationBean.setFilter(new SingleSignOutFilter());
registrationBean.addInitParameter("casServerUrlPrefix",ssoConfig.getCasServerUrlPrefix());
registrationBean.addUrlPatterns("/*");
registrationBean.setOrder(1);
return registrationBean;
}
@Bean
public FilterRegistrationBean getCASFilter(){
FilterRegistrationBean registrationBean=new FilterRegistrationBean();
registrationBean.setName("CASFilter");
registrationBean.setFilter(new AuthenticationFilter());
Map initParameters = new HashMap();
initParameters.put("casServerLoginUrl", ssoConfig.getCasServerLoginUrl());
initParameters.put("serverName", ssoConfig.getServerName());
initParameters.put("useSession", "true");
initParameters.put("redirectAfterValidation", "true");
initParameters.put("ignorePattern", "/staticres/css/|/staticres/js/");
registrationBean.setInitParameters(initParameters);
registrationBean.addUrlPatterns("/*");
registrationBean.setOrder(2);
return registrationBean;
}
@Bean
public FilterRegistrationBean getTicketValidationFilter(){
FilterRegistrationBean registrationBean=new FilterRegistrationBean();
registrationBean.setName("ticketValidationFilter");
registrationBean.setFilter(new Cas20ProxyReceivingTicketValidationFilter());
Map initParameters = new HashMap();
initParameters.put("casServerUrlPrefix", ssoConfig.getCasServerUrlPrefix());
initParameters.put("serverName", ssoConfig.getServerName());
registrationBean.setInitParameters(initParameters);
registrationBean.addUrlPatterns("/*");
registrationBean.setOrder(3);
return registrationBean;
}
@Bean
public FilterRegistrationBean getCasHttpServletRequestWrapperFilter(){
FilterRegistrationBean registrationBean=new FilterRegistrationBean();
registrationBean.setName("casHttpServletRequestWrapperFilter");
registrationBean.setFilter(new HttpServletRequestWrapperFilter());
registrationBean.addUrlPatterns("/*");
registrationBean.setOrder(4);
return registrationBean;
}
@Bean
public FilterRegistrationBean getCasAssertionThreadLocalFilter(){
FilterRegistrationBean registrationBean=new FilterRegistrationBean();
registrationBean.setName("casAssertionThreadLocalFilter");
registrationBean.setFilter(new AssertionThreadLocalFilter());
registrationBean.addUrlPatterns("/*");
registrationBean.setOrder(5);
return registrationBean;
}
// @Bean
// public ServletRegistrationBean getDemoServlet(){
// ServletRegistrationBean registrationBean=new ServletRegistrationBean();
// registrationBean.setServlet(demoServlet);
// List urlMappings=new ArrayList();
// urlMappings.add("/demoservlet");////访问,可以添加多个
// registrationBean.setUrlMappings(urlMappings);
// registrationBean.setLoadOnStartup(1);
// return registrationBean;
// }
@Bean
public ServletListenerRegistrationBean getDemoListener(){
ServletListenerRegistrationBean registrationBean
=new ServletListenerRegistrationBean<>();
registrationBean.setListener(new SingleSignOutHttpSessionListener());
registrationBean.setOrder(1);
return registrationBean;
} **/
}
2.自定义我的Filter
package com.hivescm.filter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import com.hivescm.entity.DevUser;
import com.hivescm.filter.interfaceDo.AuthInterface;
public class UserAuthFilter implements Filter{
//过滤的urlKey
private String filterUrlKey="filterUrls";
//过滤的url集合
private String[] filterUrlAll;
//业务处理类key
private String interfacePathKey="interfaceClasses";
//业务处理类集合
private String[] interfacePathAll;
private Map params = new HashMap();
public FilterConfig config;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
config = filterConfig;
for (Enumeration e = config.getInitParameterNames(); e
.hasMoreElements();) {
String name = (String) e.nextElement();
String value = config.getInitParameter(name);
params.put(name, value);
}
filterUrlAll=params.get(filterUrlKey)!=null?params.get(filterUrlKey).split(","):null;
interfacePathAll=params.get(interfacePathKey)!=null?params.get(interfacePathKey).split(","):null;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest hrequest = (HttpServletRequest)request;
HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) response);
//获取过滤的url
if (this.isContains(hrequest.getRequestURI(), filterUrlAll)) {// 只对指定过滤参数后缀进行过滤
DevUser user= (DevUser) hrequest.getSession().getAttribute("user");
if(user!=null){
//遍历配置的业务处理类执行方法验证
for(String intefaceName:interfacePathAll){
try {
Class> cla=Class.forName(intefaceName);
Object doWorkBean = cla.newInstance();
AuthInterface authInterface=(AuthInterface) doWorkBean;
String result= authInterface.doWork(user);
// Method method = cla.getMethod("doWork", DevUser.class);
// Object result= method.invoke(doWorkBean, user);
if(result!=null){
wrapper.sendRedirect((String)result);
return ;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}else{
chain.doFilter(request, response);
}
}
//放行
chain.doFilter(request, response);
}
@Override
public void destroy() {
params=null;
}
public static boolean isContains(String container, String[] regx) {
boolean result = false;
for (int i = 0; i < regx.length; i++) {
if (container.indexOf(regx[i]) != -1) {
return true;
}
}
return result;
}
}
3.自定义我的业务父类接口
package com.hivescm.filter.interfaceDo;
import com.hivescm.entity.DevUser;
public interface AuthInterface {
public String doWork(DevUser devUser);
}
4.自定义我的业务验证手机号码是否为空,为空则让其跳转到完善页面
package com.hivescm.filter.interfaceDo;
import org.apache.commons.lang3.StringUtils;
import com.hivescm.entity.DevUser;
public class ValidatePhoneInterface implements AuthInterface {
private String redictAction="/user/setPhone";
@Override
public String doWork(DevUser user) {
if(user!=null){
//判断手机号码是否完善
if(StringUtils.isBlank(user.getPhone())){
return redictAction;
}
return null;
}
return null;
}
}