您的位置:首页 > 其它

转servlet的高级应用

2009-06-28 13:10 302 查看
1:Filter(过滤器)

Filter是servlet2.3规范中新增加的,Filter并不是servlet,他不会对请求产生产生响应,但是他可以改变请求的内容,并且可以产生自己的相应。Filter是可重用的,当你在web应用中部署了一个Filter时,所有发送给这个应用的请求都要先经过这个Filter的处理。

Filter的用处:

1:访问限制

2:日志记录

3:访问资源的转换(如xslt)

4:压缩及加密

编写Filter

一个filter 必须实现javax.servlet.Filter 接口,即实现下面的三个方法:

1:void init(FilterConfig config) throws ServletException

2:void destroy()

3:void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException

在init方法中你可以定义初始化一些Filter中用到的参数,或者从web.xml中读取这些参数。

destroy方法是doFilter执行完毕后调用的方法

doFilter是编写Filter的核心方法,在这个方法中编写你的过滤代码。

实例

假定我们要限定网络地址处于202.117.96段的用户访问我们的应用,可以这样编写Filter:

import java.servlet.*;

public class MyFilter1 implements Filter {

protected FilterConfig filterConfig = null;

public void init(FilterConfig filterConfig) throws ServletException {

this.filterConfig = filterConfig;

}

public void doFilter(ServletRequest request, ServletResponse response,

FilterChain chain)

throws IOException, ServletException {

String remoteIP=request.getRemoteAddr();

int n=remoteIP.lastIndexOf(".");

String s=remoteIP.substring(0,n);

if(s.equals("202.117.96")) {

PrintWriter out = response.getWriter();

out.println("<html><head></head><body>");

out.println("<h1>对不起,你没有权利访问这个应用</h1>");

out.println("</body></html>");

out.flush();

return;

}

chain.doFilter(request, response);

}

public void destroy() {

this.filterConfig = null;

}

上面的Filter首先判断用户的ip,然后截取其网络地址,与我们屏蔽的网段比较,如果属于屏蔽的网段,则向客户端发送响应,并返回。这样其它的Filter和servlet就不会执行。如果不属于此网段,则调用FilterChain的doFilter方法,将请求交给下一个Filter处理。

以前在servlet处理包含中文的请求时总是很麻烦,servlet2.3中增加一个新的方法setCharacterEncoding用来设置请求的编码,我们可以编写一个设置编码的Filter,这样你就不必在你的每个servlet中调用这个函数,如果编码的类型改变,你只需改变一下web.xml中的参数,而Filter和servlet的代码则不用改变。



import java.servlet.*;

public class MyFilter2 implements Filter {

protected String encoding = null;

public void init(FilterConfig filterConfig) throws ServletException {

this.encoding = filterConfig.getInitParameter("encoding");

}

public void doFilter(ServletRequest request, ServletResponse response,

FilterChain chain)

throws IOException, ServletException {

if (request.getCharacterEncoding() == null) {

request.setCharacterEncoding(encoding);

}

chain.doFilter(request, response);

}

public void destroy() {

this.encoding = null;

}

上面代码中的encoding是在web.xml中指定的。

部署

在web.xml描述实例2

<web-app>

<filter>

<filter-name>Filter2</filter-name> //这里是Filter的名字,随便你怎么起

<filter-class>Myfilter2</filter-class> //Filter的类名,注意包含package

<init-param>

<param-name>encoding</param-name>

<param-value>gb2312</param-value>

</init-param>

</filter>

<filter-mapping>

<filter-name>Filter2</filter-name>//与上面的保持一致

<url-pattern>/servlet/*</url-pattern> //对所有资源应用此filter

</filter-mapping>

</web-app>

如果一个应用有多个Filter,则在web.xml文件中,<filter-mapping>靠前的filter先执行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: