为什么我们使用servletconfig接口和servletcontext接口

时间:2015-04-14 09:06:18

标签: java jsp servlets

大家好我是servlet和jsp的新手我不清楚 servletconfig接口和servletcontext接口我再次启动jsp我遇到了一个术语PageContext。 所以任何机构都用一个很好的例子来解释这些术语。

servletconfig接口和servletcontext接口以及jsp中的PageContext

2 个答案:

答案 0 :(得分:18)

<强>的ServletConfig

ServletConfig对象由Web容器创建,用于在初始化期间将信息传递给servlet。此对象可用于从web.xml文件中获取配置信息。

何时使用: 如果任何特定内容不时被修改。 您可以轻松管理Web应用程序,无需通过编辑web.xml中的值来修改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.page

2.request

3.session

4.应用

答案 1 :(得分:7)

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有点不同。名字很糟糕,你最好把它想象成“应用范围”。

这是一个应用程序范围(想想“map”),您可以使用它来存储不是特定于任何用户的数据,而是属于应用程序本身。它通常用于存储参考数据,如应用程序的配置。

您可以在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")); 
}
相关问题