几乎所有网页在访问前,都需要通过用户认证,所以用户认证可以做成一个过滤器。访问一个Servlet或JSP时,会自动的调用过滤器,过滤器里判断是否已经用户认证过了,如果已经认证通过,则显示页面,如果没有通过,则跳转至用户登录页面。
下面是用户登录过滤器的代码:
(根据网上搜索到的一个例子,修改而成)------ LoginFilter.java ------
package common.filter;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
/**
* 检测用户是否登录,如果没有登录,则重定向到登录页面
*/
public class LoginFilter implements Filter
{
private String loginURL = null;
private List notCheckURLList = null;
private String loginSessionKey = null;
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
{
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String servletPath = request.getServletPath();
// Pass if not need to check login
if (loginSessionKey == null) {
filterChain.doFilter(request, response);
return;
}
// Pass if already logged in
HttpSession session = request.getSession();
if (session.getAttribute(loginSessionKey) != null) {
filterChain.doFilter(servletRequest, servletResponse);
return;
}
// Pass if it is configured not checking
if (checkRequestURIIntNotFilterList(request)) {
filterChain.doFilter(servletRequest, servletResponse);
return;
}
// Redirect to login page
response.sendRedirect(request.getContextPath() + loginURL);
return;
}
private boolean checkRequestURIIntNotFilterList(HttpServletRequest request) {
String uri = request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());
return notCheckURLList.contains(uri);
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
notCheckURLList = new ArrayList();
loginURL = filterConfig.getServletContext().getInitParameter("loginURL");
loginSessionKey = filterConfig.getServletContext().getInitParameter("loginSessionKey");
String notCheckURLListStr = filterConfig.getServletContext().getInitParameter("notCheckURLList");
if (notCheckURLListStr != null) {
StringTokenizer st = new StringTokenizer(notCheckURLListStr, ";");
while (st.hasMoreTokens()) {
notCheckURLList.add(st.nextToken());
}
}
}
}
<context-param>
<param-name>loginURL</param-name>
<param-value>/login.jsp</param-value>
</context-param>
<context-param>
<param-name>loginSessionKey</param-name>
<param-value>userName</param-value>
</context-param>
<context-param>
<param-name>notCheckURLList</param-name>
<param-value>/login.jsp;/login;/jsp/NewFile.jsp</param-value>
</context-param>
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>common.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>