关闭

简单项目开发之一(springmvc+filter)

标签: filterspring mvc框架
589人阅读 评论(0) 收藏 举报
   前面的框架搭建已经基本完成,后面的开发我们就在这个简单架子的基础上做开发,这一篇先加过滤器filter

一:准备过滤器处理类AuditFilter(主类)和AuditHandler(实际处理类)
AuditFilter的代码如下:

package com.template.filter;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;


public class AuditFilter implements Filter {

    private AuditHandler auditHandler;

    private String appName;

    public AuditFilter() {}

    public AuditFilter(AuditHandler auditHandler) {
        this.auditHandler = auditHandler;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        auditHandler.auditRequest(appName,request);
        chain.doFilter(request, response);
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        appName = filterConfig.getInitParameter("appName");
    }

    public void destroy() {}
}

AuditHandler的代码如下:

package com.template.filter;

import javax.servlet.ServletRequest;

import org.apache.log4j.Logger;

public class AuditHandler {

    private static Logger logger = Logger.getLogger(AuditHandler.class); 

    public void auditRequest(String appName,ServletRequest request) {
        logger.info(appName+" received request from " + request.getRemoteAddr());
    }
}

二:web.xml增加如下配置:

<!-- spring security Filter -->
    <filter>
        <filter-name>auditFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
        <!-- invoke lifecycle methods -->
        <param-name>targetFilterLifecycle</param-name>
        <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>appName</param-name>
            <param-value>mytemplateweb</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>auditFilter</filter-name>
        <url-pattern>*.htm</url-pattern>
    </filter-mapping>

这里需要注意的是:filter-name的名字就是写的filter的类名
三:spring.xml增加:

<bean id="auditHandler" class="com.template.filter.AuditHandler"/>

    <bean id="auditFilter" class="com.template.filter.AuditFilter">  
        <constructor-arg ref="auditHandler"/>
    </bean> 

注意:本来想通过注解的方法注入的,没起作用,就改成这种方式了,用这种方式注入,声明的bean要么没有构造方法(有参数的和无参的),要么显示声明无参的构造方法,不然报错

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:21007次
    • 积分:283
    • 等级:
    • 排名:千里之外
    • 原创:10篇
    • 转载:3篇
    • 译文:0篇
    • 评论:1条
    文章存档
    最新评论