如何解决找不到方法HttpServletRequest.getServletContext() ---- NoSuchMethodError

报错

java.lang.NoSuchMethodError:

javax.servlet.http.HttpServletRequest.getServletContext()Ljavax/servlet/ServletContext;

 

造成问题的原因

 

ServletRequest的getServletContext方法是Servlet3.0添加的,这个可以看一下官方文档

http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getServletContext()

而Tomcat6只支持到Servlet2.5看它的官方文档可以知道,要用J2EE6的话得换成Tomcat7

http://tomcat.apache.org/tomcat-6.0-doc/index.html

旧版本需要先用request拿到HttpSession或者通过

 

修改方法

//String contextPath = req.getServletContext().getContextPath(); // 
        /**
         * ServletRequest的getServletContext方法是Servlet3.0添加的,这个可以看一下官方文档
            http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getServletContext()
            而Tomcat6只支持到Servlet2.5看它的官方文档可以知道,要用J2EE6的话得换成Tomcat7
         * 
         * */        
        String contextPath = null;
        if(req instanceof HttpServletRequest){
            HttpServletRequest hreq = (HttpServletRequest) req;
            contextPath = hreq.getSession().getServletContext().getContextPath();
        }

 

posted @ 2015-07-03 15:15  jmStatham  阅读(9036)  评论(0编辑  收藏  举报