然后创建 JSP页面,这里用到三个JSP网页,分别为login.jsp、login_error.jsp和index.jsp。
<%@ page contentType="text/html; charset=GBK" %>
<%@ page errorPage="login_error.jsp" %>
<html>
<head>
<title>
Filter的运用
</title>
</head>
<body bgcolor="#c0c0c0">
<h1>
<center>
<p/>
<h1>欢迎使用Filter过滤器!</h1>
<form action="index.jsp" method="post">
<font size="4">
<b>用户名:</b> <input type="text" name="username" value="">
<br><br>
<b>密 码:</b> <input type="text" name="password" value="">
<br><br>
<input type="submit" name="login" value="登录">  
<input type="reset" value="重写">
</font>
</form>
</center>
</h1>
<form method="post">
<br><br>
<input type="submit" name="Submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>
2.login_error.jsp:
<%@ page isErrorPage="true" %>
<html>
<title>Filter的运用</title>
<body bgcolor="#ffffff">
<center>
<h1>Filter错误提示:</h1>
</center>
<%
String err = request.getParameter("errmsg");
String errmsg = new String(err.getBytes("ISO-8859-1"),"GBK");
%>
<p>对不起,您的操作有误。请参考下列提示:</p>
您输入的 <%=errmsg%>错误!
</body>
</html>
3.index.jsp:
<html>
<head>
<title>
Filter的运用
</title>
</head>
<body bgcolor="#c0c0c0">
<center>
<p/>
<h1>祝贺你顺利通过Filter过滤!</h1>
</center>
</body>
</html>
二、创建 Filter servlet
package filtertest;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
private FilterConfig filterConfig;
//初始化用户名和密码
public static final String UserName = "aaa";
public static final String PassWord = "aaa";
//Handle the passed-in FilterConfig
public void init(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
}
//Process the request/response pair
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) {
try {
filterChain.doFilter(request, response);
String username = ((HttpServletRequest)request).getParameter("username");
String password = ((HttpServletRequest)request).getParameter("password");
System.out.println("用户 \"" + username + "\" 正在试图登录,他的密码是 \"" + password + "\"。");
if (username == null && password == null)
{
System.out.println("页面值传递错误,或者非法进入。");
}
else
{
if (!UserName.equals(username))
{
((HttpServletResponse) response).sendRedirect("login_error.jsp?errmsg=username");
return;
}
else
{
if (!PassWord.equals(password))
{
( (HttpServletResponse) response).sendRedirect("login_error.jsp?errmsg=password");
return;
}
}
}
}
catch(ServletException sx) {
filterConfig.getServletContext().log(sx.getMessage());
}
catch(IOException iox) {
filterConfig.getServletContext().log(iox.getMessage());
}
}
//Clean up resources
public void destroy() {
}
}
6.部署应用程序,启动运行。