1. Filter自定义:
import j_mongoDB.JMongoDB;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
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.db.po.User;
public class LogFilter implements Filter {
private Set<String> nofilterSet;
// private static final String LOGON_URI = "LOGON_URI";
private String logon_page;
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
res.setContentType("text/html");
res.setCharacterEncoding("utf-8");
PrintWriter out = res.getWriter();
/**
* 获取当前url
*/
String cUrl = req.getRequestURI();
/**
* 获取当前session
*/
HttpSession session = req.getSession();
/**
* 从session中取到当前用户user
*/
User user = (User) session.getAttribute("user");
List<String> priilegeList = new ArrayList<String>();
System.out.println("当前连接-URL:" + cUrl);
if (nofilterSet.contains(cUrl)) {
chain.doFilter(request, response);
return;
} else {
if (user != null && !"".equals(user)) {
try {
System.out.println("当前用户名:" + user.getUsername()
+ ";当前用户ID:" + user.getId());
priilegeList = JMongoDB.getUserPrivilegeList(user.getId(),
true);
System.out.println("当前用户权限:" + priilegeList);
if (priilegeList.contains(cUrl)) {
chain.doFilter(request, response);
} else {
out.println("没有权限访问该链接!!!");
return;
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
res.sendRedirect(logon_page);
}
}
}
@SuppressWarnings("unchecked")
public void init(FilterConfig filterConfig) throws ServletException {
/**
* 通用连接
*/
nofilterSet = (Set<String>) filterConfig.getServletContext()
.getAttribute("nofilter");
if (nofilterSet == null) {
nofilterSet = new HashSet<String>();
nofilterSet.add("/z_WebTest/");
nofilterSet.add("/z_WebTest/login.do");
filterConfig.getServletContext().setAttribute("nofilter",
nofilterSet);
}
logon_page = filterConfig.getInitParameter("LOGON_URI");
}
}
2. Web.xml配置自定义Filter
<filter>
<filter-name>logFilter</filter-name>
<filter-class>com.web.filter.LogFilter</filter-class>
<init-param> -->
<param-name>LOGON_URI</param-name>
<param-value>/z_WebTest/</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>logFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>