package com.filters;
import java.io.IOException;
import java.util.List;
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 javax.servlet.http.HttpSession;
import com.pojos.Menus;
import com.pojos.Users;
public class PowerFilter implements Filter {
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
//强制转化为子类
HttpServletRequest request=(HttpServletRequest) arg0;
HttpServletResponse response=(HttpServletResponse) arg1;
//小编一下码
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("html/text;charset=utf-8");
//取地址上输入路径 /user.do 工程名和?之间
String path=request.getServletPath();
//取?后面的参数 eg:id=2
String param=request.getQueryString();
//把请求路径拼起来
if(param!=null&¶m.length()>0)
{
path=path+"?"+param;
}
//System.out.println("path:"+path);
// 取session判断是否已经登录
HttpSession session=request.getSession();
Users user=(Users) session.getAttribute("user");
//判断是否是admin登录,如果是都可以操作
if(user!=null&&user.getUsername()=="admin")
{
arg2.doFilter(request, response);
return ;
}
// 无条件可以过的是登陆有关(登陆界面和登陆action)
if(path.equals("/index.jsp")||path.equals("/user.do?p=login")||path.equals("/"))
{
//通过
arg2.doFilter(request, response);
return ;
}
//没有登录等情况
if(user==null)
{
//getContextPath()得工程名
response.getWriter().print("<script>alert('请先登录');location='"+request.getContextPath()+"/index.jsp'</script>");
arg2.doFilter(request, response);
return ;
}
// 已经登录 主界面只要登陆就可以用
if(path.startsWith("/background/"))
{
arg2.doFilter(request, response);
return ;
}
// 其它界页还要看权限
List<Menus> menus=(List) session.getAttribute("menus");
for (Menus m : menus) {
//System.out.println("权限url:"+m.getUrl());
String url=m.getUrl();
if(url!=null&& path.startsWith("/"+url));
{
arg2.doFilter(request, response);
return ;
}
}
response.getWriter().print("<script>alert('您没有足够的权限!')</script>");
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}