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

  1. <error-page>
  2. <error-code>404</error-code>
  3. <location>/error.jsp</location>
  4. </error-page>

在类上面通过注解配置过滤器

@WebFilter(filterName="...", value={"/....jsp"}, dispatcherTypes={DispatcherType.REQUEST, DispatcherType.ASYNC})

public class FilterName implements Filter {...}

案例:登录校验,如果没有登录,不能直接通过url访问登录后才能访问的页面

(突然发现右键有Servlet的选项,内心是崩溃的……窝每次都是新建java类……

  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
  2. <%
  3. String path = request.getContextPath();
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  5. %>
  6.  
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  8. <html>
  9. <head>
  10. <base href="<%=basePath%>">
  11.  
  12. <title>My JSP 'login.jsp' starting page</title>
  13.  
  14. <meta http-equiv="pragma" content="no-cache">
  15. <meta http-equiv="cache-control" content="no-cache">
  16. <meta http-equiv="expires" content="0">
  17. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  18. <meta http-equiv="description" content="This is my page">
  19. <!--
  20. <link rel="stylesheet" type="text/css" href="styles.css">
  21. -->
  22.  
  23. </head>
  24.  
  25. <%
  26. request.setCharacterEncoding("utf-8");
  27. %>
  28.  
  29. <body>
  30. <form action="<%=request.getContextPath() %>/servlet/LoginServlet" method="post">
  31. 用户名:<input type="text" name="username">
  32. 密码:<input type="password" name="password">
  33. <input type="submit" value="提交">
  34. </form>
  35.  
  36. </body>
  37. </html>

login.jsp

  1. package com.imooc.servlet;
  2.  
  3. import java.io.IOException;
  4. import java.io.PrintWriter;
  5.  
  6. import javax.servlet.ServletConfig;
  7. import javax.servlet.ServletException;
  8. import javax.servlet.http.HttpServlet;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import javax.servlet.http.HttpSession;
  12.  
  13. public class LoginServlet extends HttpServlet {
  14.  
  15. /**
  16. * The doPost method of the servlet. <br>
  17. *
  18. * This method is called when a form has its tag value method equals to post.
  19. *
  20. * @param request the request send by the client to the server
  21. * @param response the response send by the server to the client
  22. * @throws ServletException if an error occurred
  23. * @throws IOException if an error occurred
  24. */
  25. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  26.  
  27. String username = request.getParameter("username");
  28. String password = request.getParameter("password");
  29.  
  30. System.out.println(username);
  31.  
  32. if("admin".equals(username) && "admin".equals(password)){
  33. //校验通过
  34. HttpSession session = request.getSession();
  35. session.setAttribute("username", username);
  36. response.sendRedirect(request.getContextPath()+"/success.jsp");
  37. return ;
  38. } else{
  39. //校验失败
  40. response.sendRedirect(request.getContextPath()+"/fail.jsp");
  41. return ;
  42. }
  43. }
  44.  
  45. }

