• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

如何在Java Filter 中注入 Service

java 搞代码 4年前 (2022-01-09) 15次浏览 已收录 0个评论

在项目中遇到一个问题,在 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 = (HttpServletRequ

本文来源gao!%daima.com搞$代*!码$网3

est)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/&quot;; 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);
}
}}


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:如何在Java Filter 中注入 Service

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址