Commit 67c8df0d335ad5256e5de36bc733ed5e53bf1c73
1 parent
87b7c26f
不同仓库分配不同数据库:filter拦截所有请求,将warehouseCode值存入serlvetContext中
Showing
2 changed files
with
46 additions
and
1 deletions
src/main/java/com/huaheng/framework/config/DruidConfig.java
... | ... | @@ -78,7 +78,11 @@ public class DruidConfig |
78 | 78 | */ |
79 | 79 | @Bean |
80 | 80 | public FilterRegistrationBean druidStatFilter() { |
81 | - FilterRegistrationBean bean = new FilterRegistrationBean(new WebStatFilter()); | |
81 | + // FilterRegistrationBean bean = new FilterRegistrationBean(new WebStatFilter()); | |
82 | + FilterRegistrationBean<TestFilter> bean = new FilterRegistrationBean<TestFilter>(); | |
83 | + bean.setFilter(new TestFilter());//注册自定义过滤器 | |
84 | + bean.setName("flilter1");//过滤器名称 | |
85 | + bean.setOrder(1);//优先级,最顶级 | |
82 | 86 | //添加过滤规则. |
83 | 87 | bean.addUrlPatterns("/*"); |
84 | 88 | //添加不需要忽略的格式信息. |
... | ... |
src/main/java/com/huaheng/framework/config/TestFilter.java
0 → 100644
1 | +package com.huaheng.framework.config; | |
2 | + | |
3 | +import com.huaheng.framework.aspectj.lang.constant.DataSourceName; | |
4 | +import com.huaheng.framework.datasource.DynamicDataSourceContextHolder; | |
5 | + | |
6 | +import javax.servlet.*; | |
7 | +import javax.servlet.FilterConfig; | |
8 | +import javax.servlet.http.HttpServletRequest; | |
9 | +import javax.servlet.http.HttpSession; | |
10 | +import java.io.IOException; | |
11 | + | |
12 | +public class TestFilter implements Filter { | |
13 | + @Override | |
14 | + public void init(FilterConfig filterConfig) throws ServletException { | |
15 | + | |
16 | + } | |
17 | + | |
18 | + @Override | |
19 | + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { | |
20 | + HttpServletRequest req=(HttpServletRequest)request; | |
21 | + System.out.println("自定义过滤器filter触发,拦截url:"+req.getRequestURI()); | |
22 | + try { | |
23 | + ServletContext servletContext = req.getServletContext(); | |
24 | + String warehouseCode = request.getParameter("warehouseCode"); | |
25 | + if(warehouseCode!=null){ | |
26 | + servletContext.setAttribute("warehouseCode",warehouseCode); | |
27 | + } | |
28 | + if(servletContext.getAttribute("warehouseCode")!=null&&servletContext.getAttribute("warehouseCode").equals("CS0001")) { | |
29 | + DynamicDataSourceContextHolder.setDB(DataSourceName.SLAVE); | |
30 | + } | |
31 | + chain.doFilter(request, response); | |
32 | + } finally { | |
33 | + DynamicDataSourceContextHolder.clearDB(); | |
34 | + } | |
35 | + } | |
36 | + | |
37 | + @Override | |
38 | + public void destroy() { | |
39 | + | |
40 | + } | |
41 | +} | |
... | ... |