问题描述
Filter拦截记录用户请求代码如下:publicclassLogfilterimplementsFilter{privateFilterConfigconfig;publicvoiddestroy(){//TODOAuto-generatedmethodstubthis.config=null;}publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChainchain)throwsIOException,ServletException{//TODOAuto-generatedmethodstub26:ServletContextcontext=this.config.getServletContext();longbefore=System.currentTimeMillis();System.out.println("开始过滤...");HttpServletRequesthrequest=(HttpServletRequest)request;context.log("Filter已经截获用户的请求地址:"+hrequest.getServletPath());try{chain.doFilter(request,response);}catch(Exceptione){e.printStackTrace();}longafter=System.currentTimeMillis();context.log("过滤结束!");context.log("请求被定位到:"+((HttpServletRequest)request).getRequestURI()+"所用时间为:"+(after-before));}publicvoidinit(FilterConfigfilterConfig)throwsServletException{//TODOAuto-generatedmethodstubthis.config=config;}}作用是记录所有请求,但不拦截,编译通过测试时报错:严重:Servlet.service()forservletjspthrewexceptionjava.lang.NullPointerExceptionatprimary.filter.Logfilter.doFilter(Logfilter.java:26)(Logfilter.java:26既ServletContextcontext=this.config.getServletContext();)不睡觉在线等高手答案~~~
解决方案
解决方案二:
privateFilterConfigconfig;这个对象什么时候赋值的呢?没赋值当然会出现空指针异常啦
解决方案三:
如何在XML中配置参数让init,this.config=config;来初始化呢怎么弄都时ServletContextcontext=this.config.getServletContext();空指针
解决方案四:
publicvoidinit(FilterConfigfilterConfig)throwsServletException{//TODOAuto-generatedmethodstubthis.config=config;}把里面的this.config=config;改为this.config=filterConfig;即可
解决方案五:
该回复于2009-07-18 00:21:53被版主删除
解决方案六:
3楼答案正确
解决方案七:
你也可以把第26行,写到init方法里面去。