Spring Boot Filter过滤器 实现登录

Spring Boot Filter过滤器 实现登录

Filter类

package com.citi.test;

import java.io.IOException;

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.HttpSession;

public class LogCostFilter implements Filter {

	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("init");
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		HttpSession session = request.getSession(false);
		String requestURI = request.getRequestURI();
		if (!requestURI.contains("Login")) {
			if (session != null && session.getAttribute("name") != null) {
				filterChain.doFilter(request, response);
			} else {
				String requestType = request.getHeader("X-Requested-With");
				if (requestType != null && "XMLHttpRequest".equals(requestType)) {
					response.getWriter().write("NO_LOGIN");
				} else {
					response.sendRedirect(request.getContextPath() + "/Login");
				}
				return;
			}
		} else {
			filterChain.doFilter(servletRequest, servletResponse);
		}

	}

	public void destroy() {
		System.out.println("destroy");
	}
}

启动类

package com.citi.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;

import com.citi.test.LogCostFilter;

@SpringBootApplication
public class App {
	
	@Bean
    public FilterRegistrationBean setFilter(){
        FilterRegistrationBean filterBean = new FilterRegistrationBean();
        filterBean.setFilter(new LogCostFilter());
        filterBean.setName("FilterController");
        filterBean.addUrlPatterns("/*");
        return filterBean;
    }
	
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
        
    }
}

你可能感兴趣的:(Spring Boot Filter过滤器 实现登录)