如何在Java Filter 中注入 Service
在项目中遇到一个问题,在 Filter中注入 Serivce失败,注入的service始终为null。如下所示:
public class WeiXinFilter implements Filter{
@Autowired
private UsersService usersService;
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
Users users = this.usersService.queryByOpenid(openid);
}
上面的 usersService 会报空指针异常。
解决方法一:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
ServletContext sc = req.getSession().getServletContext();
XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc);
if(cxt != null && cxt.getBean("usersService") != null && usersService == null)
usersService = (UsersService) cxt.getBean("usersService");
Users users = this.usersService.queryByOpenid(openid);
这样就行了。
方法二:
public class WeiXinFilter implements Filter{
private UsersService usersService;
public void init(FilterConfig fConfig) throws ServletException {
ServletContext sc = fConfig.getServletContext();
XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc);
if(cxt != null && cxt.getBean("usersService") != null && usersService == null)
usersService = (UsersService) cxt.getBean("usersService");
}
相关原理:
1. 如何获取 ServletContext:
1)在javax.servlet.Filter中直接获取
ServletContext context = config.getServletContext();
2)在HttpServlet中直接获取
this.getServletContext()
3)在其他方法中,通过HttpServletRequest获得
request.getSession().getServletContext();
2. WebApplicationContext 与 ServletContext (转自:http://blessht.iteye.com/blog/2121845):
Spring的 ContextLoaderListener是一个实现了ServletContextListener接口的监听器,在启动项目时会触发contextInitialized方法(该方法主要完成ApplicationContext对象的创建),在关闭项目时会触发contextDestroyed方法(该方法会执行ApplicationContext清理操作)。
ConextLoaderListener加载Spring上下文的过程
①启动项目时触发contextInitialized方法,该方法就做一件事:通过父类contextLoader的initWebApplicationContext方法创建Spring上下文对象。
②initWebApplicationContext方法做了三件事:创建 WebApplicationContext;加载对应的Spring文件创建里面的Bean实例;将WebApplicationContext放入 ServletContext(就是Java Web的全局变量)中。
③createWebApplicationContext创建上下文对象,支持用户自定义的上下文对象,但必须继承自ConfigurableWebApplicationContext,而Spring MVC默认使用ConfigurableWebApplicationContext作为ApplicationContext(它仅仅是一个接口)的实 现。
④configureAndRefreshWebApplicationContext方法用 于封装ApplicationContext数据并且初始化所有相关Bean对象。它会从web.xml中读取名为 contextConfigLocation的配置,这就是spring xml数据源设置,然后放到ApplicationContext中,最后调用传说中的refresh方法执行所有Java对象的创建。
⑤完成ApplicationContext创建之后就是将其放入ServletContext中,注意它存储的key值常量。
方法三:
直接使用spring mvc中的HandlerInterceptor或者HandlerInterceptorAdapter 来替换Filter:
public class WeiXinInterceptor implements HandlerInterceptor {
@Autowired
private UsersService usersService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// TODO Auto-generated method stub
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// TODO Auto-generated method stub
}
}
配置拦截路径:
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="net.xxxx.interceptor.WeiXinInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
Filter 中注入 Service 的示例:
public class WeiXinFilter implements Filter{
private UsersService usersService;
public void init(FilterConfig fConfig) throws ServletException {}
public WeiXinFilter() {}
public void destroy() {}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
String userAgent = req.getHeader("user-agent");
if(userAgent != null && userAgent.toLowerCase().indexOf("micromessenger") != -1){ // 微信浏览器
String servletPath = req.getServletPath();
String requestURL = req.getRequestURL().toString();
String queryString = req.getQueryString();
if(queryString != null){
if(requestURL.indexOf("mtzs.html") !=-1 && queryString.indexOf("LLFlag")!=-1){
req.getSession().setAttribute("LLFlag", "1");
chain.doFilter(request, response);
return;
}
}
String openidDES = CookieUtil.getValueByName("openid", req);
String openid = null;
if(StringUtils.isNotBlank(openidDES)){
try {
openid = DesUtil.decrypt(openidDES, "rxxxxxxxxxde"); // 解密获得openid
} catch (Exception e) {
e.printStackTrace();
}
}
// ... ...
String[] pathArray = {"/weixin/enterAppFromWeiXin.json", "/weixin/getWeiXinUserInfo.json",
"/weixin/getAccessTokenAndOpenid.json", "/sendRegCode.json", "/register.json",
"/login.json", "/logon.json", "/dump.json", "/queryInfo.json"};
List<String> pathList = Arrays.asList(pathArray);
String loginSuccessUrl = req.getParameter("path");
String fullLoginSuccessUrl = "http://www.axxxxxxx.cn/pc/";
if(requestURL.indexOf("weixin_gate.html") != -1){
req.getSession().setAttribute("loginSuccessUrl", loginSuccessUrl);
// ... ...
}
ServletContext sc = req.getSession().getServletContext();
XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc);
if(cxt != null && cxt.getBean("usersService") != null && usersService == null)
usersService = (UsersService) cxt.getBean("usersService");
Users users = this.usersService.queryByOpenid(openid);
// ... ...
if(pathList.contains(servletPath)){ // pathList 中的访问路径直接 pass
chain.doFilter(request, response);
return;
}else{
if(req.getSession().getAttribute(CommonConstants.SESSION_KEY_USER) == null){ // 未登录
String llFlag = (String) req.getSession().getAttribute("LLFlag");
if(llFlag != null && llFlag.equals("1")){ // 处理游客浏览
chain.doFilter(request, response);
return;
}
// ... ...// 3. 从腾讯服务器去获得微信的 openid ,
req.getRequestDispatcher("/weixin_gate.html").forward(request, response);
return;
}else{ // 已经登录
// 4. 已经登录时的处理
chain.doFilter(request, response);
return;
}
}
}else{ // 非微信浏览器
chain.doFilter(request, response);
}
}
}
如何在Java Filter 中注入 Service的更多相关文章
- 如何在Java的Filter中注入Service???
今天在做用户使用cookie自动登录的时候,发现在LoginFilter中读取到cookie以后要进行查询数据库然后进行用户名和密码的比对,查询数据库肯定要用到Service和Dao,一开始我以为在s ...
- 在Java filter中调用service层方法
在项目中遇到一个问题,在 Filter中注入 Serivce失败,注入的service始终为null.如下所示: public class WeiXinFilter implements Filter ...
- 关于如何在Listener中注入service和ServletContextListener源码分析
今天在做项目时突然发现我该如何向listener中注入service对象,因为监听器无法使用注解注入. 此时有人会想用以下代码通过xml的方式注入: ApplicationContext cont ...
- Spring框架中,在工具类或者普通Java类中调用service或dao
spring注解的作用: 1.spring作用在类上的注解有@Component.@Responsity.@Service以及@Controller:而@Autowired和@Resource是用来修 ...
- java多线程中注入Spring对象问题
web应用中java多线程并发处理业务时,容易抛出NullPointerException. 原因: 线程中的Spring Bean没有被注入.web容器在启动时,没有提前将线程中的bean注入,在线 ...
- Filter 中注入失败问题
参考: https://www.cnblogs.com/digdeep/p/4770004.html?tvd https://www.cnblogs.com/EasonJim/p/7666009.ht ...
- 如何在java程序中调用linux命令或者shell脚本
转自:http://blog.sina.com.cn/s/blog_6433391301019bpn.html 在java程序中如何调用linux的命令?如何调用shell脚本呢? 这里不得不提到ja ...
- 如何在Java 8中愉快地处理日期和时间
Java 8新增了LocalDate和LocalTime接口,为什么要搞一套全新的处理日期和时间的API?因为旧的java.util.Date实在是太难用了. java.util.Date月份从0开始 ...
- 如何在java项目中使用lucene
lucene是一个开源的全文检索引擎工具包,但它不是一个成型的搜索引擎,它的功能就是负责将文本数据按照某种分词算法进行分词,分词后的结果存储在索引库中,然后根据关键字从索引库检检索. 那么应该如何使用 ...
随机推荐
- python内置模块(1)
Python的模块在其它语言中通常称为库或类库,也就是lib.它是编程语言的第三级封装,第四级则是包,也就是模块的打包组合,而前两级分别是函数和类.封装的好处,自然不用多言,高内聚,松耦合,减少代码重 ...
- 关于ASP.NET MVC开发设计中出现的问题与解决方案汇总 【持续更新】
最近一直用ASP.NET MVC 4.0 +LINQ TO SQL来开发设计公司内部多个业务系统网站,在这其中发现了一些问题,也花了不少时间来查找相关资料或请教高人,最终都还算解决了,现在我将这些问题 ...
- 网络编程:socket--python核心编程(3),chapter 1
最近两天把第一部分的网络编程socket好好学习了一番,收获也蛮多的... 套接字:能使运行在不同或相同计算机上运行的进行通信:套接字一种是基于文件的(同一台计算机进程间通信),另一种是基于网络的(同 ...
- 高级四则运算器—结对项目反思(193 & 105)
高级四则运算器—结对项目反思(193 & 105) 本周我和一位韩国同学(71061105)一起结对编程完成了我们的结对项目——高级的小学四则运算题目生成器. PSP表格 PSP2.1 P ...
- [Architect] Abp 框架原理解析(3) DynamicFilters
本节目录 介绍 定义Filter 设置Filter 这是Abp中多租户.软删除.激活\禁用等如此方便的原因 Install-Package EntityFramework.DynamicFilters ...
- eclipse svn插件安装方法
eclipse svn插件安装方法 使用dropins安装插件 从Eclipse3.5开始,安装目录下就多了一个dropins目录.只要将插件解压后拖到该目录即可安装插件.比如安装svn插件subcl ...
- JS 对象属性相关--检查属性、枚举属性等
1.删除属性 delete运算符可以删除对象的属性 delete person.age //即person不再有属性age delete person['age'] //或者这样 delete只是断开 ...
- ok6410 android driver(5)
Test the android driver by JNI (Java Native Interface), In the third article, we know how to compile ...
- asp.net mvc中包含webapi时,token失效产生302的解决方案
public void ConfigureAuth(IAppBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOpt ...
- C#创建服务及使用程序自动安装服务,.NET创建一个即是可执行程序又是Windows服务的exe
不得不说,.NET中安装服务很麻烦,即要创建Service,又要创建ServiceInstall,最后还要弄一堆命令来安装和卸载. 今天给大家提供一种方式,直接使用我们的程序来安装/卸载服务,并且可以 ...