filter
web.xml
<filter>
<filter-name>encoding</filter-name>
<filter-class>com.filter.EncodingFilter</filter-class>
<init-param>
<param-name>charset</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
class:
package com.filter;
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.HttpSession;
public class LoginFilter implements Filter {
public void destroy() {
// TODO Auto-generated method stub
}
//执行过滤
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//向下转型(因为session本身是属于http协议范畴)
HttpServletRequest req = (HttpServletRequest) request;
//取得session
HttpSession ses = req.getSession();
//判断是否登录
if (ses.getAttribute("userid") != null) {
chain.doFilter(request, response);//传递请求,继续判断其他验证
} else {
//跳转到登陆页
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}