今天为练习Filter的用法编写了一个小程序.
当用户通过article的超链接读取文章的时候,会通过Filter进行检测有没有登录.只有登录的读者才能跳到文章页面,否则跳到登录页面.
文章就用简单的article1 和article2 的html页面来表示
这是Filter的代package a2;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import com.sun.jersey.spi.dispatch.RequestDispatcher;
public class LogonFilter implements Filter {
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
//这里将ServletRequest转化为子类处理类HttpServletRequest
HttpServletRequest req=(HttpServletRequest) request;
//获得Session会话
HttpSession session=req.getSession();
//判断session里面是否有用户名属性
if(session.getAttribute("logonUser")==null)
{ //获得URL去掉前面部分,然后转发为相对路径
String requestURI=req.getRequestURI();
String contextPath=req.getContextPath();
String forwardURI=requestURI.substring(contextPath.length());
session.setAttribute("viewPage", forwardURI);
javax.servlet.RequestDispatcher rd=req.getRequestDispatcher("/logon.jsp");
rd.forward(req, response);
}
else{
//如果没有用户名也要放行
chain.doFilter(request, response);
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
下面是article的html页面,当访问它的超链接的时候就会通过Filter,Filter在web.xml中设置.
<!DOCTYPE html>下面是web.xml的配置
<html>
<head>
<title>articles.html</title>
<meta name="keywords" content="keyword1,keyword2,keyword3">
<meta name="description" content="this is my page">
<meta name="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<body>
<a href="article1.html" target="_blank">阅读第1篇文章</a>
<a href="article2.html" target="_blank">阅读第2篇文章</a>
</body>
</html>
<filter>
<filter-name>LogonFilter</filter-name>
<filter-class>a2.LogonFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LogonFilter</filter-name>
<url-pattern>/articles.html</url-pattern>
</filter-mapping>