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

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中没有。

posted @ 2015-12-28 21:50  浮白斋主人  阅读(311)  评论(0编辑  收藏  举报