【问题标题】:Servet: Receive JSP File does not exist in WebContentServet:接收 JSP 文件在 WebContent 中不存在
【发布时间】:2026-02-09 15:10:01
【问题描述】:

我正在使用 Eclipse 来编写 servlet。现在,我想让example.jsp 执行类似 servlet 的操作(ServletConfig、ServletContext 的访问属性或参数...)

我把example.jsp放在WebContent上面,项目名是ProjectExample。

在 web.xml 中,这是我声明这个 servlet 的方式:

<servlet>
    <servlet-name>JSP Example</servlet-name>
    <jsp-file>example.jsp</jsp-file>  
    <init-param>
      <param-name>name</param-name>
      <param-value>hqt</param-value>
    </init-param>
// I meet warning at <jsp-file>: that doesn't found this file 
//although I have change to: `/example.jsp`, `ProjectExample/example.jsp` or `/ProjectExample/example.jsp`
</servlet>

因为Container不识别这个文件,所以当我使用:getServletConfig().getInitParameter("name")我会收到null!!!

请告诉我如何解决这个问题。

谢谢:)

@: 如果在代码中输入错误,那不是问题,因为它只是拼写错误。我不知道为什么 * 不再允许复制/粘贴功能了。

【问题讨论】:

    标签: eclipse jsp servlets web.xml


    【解决方案1】:

    我认为主要问题不在于你的配置,而在于 jsp 页面的配置方式。

    更改您的 &lt;jsp-file&gt;/example.jsp&lt;/jsp-file&gt; 并将其添加到 JSP:

    Who am I? -> <%= getServletName() %>
    

    我的盒子输出是:

    Who am I? -> jsp
    

    这是因为所有 JSP 共享同一个称为“jsp”的 servlet 配置。它在 $CATALINE_HOME/conf/web.xml 中配置(如果您使用的是 Tomcat)。对于我的 Tomcat 7,配置如下所示:

    <servlet>
        <servlet-name>jsp</servlet-name>
        <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
        <init-param>
            <param-name>fork</param-name>
            <param-value>false</param-value>
        </init-param>
        <init-param>
            <param-name>xpoweredBy</param-name>
            <param-value>false</param-value>
        </init-param>
        <load-on-startup>3</load-on-startup>
    </servlet>
    

    【讨论】:

    • 注意:这是特定于 tomcat 的,其他服务器可能工作方式不同
    • 注意:Eclipse 会将您的 $CATALINE_HOME/conf/web.xml 复制到您的工作区(以防您决定删除 jsp servlet 并检查会发生什么)
    【解决方案2】:

    你的servlet应该有init方法,在那里你可以读取你需要的参数:

    public class SimpleServlet extends GenericServlet {
        protected String myParam = null;
    
        public void init(ServletConfig servletConfig) throws ServletException{
            this.myParam = servletConfig.getInitParameter("name");
          }
    
        //your servlet code...
    }
    

    这个例子取自here

    【讨论】: