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

时间:2021-09-14 07:35:24

报错

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();
}