ServletConfig

每个servlet对应一个ServletConfig对象,不可以被其他servlet访问。

作用:

1.通过下面防范访问web.xml文件:

ServletConfig.getInitParameter(String name)

其中web.xml需要配置如下:

<servlet>
    <servlet-name>loginServlet01</servlet-name>
    <servlet-class>LoginServlet</servlet-class>
    <init-param>
        <param-name>name1</param-name>
        <param-value>value1</param-value>
    </init-param>
    <init-param>
        <param-name>name2</param-name>
        <param-value>value2</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>loginServlet01</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>

2.通过如下方法获得ServletContext

ServletConfig.getServletContext()

 

FilterConfig

和ServletConfig用法类似,应为Filter可以看成加强版的servlet,web.xml的配制方法如下:

    <filter>
        <filter-name>authority</filter-name>
        <filter-class>lee.AuthorityFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>GBK</param-value>
        </init-param>
        <init-param>
            <param-name>loginPage</param-name>
            <param-value>login.jsp</param-value>
        </init-param>
        <init-param>
            <param-name>proLogin</param-name>
            <param-value>proLogin.jsp</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>authority</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

 

ServletContext

号称是servlet中最大的类,一个WEB应用(application级)只对应一个ServletContext对象,所有servlet共享一个ServletContext对象。

作用:

1.应用是所有servlet共享,可以用来共享数据。

使用如下方法:

ServletContext.getAttribute(String name)
ServletContext.setAttribute(String name, Object value)

2.获取web.xml的数据,其中web.xml配置如下:

    <context-param>
        <param-name>driver</param-name>    
        <param-value>com.mysql.jdbc.Driver</param-value>
    </context-param>
    <context-param>
        <param-name>url</param-name>    
        <param-value>jdbc:mysql://localhost:3306/z01</param-value>
    </context-param>
    <context-param>
        <param-name>user</param-name>
        <param-value>root</param-value>
    </context-param>
    <context-param>
        <param-name>password</param-name>
        <param-value>123</param-value>
    </context-param>

3.servlet转发

ServletContext.getRequestDispatcher(String path)

4.读取资源文件

ServletContext.getRealPath(String path)
ServletContext.getResource(String path)
ServletContext.getResourceAsStream(String path)

说明:ServletContext.getRealPath这个方法可以很方便的把web路径换成实际路径。

 

posted on 2013-11-24 11:13  洋葱骑士  阅读(1602)  评论(0编辑  收藏  举报