通过Filter实现用户登录后才允许访问配送信息填写页面和后续页面

首先建立一个filter

 代码如下

 

  

package cn.itcast.web.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;

import org.apache.commons.codec.binary.Base64;

import cn.itcast.bean.user.Buyer;
import cn.itcast.utils.WebUtil;

public class BuyerLogonValidateFilter implements Filter {

 public void destroy() {
 }

 public void doFilter(ServletRequest req, ServletResponse res,
   FilterChain chain) throws IOException, ServletException {
  HttpServletRequest request = (HttpServletRequest)req;
  Buyer buyer = WebUtil.getBuyer(request);
  if(buyer == null){
   String url = WebUtil.getRequestURIWithParam(request);//得到当前请求路径
   String directUrl = new String(Base64.encodeBase64(url.getBytes()));
   HttpServletResponse response = (HttpServletResponse)res;
   response.sendRedirect("/user/logon.do?directUrl="+ directUrl);
  }else{
   chain.doFilter(req, res);
  }
 }

 public void init(FilterConfig arg0) throws ServletException {
 }

}

 

 

之后 在web.xml中进行filter的配置

 

 <filter>
        <filter-name>BuyerLogonValidateFilter</filter-name>
        <filter-class>cn.itcast.web.filter.BuyerLogonValidateFilter</filter-class> 
    </filter>
    <filter-mapping>
        <filter-name>BuyerLogonValidateFilter</filter-name>
        <url-pattern>/customer/*</url-pattern>
    </filter-mapping>

 

ok 完成

posted on 2014-02-14 09:51  yaoboyyao  阅读(135)  评论(0编辑  收藏  举报

导航