过滤器实际上就是对web资源进行拦截,做一些处理后再交给下一个过滤器或servlet处理
通常都是用来拦截request进行处理的,也可以对返回的response进行拦截处理
应用场景:自动登录、统一设置编码格式、访问权限控制、敏感字符过滤等
过滤器
样例
模拟在登录页面(login.html)进行登录,使用过滤器(FilterDemo.java)进行拦截,如果session中存在登录用户信息,则直接跳转主页(index.html),否则转发到登录页面(login.html)
login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="loginServlet" method="post">
用户名:<input name="username"><br>
密码:<input name="password" type="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
我是主页
</body>
</html>
LoginFilter.java
public class FilterDemo implements Filter {
/*初始化方法*/
public void init(FilterConfig fConfig) throws ServletException {
}
/*过滤方法*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("开始过滤了");
HttpServletRequest hsRequest=(HttpServletRequest) request;
HttpSession session = hsRequest.getSession();
String username=(String) session.getAttribute("username");
if("zhangsan".equals(username)) {
chain.doFilter(request, response);//放行
}else {
request.getRequestDispatcher("login.html").forward(hsRequest, response);
}
}
/*销毁*/
public void destroy() {
}
}
LoginServlet.java
public class LoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*用户名 zhangsan 密码123456*/
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username+password);
HttpSession session = request.getSession();
if("zhangsan".equals(username)&&"123456".equals(password)) {
session.setAttribute("username", username);
System.out.println("用户名密码正确!");
/*跳转页面*/
response.sendRedirect("index.html");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
web.xml
<web-app>
...
<servlet>
<description></description>
<display-name>loginServlet</display-name>
<servlet-name>loginServlet</servlet-name>
<servlet-class>xxx.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
...
...
<filter>
<filter-name>filterDemo</filter-name>
<filter-class>xxx.FilterDemo</filter-class>
</filter>
<filter-mapping>
<filter-name>filterDemo</filter-name>
<url-pattern>/index.html</url-pattern>
</filter-mapping>
...
</web-app>