Search code examples
eclipsejspscriptlet

jsp The method getServletContext() is undefined for the type in eclipse


I am using the eclipse helper for Java EE development. I am developing a Struts web application. In a JSP page I use code like this

<script type="text/javascript" src="<%out.print(getServletContext().getContextPath());%>/js/jquery.js"></script>
<link rel="stylesheet" href="<%out.print(getServletContext().getContextPath());%>/css/home.css" />

When I run my server this page works correctly. However, Eclipse shows an error on getServletContext()

The method getServletContext() is undefined for the type __2F_Compiler_2F_WebContent_2F_pages_2F_home_2E_jsp

Here's a screenshot:

screenshot

Because the page works correctly, I'd like to hide this error in Eclipse. How can I do that?


Solution

  • I can't speak for Eclipse's mistake, but in this specific case, you should be using the implicit JSP scriptlet variable application and not be using HttpServlet-inherited methods.

    <script type="text/javascript" src="<%out.print(application.getContextPath());%>/js/jquery.js"></script>
    <link rel="stylesheet" href="<%out.print(application.getContextPath());%>/css/home.css" />
    

    Unrelated to the concrete problem, this is a 90's way of writing JSPs which is officially discouraged since JSP 2.0 which was released more than a decade ago. Are you sure you're reading up to date resources while learning JSP? You should be using EL expressions instead.

    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.js"></script>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/css/home.css" />
    

    Or, via <c:set> to save the boilerplate:

    <c:set var="root" value="${pageContext.request.contextPath}" />
    ...
    <script type="text/javascript" src="${root}/js/jquery.js"></script>
    <link rel="stylesheet" href="${root}/css/home.css" />
    

    See also: