《Java Web开发技术应用——过滤器》
过滤器是一个程序,它先于与之相关的servlet或JSP页面运行在服务器上。过滤器可附加到一个或多个servlet或JSP页面上,并且可以检查进入这些资源的请求信息。在这之后,过滤器可以作如下的选择:
①以常规的方式调用资源(即,调用servlet或JSP页面)。
②利用修改过的请求信息调用资源。
③调用资源,但在发送响应到客户机前对其进行修改。
④阻止该资源调用,代之以转到其他的资源,返回一个特定的状态代码或生成替换输出。
用户请求——>过滤器——>WEB资源——>过滤器——>用户
过滤器的生命周期
1.实例化 web.xml 在web容器启动时依据web.xml实例化
2.初始化 init()
3.过滤 doFilter()
4.销毁 destroy()
配置:
可以通过Design界面快速配置
过滤器需要实现接口javax.servlet.Filter,开始以为是类……找了好久……
需要实现三个方法
public void destroy() {}
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {}
public void init(FilterConfig arg0) throws ServletException {}
在doFilter中实现逻辑
如果多个过滤器对应一个路径
那么按照在web.xml的中定义的顺序执行过滤器
请求——>过滤器1——>过滤器2——>Servlet——>过滤器2——>过滤器1——>用户
过滤器的分类:(默认是request
ASYNC:Servlet中异步执行过滤器和业务逻辑内容。
ERROR:处理error-page
FORWARD:通过request.getRequestDispatcher("url").forward(request, response);或者<jsp:forward page="..."></jsp:forward>
INCLUDE:通过request.getRequestDispatcher("url").include(request, response);或者<jsp:include page="..."></jsp:include>
REQUEST:通过链接直接访问,或者通过response.sendRedirect("url");
在web.xml里面配置error-page
<error-page> <error-code>404</error-code> <location>/error.jsp</location> </error-page>
在类上面通过注解配置过滤器
@WebFilter(filterName="...", value={"/....jsp"}, dispatcherTypes={DispatcherType.REQUEST, DispatcherType.ASYNC})
public class FilterName implements Filter {...}
案例:登录校验,如果没有登录,不能直接通过url访问登录后才能访问的页面
(突然发现右键有Servlet的选项,内心是崩溃的……窝每次都是新建java类……
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'login.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <% request.setCharacterEncoding("utf-8"); %> <body> <form action="<%=request.getContextPath() %>/servlet/LoginServlet" method="post"> 用户名:<input type="text" name="username"> 密码:<input type="password" name="password"> <input type="submit" value="提交"> </form> </body> </html>