[英]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>
請注意,我有兩個參數(一個在應用程序中,另一個在配置范圍內)。 當我嘗試將它們放入result.jsp中時:
<html><body>
Name is: <%=application.getInitParameter("name") %>
<br>
Email is: <%=config.getInitParameter("email") %>
</body></html>
,我得到以下 output:
Name is: Max
Email is: null
我的問題很簡單:我是如何獲得“電子郵件”參數的 NULL 的? 我的 JSP 文件不應該“查看”我如何配置它並返回“example@gmail.com”嗎?
這是您的整個web.xml
文件嗎? 您是否有機會直接在瀏覽器中訪問 JSP? 喜歡:
http://localhost:8080/<yourAppContext>/result.jsp
如果是這種情況,那么您將收到以下響應:
Name is: Max
Email is: null
這沒有錯。 它是正確的。
The reason you get this result is that you are not accessing the JSP through the configuration you defined in web.xml
, you are just accessing the JSP directly, which behind the scene has a different implicit configuration, and it's not the one you think you正在配置。
如果你想要這個回應:
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
您可能還想閱讀以下內容:
為了進一步推動這一點,重要的是要提到您需要一個 servlets 的映射才能有用。 如果您只是在web.xml
中定義一個 servlet,它就在那里。 您需要告訴服務器如何使用它,為此您需要使用<servlet-mapping>
。 它對服務器說,對於路徑上的請求,需要調用一些特定的 servlet 來處理請求。
您可以創建此映射以使用<servlet-class>
指向 servlet class 或使用<jsp-file>
指向 JSP 。 它們基本上是一樣的,因為 JSP 最終會變成 servlet class。
我認為讓您感到困惑的是(基於下面的評論),對於 JSP 文件,您已經有一些由服務器創建的隱式映射,如此處所述。
當您直接訪問 JSP 時,使用
http://localhost:8080/<yourAppContext>/result.jsp
您正在使用不包含附加特殊配置的隱式服務器映射(例如您要發送給它的 email)。
當您訪問 JSP 時
http://localhost:8080/<yourAppContext>/test
您正在訪問您的映射。 您可以根據需要進行配置,並發送您想要的任何參數,您的 JSP 現在將能夠讀取它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.