我是靠谱客的博主 大气大叔,最近开发中收集的这篇文章主要介绍如何自定义一个Filter 过滤器?Mybatis里使用FilterFilter是如何实现拦截的?SpringBoot里使用Filter定义多个拦截器,并决定它们的执行顺序,觉得挺不错的,现在分享给大家,希望可以做个参考。
概述
Mybatis里使用Filter
1. 拦截请求
1.1. 使用注解 @WebFilter("/*")
@WebFilter("/*")
public class OpenSessioInView implements Filter {
...
}
1.2. 配置文件 web.xml
<filter>
<filter-name>opensession</filter-name>
<filter-name>com.filter.OpenSessioInView.java</filter-name>
</filter>
<filter-mapping>
<filter-name>opensession</filter-name>
<url-pattern> /*</url-pattern>
</filter-mapping>
2. 自定义过滤器
@WebFilter("/*")
public class OpenSessioInView implements Filter {
private static final Logger logger = Logger.getLogger(OpenSessioInView.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
logger.info("初始化过滤器:");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// InputStream resourceAsStream = Resources.getResourceAsStream("mybatis.xml");
// SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
// SqlSession session = build.openSession();
SqlSession session = MyBatisUtil.getSession();
System.out.println("opensession");
try {
logger.info("过滤器开始;");
chain.doFilter(request, response);
session.commit();
logger.info("过滤器结束;");
} catch (Exception e) {
e.printStackTrace();
session.rollback();
System.out.println("roolback");
} finally {
MyBatisUtil.closeSession();
System.out.println("commit");
System.out.println("closesession");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
// session.commit();
// session.close();
}
@Override
public void destroy() {
logger.info("销毁过滤器");
}
}
使用
public class MyBatisUtil {
//3. factory实例化的过程是一个比较费性能的过程,做项目的时候都是保证有且仅有一个factory,因为没必要频繁创建工厂
private static SqlSessionFactory factory;// 2.静态代码块调用的东西也是静态的,所以这里是 static
private static ThreadLocal<SqlSession> tl = new ThreadLocal<>();
//1. 希望类在加载的时候就会产生factory对象,所以用静态块
static {
try {
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis.xml");
factory = new SqlSessionFactoryBuilder().build(resourceAsStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSession() {
SqlSession sin = tl.get();
if (sin == null) {
SqlSession session = factory.openSession();
tl.set(session);
}
return tl.get();
}
public static void closeSession() {
SqlSession sl = tl.get();
if (sl != null) {
sl.close();
}
tl.set(null);
}
}
@WebServlet("/inssssss")
public class LogServlet extends HttpServlet {
LogService logService = new LogServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String accOut = req.getParameter("accOut");
String accIn = req.getParameter("accIn");
String money = req.getParameter("money");
LogInfo loginfo = new LogInfo();
loginfo.setAccOut(accOut);
loginfo.setAccIn(accIn);
loginfo.setMoney(Double.parseDouble(money));
int index = logService.insert(loginfo);
if (index > 0) {
resp.sendRedirect("success.jsp");
} else {
resp.sendRedirect("error.jsp");
}
}
}
public class LogServiceImpl implements LogService {
@Override
public int insert(LogInfo loginfo) {
SqlSession session = MyBatisUtil.getSession();
LogMapper logmapper = session.getMapper(LogMapper.class);
int index = logmapper.ins(loginfo);
return index;
}
tomcat 一启动机会初始化过滤器
Filter是如何实现拦截的?
SpringBoot里使用Filter
1. 手动注册配置实现
@Component
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
String requestUri = request.getRequestURI();
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
@Configuration
public class MyFilterConfig {
@Autowired
MyFilter myFilter;
@Bean
public FilterRegistrationBean<MyFilter> thirdFilter() {
FilterRegistrationBean<MyFilter> filterRegistrationBean = new FilterRegistrationBean<>();
filterRegistrationBean.setFilter(myFilter);
filterRegistrationBean.setUrlPatterns(new ArrayList<>(Arrays.asList("/api/*")));
return filterRegistrationBean;
}
}
注解实现
为了能让 Spring 找到它,你需要在启动类上加上 @ServletComponentScan 注解
@WebFilter(filterName = "MyFilterWithAnnotation", urlPatterns = "/api/*")
public class MyFilterWithAnnotation implements Filter {
......
}
定义多个拦截器,并决定它们的执行顺序
@Component
public class MyFilter2 implements Filter {
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
String requestUri = request.getRequestURI();
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
@Configuration
public class MyFilterConfig {
@Autowired
MyFilter myFilter;
@Autowired
MyFilter2 myFilter2;
@Bean
public FilterRegistrationBean<MyFilter> setUpMyFilter() {
FilterRegistrationBean<MyFilter> filterRegistrationBean = new FilterRegistrationBean<>();
filterRegistrationBean.setOrder(2);
filterRegistrationBean.setFilter(myFilter);
filterRegistrationBean.setUrlPatterns(new ArrayList<>(Arrays.asList("/api/*")));
return filterRegistrationBean;
}
@Bean
public FilterRegistrationBean<MyFilter2> setUpMyFilter2() {
FilterRegistrationBean<MyFilter2> filterRegistrationBean = new FilterRegistrationBean<>();
filterRegistrationBean.setOrder(1);
filterRegistrationBean.setFilter(myFilter2);
filterRegistrationBean.setUrlPatterns(new ArrayList<>(Arrays.asList("/api/*")));
return filterRegistrationBean;
}
}
最后
以上就是大气大叔为你收集整理的如何自定义一个Filter 过滤器?Mybatis里使用FilterFilter是如何实现拦截的?SpringBoot里使用Filter定义多个拦截器,并决定它们的执行顺序的全部内容,希望文章能够帮你解决如何自定义一个Filter 过滤器?Mybatis里使用FilterFilter是如何实现拦截的?SpringBoot里使用Filter定义多个拦截器,并决定它们的执行顺序所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复