filter实际上就是一个过滤器
1使用Servlet3.0的注解进行配置
2启动类中家@ServletComponentScan,进行扫描
3新建一个Filter类,implements Filter,并且实现对应的接口
4@WebFilter(urlPatterns = "/api/*",filterName = "LogginFilter") 标记一个类为filter,被spring扫描
urlPatterns 是拦截规则,支持正则
5控制filterChain.doFilter方法的调用,来实现是否支持放行,不放行,web应该返回resp.sendRedirect("/index.html");
场景:权限的控制,用户的登陆(非前后端分离)
6代码:
6.1目录结构
6.2添加注解
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
@ServletComponentScan
public class Springboot2Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Springboot2Application.class);
}
public static void main(String[] args) {
SpringApplication.run(Springboot2Application.class, args);
}
}
6.3新建Filter
package com.example.demo.filter;
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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebFilter(urlPatterns = "/api/*",filterName = "LogginFilter")
public class LogginFilter implements Filter{
/**
* 容器加载的时候调用
*/
@Override
public void init(FilterConfig filterConfig)throws ServletException {
System.out.println("init loginFilter");
}
/**
* 容器拦截的时候调用
*/
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse serletResponse, FilterChain filterChain)
throws IOException, ServletException {
System.out.println("doliter loginFilter");
HttpServletRequest rec=(HttpServletRequest)servletRequest;
HttpServletResponse resp=(HttpServletResponse) serletResponse;
String username=rec.getParameter("username");
if("李明".equals(username)) {
filterChain.doFilter(servletRequest, serletResponse);
}else {
resp.sendRedirect("/index.html");
return;
}
}
/**
* 容器销毁的时候调用
*/
@Override
public void destroy() {
System.out.println("destroy loginFilter");
}
}
6.4新建controller
package com.example.demo.controller.login;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoginController {
private Map<String,Object> params=new HashMap<>();
@RequestMapping(value="/api/v1/account")
public Object account() {
params.put("money", "1000");
return params;
}
}