1.创建动态web项目
2.创建filters的文件
3.创建主页面
4.配置xml项目
总结构
主页面代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>过滤器</title>
</head>
<body>
<form action="result.jsp">
用户名:<input type="text" name="user">
密码:<input type="text" name="pw">
<input type="submit" value="提交">
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 过滤器要加在接受请求页面的或服务器上 -->
<%
String s=request.getParameter("user");
out.print(s);
%>
</body>
</html>
package filter_test;
//filter是一个特殊的servlet类,有自己的生命周期,包括初始化,处理请求和相应,销毁等阶段
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.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
/**
* Servlet Filter implementation class Filter01
*/
@WebFilter("/Filter01")
public class Filter01 extends HttpFilter implements Filter {
/**
* @see HttpFilter#HttpFilter()
*/
public Filter01() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
System.out.println("销毁...");
// 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
System.out.println("过滤...");
// pass the request along the filter chain
chain.doFilter(request, response);
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
System.out.println("初始化...");
// TODO Auto-generated method stub
}
}