【发布时间】:2015-04-14 09:06:18
【问题描述】:
大家好,我是 servlet 和 jsp 的新手 我不清楚 servletconfig 接口和 servletcontext 接口 我再次启动 jsp 我遇到了 PageContext 一词。 所以任何人都会用一个很好的例子来解释我这些术语。
jsp中的servletconfig接口和servletcontext接口和PageContext
【问题讨论】:
大家好,我是 servlet 和 jsp 的新手 我不清楚 servletconfig 接口和 servletcontext 接口 我再次启动 jsp 我遇到了 PageContext 一词。 所以任何人都会用一个很好的例子来解释我这些术语。
jsp中的servletconfig接口和servletcontext接口和PageContext
【问题讨论】:
ServletConfig
ServletConfig 对象由 Web 容器创建,用于在初始化期间将信息传递给每个 servlet。该对象可用于从 web.xml 文件中获取配置信息。
何时使用: 如果不时修改任何特定内容。 您可以通过编辑 web.xml 中的值来轻松管理 Web 应用程序,而无需修改 servlet
你的 web.xml 看起来像:
<web-app>
<servlet>
......
<init-param>
<!--here we specify the parameter name and value -->
<param-name>paramName</param-name>
<param-value>paramValue</param-value>
</init-param>
......
</servlet>
</web-app>
这样你就可以在 servlet 中获得价值:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//getting paramValue
ServletConfig config=getServletConfig();
String driver=config.getInitParameter("paramName");
}
ServletContext
Web 容器为每个 Web 应用程序创建一个 ServletContext 对象。该对象用于从 web.xml 中获取信息
何时使用: 如果您想将信息共享给所有的 sevlet,最好让所有的 servlet 都可以使用它。
web.xml 看起来像:
<web-app>
......
<context-param>
<param-name>paramName</param-name>
<param-value>paramValue</param-value>
</context-param>
......
</web-app>
这样你就可以在 servlet 中获得价值:
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
//creating ServletContext object
ServletContext context=getServletContext();
//Getting the value of the initialization parameter and printing it
String paramName=context.getInitParameter("paramName");
}
PageContext
是jsp中的类,它的隐含对象pageContext用于设置、获取或删除以下作用域的属性:
1.页
2.请求
3.会话
4.应用
【讨论】:
ServletConfig 由 GenericServlet(它是 HttpServlet 的超类)实现。它允许应用程序部署者将参数传递给 servlet(在 web.xml 全局配置文件中),并且 servlet 在其初始化期间检索这些参数。
例如,您的 web.xml 可能如下所示:
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.company.(...).MyServlet</servlet-class>
<init-param>
<param-name>someParam</param-name>
<param-value>paramValue</param-value>
</init-param>
</servlet>
在您的 servlet 中,可以像这样检索“someParam”参数:
public class MyServlet extends GenericServlet {
protected String myParam = null;
public void init(ServletConfig config) throws ServletException {
String someParamValue = config.getInitParameter("someParam");
}
}
ServletContext 有点不同。它的名字很糟糕,您最好将其视为“应用程序范围”。
它是一个应用程序范围的范围(想想“地图”),您可以使用它来存储不特定于任何用户的数据,而是属于应用程序本身的数据。它通常用于存储参考数据,例如应用程序的配置。
您可以在 web.xml 中定义 servlet-context 参数:
<context-param>
<param-name>admin-email</param-name>
<param-value>admin-email@company.com</param-value>
</context-param>
然后在您的 servlet 中像这样在您的代码中检索它们:
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
String adminEmail = getServletContext().getInitParameter("admin-email"));
}
【讨论】:
init() 方法的目的:让您在 servlet 实际暴露给外部世界之前读取 init-params(参见名称中的“init”?)并执行所需的初始化任务。