loginFilter.java
/**
* loginFilter.java
*/
package myFilter;
import java.io.IOException;
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;
/**
* 检查 session 中的 username 内容是否为空,为空则没有登录,转发到登录页面, 如果不为空,则分发请求。
* @author wind
*
*/
public class loginFilter implements Filter {
private String onErrorUrl;
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
HttpSession session = req.getSession();
String username = (String) session.getAttribute("username");
boolean flag = true;
if (username == null) {
flag = false;
} else {
}
if (flag) {
/*
* Causes the next filter in the chain to be invoked, or if the
* calling filter is the last filter in the chain, causes the
* resource at the end of the chain to be invoked.
*/
chain.doFilter(request, response);
} else {
/*
* Forwards a request from a servlet to JSP file on the server.
*/
req.getRequestDispatcher(onErrorUrl).forward(req, res);
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
/*
* Returns a String containing the value of the named initialization
* parameter, or null if the parameter does not exist.
*/
onErrorUrl = filterConfig.getInitParameter("onError");
if (onErrorUrl == null || "".equals(onErrorUrl)) {
onErrorUrl = "/index.jsp";
}
}
}
web.xml添加以下代码:
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>myFilter.loginFilter</filter-class>
<init-param>
<param-name>onError</param-name>
<param-value>/index.jsp</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/havesession/*</url-pattern>
</filter-mapping>
特别注意:<url-pattern>/havesession/*</url-pattern>这里意思是过滤/havasession/路径中的所有HTTP请求。