JAVA工具类集锦4--登录过滤器

4、登录过滤器

import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.FilterChain;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;

/**
*
* <p>Title: 登陆过滤操作</p>
*/
public class LoginFilter
implements Filter {
private static String loginURL;
private static ArrayList needRight;
private static ArrayList noneedRight;
private FilterConfig filterConfig;
public LoginFilter() {
}

public void init(FilterConfig filtercfg) throws javax.servlet.
ServletException {
loginURL = filtercfg.getInitParameter("loginURL");
this.filterConfig = filterConfig;
needRight = new ArrayList();
needRight.add("forum_add");
needRight.add("forum_delete");
needRight.add("forum_update");
needRight.add("topic_delete");
needRight.add("topic_update");

noneedRight = new ArrayList();
noneedRight.add("login"); //用户登录
noneedRight.add("user_add"); //用户注册
noneedRight.add("include/check.js"); //JAVASCRIPT脚本
}

private boolean isRightNeed(String queryString) {
if (queryString.indexOf("method=") > -1) {
for (int i = 0; i < needRight.size(); i++) {
String method = (String) needRight.get(i);
if (queryString.indexOf(method) > -1) {
return true;
}
}
}
return false;
}

private boolean isLoginNeed(String queryString) {
for (int i = 0; i < noneedRight.size(); i++) {
String method = (String) noneedRight.get(i);
if (queryString.indexOf(method) > -1) {
return false;
}
}
return true;
}

private boolean hasRight(User loginUser, String queryString) {
boolean flag = true;
if (isRightNeed(queryString)) {
if (loginUser.getDegree() == User.SUPERADMIN) {
flag = true;
}
else {
flag = false;
}
}
return flag;
}

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterchain) throws java.io.
IOException,
javax.servlet.ServletException {
HttpServletRequest httprequest = (HttpServletRequest) request;
HttpServletResponse httpresponse = (HttpServletResponse) response;
User loginUser = (User) httprequest.getSession().getAttribute(
"user");
String tempURI = (httprequest.getRequestURI()).toLowerCase();
String tempURL = (httprequest.getRequestURL()).toString().
toLowerCase();
String queryString = httprequest.getQueryString();
if (queryString == null) {
queryString = tempURI;
}
System.out.println("queryString:" + queryString);
if (loginUser == null) {
if (!isLoginNeed(queryString)) {
filterchain.doFilter(request, response);
return;
}
else {
httpresponse.sendRedirect("login.jsp");
return;
}
}
if (hasRight(loginUser, queryString)) {
filterchain.doFilter(request, response);
return;
} else {
httpresponse.sendRedirect("success.jsp?flag=false");
return;
}
}

public void destroy() {
loginURL = null;
filterConfig = null;
}

}

阅读更多
换一批

没有更多推荐了,返回首页