jSTL之在 Scriptlet 和 EL 中使用 ServletContext 和 ServletConfig

duanxz 阅读:17 2024-10-17 08:59:04 评论:0

我尝试运行以下几行。

<%=application.getInitParameter("tagline")%>                
<br /> 
<%=config.getInitParameter("admincontact")%> 
 
${initParam.tagline} 
<br /> 
${pageContext.servletConfig.initParameter("admincontact")} 

我的 web.xml 是

<servlet> 
<jsp-file>/index.jsp</jsp-file> 
<init-param> 
    <param-name>admincontact</param-name> 
    <param-value>8939302763</param-value>   
</init-param> 
</servlet> 
    <context-param> 
<param-name>tagline</param-name> 
<param-value>Each one Plant one</param-value> 

我在 ${pageContext.servletConfig.initParameter("admincontact")} 和空值 <%=config.getInitParameter("admincontact")%> .

问候, 约翰

请您参考如下方法:

有一个FAQ on JavaRanch关于这个。

声明如下;

How to access servlet init parameters using EL?

You cannot use the following syntax to access servlet init parameters:

${pageContext.servletConfig.initParameter.name}

You cannot get Servlet init parameters using this technique. The getInitParameter(java.lang.String name) does not fit in this case, because it requires some arguments.

According to the JavaBean spec, the property has getter & setter methods in the form

public type1 getXXX() -- WITH NO ARGUMENTS.

public void setXXX(type1)

Now consider the pageContext as bean Object. The PageContext class has methods like getServletConfig(), getRequest(), getSession() etc. You can access these like pageContext.page, pageContext.request etc in EL.

ServletContext object has a couple of methods like getMajorVersion(), getMinorVersion() with no args. so we can access these methods treating it as properties to sevletContext bean as pageContext.servletContext.majorVersion and pageContext.servletContext.minorVersion.

If you want to access Servlet init parameters using EL, then it is better to create a Map of the init parameters for the servlet and place it in the request as a scoped variable -- let's say initParameters. You would then be able to obtain any param by name with ${requestScope.initParameters.name}.

NOTE:

We can access context init parameters with ${initParam.name}


标签:Servlet
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号