如何在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是一个开源的全文检索引擎工具包,但它不是一个成型的搜索引擎,它的功能就是负责将文本数据按照某种分词算法进行分词,分词后的结果存储在索引库中,然后根据关键字从索引库检检索. 那么应该如何使用 ...
随机推荐
- Velocity魔法堂系列一:入门示例
一.前言 Velocity作为历史悠久的模板引擎不单单可以替代JSP作为Java Web的服务端网页模板引擎,而且可以作为普通文本的模板引擎来增强服务端程序文本处理能力.而且Velocity被移植到不 ...
- 第一个sprint总结和读后感
总结:通过第一个sprint的冲刺,了解了sprint的整个流程,学会了在一个团队里该如何开展一个项目和分配任务.我们的队团在第一个sprint中没有达到我们预期的效果,我们也做出了反省,原因一是我们 ...
- 字符串hash + 二分答案 - 求最长公共子串 --- poj 2774
Long Long Message Problem's Link:http://poj.org/problem?id=2774 Mean: 求两个字符串的最长公共子串的长度. analyse: 前面在 ...
- C#设计模式——职责链模式(Chain Of Responsibility Pattern)
一.概述 在软件开发中,某一个对象的请求可能会被多个对象处理,但每次最多只有一个对象处理该请求,对这类问题如果显示指定请求的处理对象,那么势必会造成请求与处理的紧耦合,为了将请求与处理解耦,我们可以使 ...
- 【EF 译文系列】重试执行策略的局限性(EF 版本至少为 6)
原文链接:Limitations with Retrying Execution Strategies (EF6 onwards) 当使用重试执行策略的时候,大体有以下两种局限性: 不支持以流的方式进 ...
- JS代码的位置与事件响应代码块的封装问题
JS代码的位置 我们可以将JavaScript代码放在html文件中任何位置,但是我们一般放在网页的head或者body部分. 放在<head>部分最常用的方式是在页面中h ...
- iis7.5错误 配置错误
iis7.5详细错误 HTTP 错误 500.19 - Internal Server Error无法访问请求的页面,因为该页的相关配置数据无效. 详细错误信息模块 IIS Web Core 通知 ...
- 根据数据库输出XML菜单
USE [test_YTHH] GO /****** Object: StoredProcedure [dbo].[usp_Print_SCC_Menu] Script Date: 04/08 ...
- 2. npm 的使用
NPM是随同NodeJS一起安装的包管理工具,能解决NodeJS代码部署上的很多问题,常见的使用场景有以下几种: 允许用户从NPM服务器下载别人编写的第三方包到本地使用. 允许用户从NPM服务器下载并 ...
- php表单中如何获取单选按钮与复选按钮的值
php代码中获取表单中单选按钮的值:(单选按钮只能让我们选择一个,这里有一个"checked"属性,这是用来默认选取的,我们每次刷新我们的页面时就默认为这个值.) 例:<fo ...