过滤特定网址的映射

时间:2014-09-22 06:03:27

标签: java xml jsp filter servlet-filters

ExpiryFilter.java

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

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.HttpServletResponse;

public class ExpiryFilter implements Filter {

    // add a five years expiry
    private Integer years = 1;

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        if (years > -1) {
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(Calendar.YEAR, years);

            // HTTP header date format: Thu, 01 Dec 1994 16:00:00 GMT
            String o = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss zzz")
                    .format(c.getTime());
            ((HttpServletResponse) response).setHeader("Expires", o);
        }

        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {      
    }
}

我正在创建一个Web应用程序,因为我想给出有效期。所以我使用过滤器进行映射。

的web.xml

<filter>
    <description>Set cache expiry for static content</description>
    <filter-name>ExpiryFilter</filter-name>
    <filter-class>ExpiryFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>ExpiryFilter</filter-name>
    <url-pattern>/ExpiryDate/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

这是我的本地主机链接http://localhost:8080/ExpiryDate/test.jsp.我需要在一年后过滤。在一年或特定时间段之后,特定链接无法运行。所以请帮助我找出解决方案。

谢谢。

1 个答案:

答案 0 :(得分:3)

因为它是一个页面,所以只需在JSP页面的开头检查两个日期(您指定的开始日期和请求的日期)之间的差异。 是这样的比索做代码

if (difference is one year ){
<body>
link is expired
</body>
}else{
<body>
//what ever data you show
</body>
}