Filter实现
package com.cc.boot.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
public class MyFilter2 implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("进入到filter222222222 = " + servletRequest);
filterChain.doFilter(servletRequest,servletResponse);
}
}
Filter配置类
package com.cc.boot.config;
import com.cc.boot.filter.MyFilter2;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FilterConfig {
@Bean
FilterRegistrationBean myFilterRegistrationBean() {
//注册过滤器
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new MyFilter2());
//添加过滤器路径,如果是user,下的一级,写一个*号,2个过滤会失效.例如:/user/**
filterRegistrationBean.addUrlPatterns("/user/*");
return filterRegistrationBean;
}
}
Filter测试类
package com.cc.boot.controller;
import com.cc.boot.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@Controller
@Slf4j
public class Filter2Controller {
@RequestMapping(value = "/user/filter")
public @ResponseBody
Object login(HttpServletRequest request) {
User user = new User();
user.setId("1009");
user.setUserName("张飞机");
request.getSession().setAttribute("user", user);
return "登录成功";
}
@RequestMapping(value = "/center")
public @ResponseBody
Object center() {
log.info("被拦截了吗-----------------------");
return "登录后可以访问center";
}
}
localhost:8080//user/filter