LoginServlet.java

  1. package com.imooc.filter;
  2.  
  3. import java.io.IOException;
  4.  
  5. import javax.servlet.Filter;
  6. import javax.servlet.FilterChain;
  7. import javax.servlet.FilterConfig;
  8. import javax.servlet.ServletException;
  9. import javax.servlet.ServletRequest;
  10. import javax.servlet.ServletResponse;
  11. import javax.servlet.http.HttpServletRequest;
  12. import javax.servlet.http.HttpServletResponse;
  13. import javax.servlet.http.HttpSession;
  14.  
  15. public class LoginFilter implements Filter {
  16.  
  17. private FilterConfig config;
  18.  
  19. @Override
  20. public void destroy() {
  21. // TODO Auto-generated method stub
  22.  
  23. }
  24.  
  25. @Override
  26. public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
  27. throws IOException, ServletException {
  28. HttpServletRequest request = (HttpServletRequest) arg0;
  29. HttpServletResponse response = (HttpServletResponse) arg1;
  30.  
  31. String charset = config.getInitParameter("charset");
  32. if (charset == null) {
  33. charset = "utf-8";
  34. }
  35.  
  36. request.setCharacterEncoding("utf-8");
  37.  
  38. String noLoginPaths = config.getInitParameter("noLoginPaths");
  39. if (noLoginPaths != null) {
  40. String[] strArray = noLoginPaths.split(";");
  41. for (String s: strArray) {
  42. if (s != null && !s.equals("") && request.getRequestURL().indexOf(s) != -1) {
  43. arg2.doFilter(arg0, arg1);
  44. return;
  45. }
  46. }
  47. }
  48.  
  49. HttpSession session = request.getSession();
  50. if (session.getAttribute("username") != null) {
  51. arg2.doFilter(arg0, arg1);
  52. } else {
  53. response.sendRedirect("login.jsp");
  54. }
  55. }
  56.  
  57. @Override
  58. public void init(FilterConfig arg0) throws ServletException {
  59. // TODO Auto-gegnerated method stub
  60. config = arg0;
  61. }
  62.  
  63. }

