使用Filter登录控制
使用Filter登录控制
我对Filter的理解:
Fileter就像过滤器,对浏览器发出的请求过滤。在执行浏览器发出的请求之后,用户察觉不到的,服务器端执行了一串过滤器,然后再处理用户的请求。执行过滤器的顺序由过滤器在web.xml中的注册顺序决定。
过滤器的使用
凡是你想对特定请求加以处理的话,就可以使用到过滤器。比如统一请求和响应编码、检查用户是否登录。
如何使用Filter
这里介绍的是在Servlet+JSP的项目中使用Filter进行登录控制
首先,新建一个Filter;
点击查看代码
@WebFilter("/LoginFilter")
public class LoginFilter implements Filter {
private String logon_page;
private String register_page;
/**
* Default constructor.
*/
public LoginFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
// place your code here
// pass the request along the filter chain
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
HttpSession session = req.getSession();
String request_uri = req.getRequestURI();
String ctxPath = req.getContextPath();
String uri = request_uri.substring(ctxPath.length());
System.out.println("uri:" + uri);
if (uri.equals(logon_page) || uri.equals(register_page)) {
chain.doFilter(request, response);
return;
}else {
if (null != session.getAttribute("name") && "" != session.getAttribute("name")) {
chain.doFilter(request, response);
return;
}else {
resp.sendRedirect(req.getContextPath()+"/Login.jsp");
}
}
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
logon_page = "/Login.jsp";
System.out.println(logon_page);
if (null == logon_page) {
throw new ServletException("û���ҵ���¼ҳ�����ҳ");
}
}
}
其次,在web.xml中注册这个Filter
点击查看代码
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>Filter.LoginFilter</filter-class>
<init-param>
<param-name>LOGON_URI</param-name>
<param-value>./Login.jsp</param-value>
</init-param>
</filter>
最后,在web.xml中设置mapping映射关系,这将决定哪些文件将被这个Filter过滤
点击查看代码
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>