嗨,我在servlet和jsp中都是新手,我对servletconfig接口和servletcontext接口不太清楚,我再次启动jsp,我遇到了术语jsp。所以任何一个人都会用一个很好的例子来解释这个词。
jsp中的servletconfig接口、servletcontext接口和PageContext
发布于 2015-04-14 12:30:38
ServletConfig
ServletConfig对象是由web容器为每个servlet创建的,用于在initialization.This对象可以从web.xml文件中获取配置信息的过程中将信息传递给servlet。
何时使用:,如果任何特定内容不时被修改。通过编辑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获取信息。
何时使用: --如果您想要将信息共享给所有的服务器端,这是使所有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.page
2.request
3.session
4.application
发布于 2015-04-14 09:18:35
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-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"));
}https://stackoverflow.com/questions/29623323
复制相似问题