版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
一 定义认证Filter
package lee;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.*;
@WebFilter(filterName="authority"
, urlPatterns={"/*"}
, initParams={
@WebInitParam(name="encoding", value="GBK"),
@WebInitParam(name="loginPage", value="/login.jsp"),
@WebInitParam(name="proLogin", value="/proLogin.jsp")})
public class AuthorityFilter implements Filter
{
// FilterConfig可用于访问Filter的配置信息
private FilterConfig config;
// 实现初始化方法
public void init(FilterConfig config)
{
this.config = config;
}
// 实现销毁方法
public void destroy()
{
this.config = null;
}
// 执行过滤的核心方法
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException,ServletException
{
// 获取该Filter的配置参数
String encoding = config.getInitParameter("encoding");
String loginPage = config.getInitParameter("loginPage");
String proLogin = config.getInitParameter("proLogin");
// 设置request编码用的字符集
request.setCharacterEncoding(encoding); // ①
HttpServletRequest requ = (HttpServletRequest)request;
HttpSession session = requ.getSession(true);
// 获取客户请求的页面
String requestPath = requ.getServletPath();
// 如果session范围的user为null,即表明没有登录
// 且用户请求的既不是登录页面,也不是处理登录的页面
if( session.getAttribute("user") == null
&& !requestPath.endsWith(loginPage)
&& !requestPath.endsWith(proLogin))
{
// forward到登录页面
request.setAttribute("tip" , "您还没有登录");
request.getRequestDispatcher(loginPage)
.forward(request, response);
}
// "放行"请求
else
{
chain.doFilter(request, response);
}
}
}
二 视图
1 login.jsp
<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>登录页面</title>
<meta name="website" content="http://www.crazyit.org" />
</head>
<body>
<h2>登录页面</h2>
<%
if(request.getAttribute("tip") != null)
{
out.println("<font color='red'>"
+ request.getAttribute("tip")
+ "</font>");
}
%>
<form method="post" action="proLogin.jsp">
用户名:<input type="text" name="name"/><br/>
<input type="submit" value="登录"/>
</form>
</body>
</html>
2 proLogin.jsp
<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> 登录页面 </title>
<meta name="website" content="http://www.crazyit.org" />
</head>
<body>
<h2>登录页面</h2>
<%
session.setAttribute("user"
, request.getParameter("name"));
%>
登录成功,可以访问该应用的其他页面
</body>
</html>
三 测试