为什么从 JSP 检索 servlet 的初始化参数时得到 null?

Why I get null when retrieving servlet's init parameter from JSP?

我有 DD(web.xml 文件),代码非常简单:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>TestProject</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
  <servlet-name>test</servlet-name>
  <jsp-file>/result.jsp</jsp-file>

  <init-param>
  <param-name>email</param-name>
  <param-value>example@gmail.com</param-value>
  </init-param>
  </servlet>
  
  <context-param>
  <param-name>name</param-name>
  <param-value>Max</param-value>
  </context-param>
  
</web-app>

注意我有两个参数(一个在 application 中,另一个在 configuration 范围中)。当我尝试将它们放入 result.jsp 时:

<html><body>
Name is: <%=application.getInitParameter("name") %>
<br>
Email is: <%=config.getInitParameter("email") %>
</body></html>

,我得到以下输出:

Name is: Max 
Email is: null 

我的问题很简单:“email”参数是如何得到 NULL 的?我的 JSP 文件不应该“看到”我的配置方式和 return “example@gmail.com”吗?

那是你的整个 web.xml 文件吗?您是否有机会直接在浏览器中访问 JSP?喜欢:

http://localhost:8080/<yourAppContext>/result.jsp

如果是这样,那么您将收到以下回复:

Name is: Max
Email is: null 

没有错。没错。

你得到这个结果的原因是你没有通过你在web.xml中定义的配置访问JSP,你只是直接访问JSP,这在场景具有不同的隐式配置,这不是您认为正在配置的配置。

如果你想要这样的回复:

Name is: Max
Email is: example@gmail.com

然后你需要添加一个servlet映射。完整配置为:

<servlet>
    <servlet-name>test</servlet-name>
    <jsp-file>/result.jsp</jsp-file>

    <init-param>
        <param-name>email</param-name>
        <param-value>example@gmail.com</param-value>
    </init-param>
</servlet>

<servlet-mapping>
    <servlet-name>test</servlet-name>
    <url-pattern>/test</url-pattern>   
</servlet-mapping>

并且您需要访问此 URL,而不是 JSP 路径,具有:

http://localhost:8080/<yourAppContext>/test

您可能还想阅读这些:

  • Url Mapping For Jsp
  • Servlet JSP web.xml

为了进一步说明这一点,重要的是要提到您需要一个 servlet 映射才能发挥作用。如果您只是在 web.xml 中定义一个 servlet,它就在那里。您需要告诉服务器如何使用它,为此您使用 <servlet-mapping>。它告诉服务器对于路径上的请求,需要调用一些特定的 servlet 来处理请求

您可以创建此映射以使用 <servlet-class> 指向 servlet class 或使用 <jsp-file> 指向 JSP。它们基本上是同一件事,因为 JSP 最终变成了 servlet class.

我认为让您感到困惑的(基于下面的评论)是,对于 JSP 文件,您已经拥有服务器创建的一些隐式映射,如 .[=26= 所述]

当您直接访问 JSP 时,使用

http://localhost:8080/<yourAppContext>/result.jsp

您正在使用 隐式 服务器映射,其中不包含任何附加的特殊配置(例如您要发送给它的电子邮件)。

当您使用

访问 JSP 时
http://localhost:8080/<yourAppContext>/test

您正在访问您的映射。你可以随心所欲地配置它,并向它发送你想要的任何参数,你的 JSP 现在就可以读取它们了。