LoginFilter.java

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  3. <display-name>LoginFilter</display-name>
  4. <servlet>
  5. <description>This is the description of my J2EE component</description>
  6. <display-name>This is the display name of my J2EE component</display-name>
  7. <servlet-name>LoginServlet</servlet-name>
  8. <servlet-class>com.imooc.servlet.LoginServlet</servlet-class>
  9. </servlet>
  10.  
  11. <servlet-mapping>
  12. <servlet-name>LoginServlet</servlet-name>
  13. <url-pattern>/servlet/LoginServlet</url-pattern>
  14. </servlet-mapping>
  15. <welcome-file-list>
  16. <welcome-file>index.html</welcome-file>
  17. <welcome-file>index.htm</welcome-file>
  18. <welcome-file>index.jsp</welcome-file>
  19. <welcome-file>default.html</welcome-file>
  20. <welcome-file>default.htm</welcome-file>
  21. <welcome-file>default.jsp</welcome-file>
  22. </welcome-file-list>
  23. <filter>
  24. <filter-name>LoginFilter</filter-name>
  25. <filter-class>com.imooc.filter.LoginFilter</filter-class>
  26. <init-param>
  27. <param-name>noLoginPaths</param-name>
  28. <param-value>login.jsp;fail.jsp;LoginServlet</param-value>
  29. </init-param>
  30. <init-param>
  31. <param-name>charaset</param-name>
  32. <param-value>GBK</param-value>
  33. </init-param>
  34. </filter>
  35. <filter-mapping>
  36. <filter-name>LoginFilter</filter-name>
  37. <url-pattern>/*</url-pattern>
  38. </filter-mapping>
  39. </web-app>

web.xml

Java Web——过滤器的更多相关文章

  1. java web 过滤器跟拦截器的区别和使用

    注:文章整理自知乎大牛以及百度网友(电脑网络分类达人 吕明),特此感谢! 一.过滤器 1.什么是过滤器? 过滤器是一个程序,它先于与之相关的servlet或JSP页面运行在服务器上.过滤器可附加到一个 ...

  2. java web过滤器实际应用(解决中文乱码 html标签转义功能 敏感字符过滤功能)

    转载地址:http://www.cnblogs.com/xdp-gacl/p/3952405.html 在filter中可以得到代表用户请求和响应的request.response对象,因此在编程中可 ...

  3. java web过滤器防止未登录进入界面

    import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import ja ...

  4. JAVA WEB 过滤器(Filter)中向容器 Spring 注入 bean

    如果直接使用 @Autoware 获取 bean 会直接使该 bean 为 null,这是因为这种配置过滤器的方法无法在过滤器中使用 Spring bean,因为 Filter 比 bean 先加载, ...

  5. java Web 过滤器Filter详解

    简介 Filter也称之为过滤器,Web开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp, Servlet, 静态图片文件或静态 html 文件等进行拦截,从而实现一些特殊 ...

  6. Java Web 中 过滤器与拦截器的区别

    过滤器,是在java web中,你传入的request,response提前过滤掉一些信息,或者提前设置一些参数,然后再传入servlet或者struts的 action进行业务逻辑,比如过滤掉非法u ...

  7. 初学Java Web(8)——过滤器和监听器

    什么是过滤器 过滤器就是 Servlet 的高级特性之一,就是一个具有拦截/过滤功能的一个东西,在生活中过滤器可以是香烟滤嘴,滤纸,净水器,空气净化器等,在 Web 中仅仅是一个实现了 Filter ...

  8. JAVA WEB 三器之过滤器(Filter)

    过滤器(Filter) 1. 简介 过滤器可以动态地拦截请求和响应,以变换或使用包含在请求或响应中的信息,它是 Servlet 技术中最实用的技术,属于系统级别,主要是利用函数的回调实现.对 Jsp, ...

  9. SpringMVC内容略多 有用 熟悉基于JSP和Servlet的Java Web开发,对Servlet和JSP的工作原理和生命周期有深入了解,熟练的使用JSTL和EL编写无脚本动态页面,有使用监听器、过滤器等Web组件以及MVC架构模式进行Java Web项目开发的经验。

    熟悉基于JSP和Servlet的Java Web开发,对Servlet和JSP的工作原理和生命周期有深入了解,熟练的使用JSTL和EL编写无脚本动态页面,有使用监听器.过滤器等Web组件以及MVC架构 ...

随机推荐

  1. easyui改变tab标题

    截图:   代码: //更改tab的标题 var tab = $('#microAppVersionTabs').tabs('getTab',0);// 取得第一个tab $('#microAppVe ...

  2. linux上部署Appach,让文件目录以网页列表形式访问

    效果: 1.首先,需要安装Apache httpd服务 yum install -y httpd 2.查看或者设置httpd主配文件 vim /etc/httpd/conf/htpd.conf 从中可 ...

  3. PhoenixFD插件流体模拟——UI布局【Simulation】详解

    前言 之前使用RealFlow做流体模拟,但是总得和3ds导来导去,略显麻烦,特意学习PhoenixFD插件,直接在3ds中进行流体模拟.若读者有更好的流体模拟方法,欢迎在评论区交流. 原文地址:ht ...

  4. 11. Container With Most Water (JAVA)

    Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). ...

  5. FortiGate防火墙HA下联堆叠交换机

    1.拓扑图 2.防火墙配置 3.交换机配置 interface GigabitEthernet1/0/47 switchport access vlan 30 switchport mode acce ...

  6. Java日志框架-logback的介绍及配置使用方法(纯Java工程)(转)

    说明:内容估计有些旧,2011年的,但是大体意思应该没多大变化,最新的配置可以参考官方文档. 一.logback的介绍 Logback是由log4j创始人设计的又一个开源日志组件.logback当前分 ...

  7. js 加减乘除失精

    js 计算失精是因为js 先将10十进制代码转化为2进制,再计算导致 具体解决方案: 1. 加 function accAdd(arg1,arg2){ var r1,r2,m; ].length}} ...

  8. Java线程池的构造以及使用

    有时候,系统需要处理非常多的执行时间很短的请求,如果每一个请求都开启一个新线程的话,系统就要不断的进行线程的创建和销毁,有时花在创建和销毁线程上的时间会比线程真正执行的时间还长.而且当线程数量太多时, ...

  9. angularjs1.x的directive中的link参数element见解

    angular.module("APP",[]) .directive("testDw",function () { return{ restrict:&quo ...

  10. css3回顾 checkbox

    <div class="checkBox"> <input type="checkbox" id="check1"> ...