public class LoginFilter implements Filter {
private ICacheClient memcache;
public void setMemcache(ICacheClient memcache) {
this.memcache = memcache;
}
private FilterConfig filterConfig;
@Override
public void destroy() {
this.filterConfig=null;
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException,
ServletException {
//获取session
HttpServletRequest request=(HttpServletRequest)req;
HttpServletResponse response=(HttpServletResponse)resp;
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
HttpSession session=request.getSession();
// BeanDefinitionRegistry reg = new DefaultListableBeanFactory();
// PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(reg);
// reader.loadBeanDefinitions(new ClassPathResource("/PayWap/conf/paywap/properties/memcache.properties"));
// BeanFactory factory = (BeanFactory)reg;
// String[] locations ={"conf/spring/applicationContext-Memcache.xml"};
// ApplicationContext context = new ClassPathXmlApplicationContext("conf/spring/applicationContext-Memcache.xml");
// ICacheClient memcache= (CacheClientImpl)context.getBean("memcache");
/* Resource res = new ClassPathResource("conf/spring/applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(res);
PropertyPlaceholderConfigurer cfg = (PropertyPlaceholderConfigurer)factory.getBean("PropertyConfigurer");
cfg.postProcessBeanFactory((XmlBeanFactory) factory);
ICacheClient memcachea= (CacheClientImpl) factory.getBean("memcache");*/
//获取session中是否保存了用户信息
Object obj=session.getAttribute(WebConstants.USER_INFO);
//获取访问地址
String uri=request.getRequestURI();
String tid = request.getParameter("tid");
if(uri==null)
uri="";
//uri=uri.toLowerCase();
//判断sesion中的用户信息为空
if(obj==null && checkUri(uri)){
//如果cookie有值则取cookie值
TokenBean tokenBean = (TokenBean) memcache.get(tid);
if(tokenBean!=null){
//登录过,将用户信息保存到session中
AllUsers user=new AllUsers();
user.setUserid(tokenBean.getUserId());
user.setPhone(tokenBean.getPhone());
//user.setUserpwd(userInfo[2]);
session.setAttribute(WebConstants.USER_INFO, user);
}
else{
//跳转到登录页面
response.sendRedirect(request.getContextPath()+"/v/login");
return;
}
}
//跳转到指定的url地址
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig conf) throws ServletException {
this.filterConfig=conf;
}
/**
* 需要放行的uri包含的字符串数组
*/
private String[] filterStr={"/v/login","/v/foreign","/v/recharge/mobilePurseChargeCallback","/v/recharge/bankChargeCallback","v/shortcutpay/callback"};
/**
*
* 说明:验证是否为不允许放行的uri
* @param uriStr uri
* @return 没有找到允许放行的返回true 否则返回false
*
*/
private boolean checkUri(String uriStr){
for(int i=0;i<filterStr.length;i++){
if(uriStr.indexOf(filterStr[i])>=0)
return false;
}
return true;
}