首页 > 其他 > 详细

struts2-(1)使用Filter作为控制器

时间:2015-12-28 23:16:17      阅读:151      评论:0      收藏:0      [点我收藏+]

1.使用filter作为控制器

(1)创建类,实现javax.servlet.Filter

package com.controller.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestFilter implements Filter{

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)arg0;
        HttpServletResponse response = (HttpServletResponse)arg1;
        //1.获取servletPath
        String servletPath = request.getServletPath();
        //2.判断servletPath若是input.action,则转发到input.html
        String path = null;
        
        if("/input.action".equals(servletPath)){
                path = "/service/input.html";
        }else if("/detail.action".equals(servletPath)){
            path = "/service/detail.html";
        }
        
        if(path != null){
            request.getRequestDispatcher(path).forward(request, response);
        }
        
        return;
        
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub
        
    }

    

}

(2)配置web.xml,和servlet基本一样

<filter>
        <filter-name>productFilter</filter-name>
        <filter-class>com.controller.filter.TestFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>productFilter</filter-name>
        <url-pattern>*.action</url-pattern>
    </filter-mapping>

2.filter和servlet的區別

(1) Servlet可以做的,Filter都可以完成。

(2) Servlet不擅长拦截资源。filter里面有一个FilterChain,可以不停地把请求传递给下一个拦截器。而Servlet的API中没有。

struts2-(1)使用Filter作为控制器

原文:http://www.cnblogs.com/fubaizhaizhuren/p/Filter.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!