前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Filter、Listener 学习总结

Filter、Listener 学习总结

作者头像
bgZyy
发布2018-05-16 14:36:35
1.2K0
发布2018-05-16 14:36:35
举报

  今天我们来介绍 Filter、Listener 这两个模块一些简单的知识和应用,接下来我们开始我们的正题 !

  1. Filter(过滤器)

    1.1 对 Servlet 容器调用 Servlet 的过程进行拦截,从而在 Servlet 进行响应的前后实现一些特殊的功能,我们需要知道 JSP 的底层实现也是 Servlet 所以所拦截的当然包括 JSP

    1.2 如何写一个 FIiter?

      a. 实现 Filter 接口(类似于 Servlet 接口,我们可以对比 Servlet 接口学习 Filter)

      b. 在 web.xml 文件中映射文件 Filter

      c. 配置所要拦截的资源

    1.3 Filter 接口

      a. Filter 对象在被 WEB 应用加载的时候便被创建, init(FilterConfig filterConfig)  方法在创建 Filter 对象的时候别调用,且只有一次;FilterConfig 对象类似于 ServletConfig 对象,可以获取当前 FilterConfig 的初始化参数;

      b.  doFilter(ServletRequest request, ServletResponse response, FilterChain chain)  每次请求的拦截都会调用该方法,所以便是执行逻辑代码的方法,利用此方法拦截请求后使用方法  chain.doFilter(requset, response);  释放链接,或者传给下一个 Filter 进行拦截,或者将请求放回请求资源

      c. 对于多个 Filter,其执行顺序按照 web.xml 文件中的映射顺序执行,与创建时间无关

      d. 小案例之 HelloWorld

        Ⅰ. 演示

        Ⅱ. 功能介绍

          a. 一个小登录页面,用户名和密码分别配置为当前 WEB 的应用初始化参数,通过获取请求参数和配置的初始化参数进行比较,若正确则响应欢迎页面,否则返回原页面响应错误消息;

        Ⅲ. 代码

          a. 登录页面

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3 <head>
 4     <title>Login</title>
 5 </head>
 6 <body>
 7 <h3>${requestScope.message}</h3>
 8 <form action="hello.jsp" method="post">
 9     UserName: <input type="text" name="name"><br><br>
10     PassWord: <input type="password" name="password"><br><br>
11     <button type="submit">Submit</button>
12 </form>
13 </body>
14 </html>

          b. web.xml

 1 <context-param>
 2 <!-- 配置用户名为当前 WEB 应用的初始化参数 -->
 3         <param-name>name</param-name>
 4         <param-value>Yin</param-value>
 5 </context-param>
 6 <filter>
 7         <filter-name>LoginFilter</filter-name>
 8         <filter-class>com.javaweb.filter.hello.LoginFilter</filter-class>
 9     </filter>
10     <filter>
11         <filter-name>HelloFilter</filter-name>
12         <filter-class>com.javaweb.filter.hello.HelloFilter</filter-class>
13         <init-param>
14 <!-- 配置密码为 Filter 初始化 -->
15             <param-name>password</param-name>
16             <param-value>123</param-value>
17         </init-param>
18 </filter>

          c. UserNameFilter.java

 1 package com.javaweb.filter.hello;
 2 
 3 import com.sun.org.apache.regexp.internal.RE;
 4 
 5 import javax.servlet.*;
 6 import java.io.IOException;
 7 
 8 /**
 9  */
10 public class UserNameFilter implements Filter {
11     private FilterConfig filterConfig;
12 
13     @Override
14     public void init(FilterConfig filterConfig) throws ServletException {
15         this.filterConfig = filterConfig;
16     }
17 
18     @Override
19     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
20         String userName = servletRequest.getParameter("name");
21         String nameReal = filterConfig.getServletContext().getInitParameter("name");
22 
23         if (!userName.equals(nameReal)) {
24             servletRequest.setAttribute("message", "用户名错误");
25             servletRequest.getRequestDispatcher("/helloFilter/login.jsp").forward(servletRequest, servletResponse);
26             return;
27         }
28         filterChain.doFilter(servletRequest, servletResponse);
29     }
30 
31     @Override
32     public void destroy() {
33 
34     }
35 }

          d. PasswordFilter.java

 1 package com.javaweb.filter.hello;
 2 
 3 
 4 import javax.servlet.*;
 5 import java.io.IOException;
 6 
 7 /**
 8  * Created by shkstart on 2017/11/23.
 9  */
10 public class HelloFilter implements Filter {
11     private FilterConfig filterConfig;
12 
13     @Override
14     public void init(FilterConfig filterConfig) throws ServletException {
15         this.filterConfig = filterConfig;
16     }
17 
18     @Override
19     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
20         String password = servletRequest.getParameter("password");
21         String passReal = filterConfig.getInitParameter("password");
22 
23         if (!password.equals(passReal)) {
24             servletRequest.setAttribute("message", "密码错误");
25             servletRequest.getRequestDispatcher("/helloFilter/login.jsp").forward(servletRequest, servletResponse);
26             return;
27         }
28         filterChain.doFilter(servletRequest, servletResponse);
29     }
30 
31     @Override
32     public void destroy() {
33 
34     }
35 }

      e. 案例 -- 字符编码过滤器

        Ⅰ. 演示

         Ⅱ. 功能介绍

          a. 在乱码显示之后我们将此页面加入字符编码的过滤器,从而显示正常  

          b. 在 web.xml 文件中配置一个编码方式(UTF-8)为当前 WEB 应用的初始化参数,在过滤器中在每一个请求之前改变字符编码,防止乱码

        Ⅲ. 代码

          a. 页面

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3 <head>
 4     <title>FormPage</title>
 5 </head>
 6 <body>
 7   <form action="b.jsp" method="post">
 8       UserName: <input type="text" name="name"><br><br>
 9       <button type="submit">Submit</button>
10   </form>
11 </body>
12 </html>

        b.jsp

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3 <head>
 4     <title>Welcom</title>
 5 </head>
 6 <body>
 7   <h3>
 8       Hello ${param.name}
 9   </h3>
10 </body>
11 </html>

        web.xml

 1     <context-param>
 2         <param-name>encoding</param-name>
 3         <param-value>UTF-8</param-value>
 4     </context-param>
 5     <filter>
 6         <filter-name>EncodingFilter</filter-name>
 7         <filter-class>com.javaweb.filter.hello.encoding.filter.EncodingFilter</filter-class>
 8     </filter>
 9     <filter-mapping>
10         <filter-name>EncodingFilter</filter-name>
11         <url-pattern>/*</url-pattern>
12     </filter-mapping>

        EncodingFilter.java

package com.javaweb.filter.hello.encoding.filter;

import javax.servlet.*;
import java.io.IOException;

public class EncodingFilter implements Filter {
    private FilterConfig filterConfig;

    public void destroy() {

    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        ServletContext servletContext = filterConfig.getServletContext();
        String encoding = servletContext.getInitParameter("encoding");
        req.setCharacterEncoding(encoding);

        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {
        this.filterConfig = config;
    }
}

       f. 案例 -- 权限管理

        Ⅰ. 演示

        Ⅱ. 功能介绍

          a. 用户登录成功后可以根据用户所拥有的权限过滤用户可登录的页面,若用户拥有该权限,则可以访问该页面,否则提示用户没有权限;

          b. 管理员登录页面,登录成功后可以管理用户所拥有的权限,如上;

          c. 该案例采用 Map 变量代替数据库存储用户的权限信息;

          d. 流程解析

            1. 新建 User、Authority 两个类,User 中包含了  String UserName、List<Authority> authorityList  两个变量,Authority 中包含了  String AuthorityName,String url  两个变量,其中 url 为当前权限所对应的目标页面;

            2. 新建 UserDao 类,首先初始化权限信息,模仿数据库将所有的权限信息存入  List<Authority> authorityList  变量中,并编写  getAuthorityList()  方法,用于获取所有的权限;

            3. 在 UserDao 类模仿数据库将用户以及用户所拥有的权限信息存入  Map<String, List<Authority> userInfo  变量中,在初始化的时候为用户赋予其所拥有的权限;

            4. 我们将 2,3 中模仿数据库的代码写入 static 代码块中,只初始化一次就好;

            5. 在 UserDao 类编写方法  getUser(String userName)  和  update(String userName, List<Authority> authority)  两个方法,分别用户获取权限和更新权限;

            6. 用户登录成功后显示所有可能被访问的页面,点击超链接后利用过滤器拦截请求根据其所拥有的权限所对应的页面和访问的页面对比给出响应;

            7. 管理页面登录成功后可以可以选择更改权限,具体代码如下:

        Ⅲ. 代码 

          User Authority 类

 1 package com.javaweb.authority.domain;
 2 
 3 import java.util.List;
 4 
 5 /**
 6  * Created by shkstart on 2017/11/27.
 7  */
 8 public class User {
 9     private String userName;
10     private List<Authority> authorityList;
11 
12     public String getUserName() {
13         return userName;
14     }
15 
16     public void setUserName(String userName) {
17         this.userName = userName;
18     }
19 
20     public List<Authority> getAuthorityList() {
21         return authorityList;
22     }
23 
24     public void setAuthorityList(List<Authority> authorityList) {
25         this.authorityList = authorityList;
26     }
27 
28     public User(String userName, List<Authority> authorityList) {
29         this.userName = userName;
30         this.authorityList = authorityList;
31     }
32 
33     public User() {
34 
35     }
36 }
 1 package com.javaweb.authority.domain;
 2 
 3 /**
 4  * Created by shkstart on 2017/11/27.
 5  */
 6 public class Authority {
 7     private String displayName;
 8     private String url;
 9 
10     public String getDisplayName() {
11         return displayName;
12     }
13 
14     public void setDisplayName(String displayName) {
15         this.displayName = displayName;
16     }
17 
18     public String getUrl() {
19         return url;
20     }
21 
22     public void setUrl(String url) {
23         this.url = url;
24     }
25 
26     public Authority(String displayName, String url) {
27         this.displayName = displayName;
28         this.url = url;
29     }
30 
31     public Authority() {
32 
33     }
34 }
 1 package com.javaweb.authority.dao;
 2 
 3 import com.javaweb.authority.domain.Authority;
 4 import com.javaweb.authority.domain.User;
 5 
 6 import java.util.ArrayList;
 7 import java.util.HashMap;
 8 import java.util.List;
 9 import java.util.Map;
10 
11 public class UserDao {
12     private static Map<String, User> userMap;
13     private static List<Authority> authorityList;
14 
15     static {
16         userMap = new HashMap<String, User>();
17         authorityList = new ArrayList<Authority>();
18 
19         authorityList.add(new Authority("Article_1", "/authority/article_1.jsp"));
20         authorityList.add(new Authority("Article_2", "/authority/article_2.jsp"));
21         authorityList.add(new Authority("Article_3", "/authority/article_3.jsp"));
22         authorityList.add(new Authority("Article_4", "/authority/article_4.jsp"));
23 
24         User user1 = new User("YY", authorityList.subList(0, 2));
25 
26         User user2 = new User("SS", authorityList.subList(2, 4));
27 
28         userMap.put("YY", user1);
29         userMap.put("SS", user2);
30     }
31 
32     public static User getUser(String userName) {
33         User user = null;
34 
35         if (userMap.containsKey(userName)) {
36             user = userMap.get(userName);
37         }
38         return user;
39     }
40 
41     public static void update(String userName, List<Authority> authorityList) {
42         User user = getUser(userName);
43         user.setAuthorityList(authorityList);
44     }
45 
46     public static List<Authority> getAuthorityList() {
47         return authorityList;
48     }
49 }

          用户登录页面(用户登录成功后重定向到所要访问的页面 ArticleList.jsp)

 1 <%--登录页面--%>
 2 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 3 <html>
 4 <head>
 5     <title>LoginPage</title>
 6 </head>
 7 <body>
 8   <h3>${requestScope.message}</h3>
 9   <form action="login.do" method="post">
10       UserName: <input type="text" name="userName"><br><br>
11       <button type="submit">Submit</button>
12   </form>
13 </body>
14 </html>

          Servlet 和以前一样,利用反射实现多个请求利用一个 Servlet,其 login 方法如下

 1     /*
 2     * 权限过滤功能中的登录函数
 3     * */
 4     protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 5         String userName = request.getParameter("userName");
 6         User user = UserDao.getUser(userName);
 7 //        判断用户是否存在
 8         isUser(request, response);
 9 //        将用户信息封装到 session 中,便于后面获取
10         getSession(request).setAttribute("loginUserName", userName);
11         response.sendRedirect(request.getContextPath() + "/authority/ArticleList.jsp");
12     }

          login 方法所使用到的 isUser 方法

 1     /*
 2     * 过滤权限功能的登录页面中对不存在的用户名的处理
 3     * */
 4     protected void isUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 5         String userName = request.getParameter("userName");
 6         User user = UserDao.getUser(userName);
 7         if (user == null) {
 8 //            将错误消息加入到 request 中,便于转发会页面时显示
 9             request.setAttribute("message", "该用户不存在");
10             request.getRequestDispatcher("/index.jsp").forward(request, response);
11             return;
12         }
13     }

          ArticleList.jsp 页面 -- 重定向到的页面

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3 <head>
 4     <title>ArticleList</title>
 5 </head>
 6 <body>
 7 <a href="article_1.jsp">Article1 Page</a><br><br>
 8 <a href="article_2.jsp">Article2 Page</a><br><br>
 9 <a href="article_3.jsp">Article3 Page</a><br><br>
10 <a href="article_4.jsp">Article4 Page</a><br><br>
11 </body>
12 </html>

          由于我们将所有访问页面和登录页面以及其他不需要拦截的页面在一个文件夹下,所以我们将那些不需要拦截的页面配置为 WEB 应用的初始化参数,在拦截器中判断。

          每次点击超链接的时候拦截请求,将登录用户所拥有的权限和所访问页面对比,给出响应,AuthorityFilter 代码如下:

 1 package com.javaweb.authority.filter;
 2 
 3 import com.javaweb.authority.dao.UserDao;
 4 import com.javaweb.authority.domain.Authority;
 5 import com.javaweb.authority.domain.User;
 6 
 7 import javax.servlet.*;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 import java.io.IOException;
11 import java.util.Arrays;
12 import java.util.List;
13 
14 /**
15  * 权限管理小实例:权限过滤
16  * 1. 将所有页面加入到一个目录下,把其中不需要过滤的页面配置为当前 WEB 应用的初始化参数
17  * 2. 判断用户信息是否存在,若不存在则重定向会登录页面,防止直接访问 ArticleList 页面
18  * 3. 判断当前所请求的页面是否为不需要过滤的页面,若是则直接释放请求,并结束方法
19  * 4. 若不是判断当前登录用户的 List<Authority> 的 URl 值是否和所请求的页面的 url 值是否相等,若相等则释放请求
20  * 5. 若不相等则重定向到错误页面
21  */
22 public class AuthorityFilter implements Filter {
23     private FilterConfig filterConfig;
24     private ServletContext servletContext;
25 
26     public void destroy() {
27     }
28 
29     public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
30 //        强制转换为 HttpServletXxx
31         HttpServletRequest request = (HttpServletRequest) req;
32         HttpServletResponse response = (HttpServletResponse) resp;
33 //        获取初始化参数,不被过滤的页面
34         String uncheckedPage = servletContext.getInitParameter("uncheckedPage");
35         List<String> uncheckedPageList = Arrays.asList(uncheckedPage.split(","));
36 //        获取请求页面
37         String servletPath = request.getServletPath();
38 //        获取用户信息
39         String userName = (String) request.getSession().getAttribute("loginUserName");
40         if (userName == null) {
41             response.sendRedirect(request.getContextPath() + "/index.jsp");
42         }
43 //        判断所访问页面是否为不需要拦截的页面,若是则直接释放请求
44         for (String page : uncheckedPageList) {
45             if (page.equals(servletPath)) {
46                 chain.doFilter(request, response);
47                 return;
48             }
49         }
50 //        因为对每次请求过滤的时候就会重新从 UserDao 中获取,也就是 Map 中,所以在后台更新后不用刷新就可以使用
51         List<Authority> authorityList = UserDao.getUser(userName).getAuthorityList();
52 //        若是需要拦截的页面,则遍历用户所拥有权限,将其 url 和目标页面对比,若是则结束方法,释放连接,若不是则返回错误页面
53         for (Authority authority : authorityList) {
54             String url = authority.getUrl();
55             if (url.equals(servletPath)) {
56                 chain.doFilter(request, response);
57                 return;
58             }
59         }
60 
61         response.sendRedirect(request.getContextPath() + "/authority/NoAuthority.jsp");
62     }
63     /*
64     * 初始化参数,FilterConfig 必须放在第一行
65     * */
66     public void init(FilterConfig config) throws ServletException {
67         this.filterConfig = config;
68         servletContext = config.getServletContext();
69     }
70 }

          若没有对应的权限响应的页面代码如下:

 1 <%--
 2   Created by IntelliJ IDEA.
 3   User: yin‘zhao
 4   Date: 2017/11/28
 5   Time: 12:41
 6   To change this template use File | Settings | File Templates.
 7 --%>
 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 9 <html>
10 <head>
11     <title>NoAuthority</title>
12 </head>
13 <body>
14   <h3>对不起,你没有权限请<a href="ArticleList.jsp">返回</a></h3>
15 </body>
16 </html>

          以上代码便是过滤用户权限信息的代码,接下来我们开始权限管理代码:

            管理登录页面 authority_manager.jsp(登录代码)

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 3 <html>
 4 <head>
 5     <title>Manager</title>
 6 </head>
 7 <body>
 8 <h3>
 9     <%--显示错误消息的 EL 表达式--%>
10     ${requestScope.message}
11     <form action="${pageContext.request.contextPath}/query.do" method="post">
12         <%--用户名--%>
13         UserName: <input type="text" name="userName" value="${param.userName}"><br>
14         <button type="submit">Submit</button>
15         <br><br>
16     </form>
17 </h3>
18 </body>
19 </html>

            提交请求到 Servlet 类中的 query 方法,query 方法代码如下

 1 protected void query(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 2 //        获取请求参数 userName
 3         String userName = request.getParameter("userName");
 4 //        根据 userName 获取 User 对象
 5         User user = UserDao.getUser(userName);
 6 //        判断 user 是否为空,若为空返回原页面结束方法,并提示错误消息
 7         if (user == null) {
 8             request.setAttribute("message", "该用户不存在");
 9             request.getRequestDispatcher("/authority_manager/authority_manager.jsp").forward(request, response);
10             return;
11         }
12 //        若 user 存在则将 User 信息保存到 session 中,方便后面页面的回显
13         getSession(request).setAttribute("userName", userName);
14 //        获取用户当前所有的权限信息
15         List<Authority> authorityList = user.getAuthorityList();
16 //        将用户的权限信息和所有的权限信息封装到 request 请求域中,转发传回页面
17         if (authorityList.size() != 0) {
18             request.setAttribute("userAuthorityList", authorityList);
19             request.setAttribute("authorityList", UserDao.getAuthorityList());
20             request.getRequestDispatcher("/authority_manager/authority_manager.jsp").forward(request, response);
21         }
22     }

           query 方法将登录用户所拥有的权限封装到 request 域中,然后转发回原页面,利用 JSTL 以及 EL 在页面显示权限信息,authority_manager.jsp

 1 <%--
 2   Created by IntelliJ IDEA.
 3   User: yin‘zhao
 4   Date: 2017/11/27
 5   Time: 21:19
 6   To change this template use File | Settings | File Templates.
 7 --%>
 8 <%--权限管理页面--%>
 9 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
10 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
11 <html>
12 <head>
13     <title>Manager</title>
14 </head>
15 <body>
16 <h3>
17     <%--显示错误消息的 EL 表达式--%>
18     ${requestScope.message}
19     <form action="${pageContext.request.contextPath}/query.do" method="post">
20         <%--用户名--%>
21         UserName: <input type="text" name="userName" value="${param.userName}"><br>
22         <button type="submit">Submit</button>
23         <br><br>
24     </form>
25         <%--多选框提交表单,用户显示更改登录用户的权限信息--%>
26     <form action="${pageContext.request.contextPath}/update.do" method="post">
27         <table cellspacing="20" cellpadding="0">
28             <%--判断 request 域中的权限信息是否为空,若不为空则显示多选框--%>
29             <c:if test="${!empty requestScope.userAuthorityList}">
30                 <tr>
31                     <th>${sessionScope.userName}的权限是</th>
32                 </tr>
33                 <c:forEach items="${requestScope.authorityList}" var="authority">
34                     <%--设置标识,用于为多选框打勾的标准,此表示需要每次遍历完内层循环后置为 false,因为每次根据 flag 的值只打印一个多选框--%>
35                     <c:set var="flag" value="false"></c:set>
36                     <c:forEach items="${requestScope.userAuthorityList}" var="userAuthority">
37                         <%--若当前 URl 和所有的 URl 有相等值则为其打勾,否则正常显示多选框--%>
38                         <c:if test="${userAuthority.url == authority.url}">
39                             <c:set var="flag" value="true"></c:set>
40                         </c:if>
41                     </c:forEach>
42                     <c:if test="${flag == true}">
43                         <tr>
44                             <td>${authority.displayName}</td>
45                             <td><input type="checkbox" value="${authority.url}" name="authority" checked></td>
46                         </tr>
47                     </c:if>
48                     <c:if test="${flag == false}">
49                         <tr>
50                             <td>${authority.displayName}</td>
51                             <td><input type="checkbox" value="${authority.url}" name="authority"></td>
52                         </tr>
53                     </c:if>
54                 </c:forEach>
55                 <tr>
56                     <td><button type="submit">Update</button></td>
57                 </tr>
58             </c:if>
59         </table>
60     </form>
61 </h3>
62 </body>
63 </html>

          在页面上如果需要更改登录用户的权限,我们选择上对应的权限点击提交按钮到 Servlet 的 Update 方法,代码如下

 1     protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 2 //        获取多选框的提交信息,即权限信息
 3         String[] authorityVal = request.getParameterValues("authority");
 4 //        获取 session 中保存的用户信息
 5         String userName = (String) getSession(request).getAttribute("userName");
 6 //        用于保存用户更新后的权限信息的 List
 7         List<Authority> authorityList = new ArrayList<Authority>();
 8 
 9 //        获取所有的权限信息的第 i 个,和用户权限信息对比,若 URl 相等则将完整的权限信息加到预先定义好的 List 中
10         List<Authority> secondAuthorityList = UserDao.getAuthorityList();
11         for (int i = 0; i < authorityVal.length; i++) {
12             for (Authority authority : secondAuthorityList) {
13                 if (authority.getUrl().equals(authorityVal[i])) {
14                     authorityList.add(authority);
15                 }
16             }
17         }
18 //        执行更新操作,userName 为 session 域中提前保存的,List<Authority> 为上面所对比添加的
19         UserDao.update(userName, authorityList);
20         response.sendRedirect(request.getContextPath() + "/authority_manager/authority_manager.jsp");
21     }
22 
23     protected HttpSession getSession(HttpServletRequest request) throws ServletException, IOException {
24         return request.getSession();
25     }

          web.xml (配置文件)        

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
 5          version="3.1">
 6     <context-param>
 7         <param-name>uncheckedPage</param-name>
 8         <param-value>/authority/ArticleList.jsp,/authority/NoAuthority.jsp</param-value>
 9     </context-param>
10     <filter>
11         <filter-name>AuthorityFilter</filter-name>
12         <filter-class>com.javaweb.authority.filter.AuthorityFilter</filter-class>
13     </filter>
14     <filter-mapping>
15         <filter-name>AuthorityFilter</filter-name>
16         <url-pattern>/authority/*</url-pattern>
17     </filter-mapping>
18     <servlet>
19         <servlet-name>ManagerServlet</servlet-name>
20         <servlet-class>com.javaweb.authority.controller.ManagerServlet</servlet-class>
21     </servlet>
22     <servlet-mapping>
23         <servlet-name>ManagerServlet</servlet-name>
24         <url-pattern>*.do</url-pattern>
25     </servlet-mapping>
26 </web-app>

        下面我贴出案例目录结构,方便大家更好的理解 

   2. Listener(监听器)

    2.1 专门用于对其他对象身上发生的时间或状态改变进行监听和相应处理的对象,当被监听的对象发生变化时立即采取响应的行动

    2.2 Servlet 监听器:Servlet 规范中定义了一种特殊类,它用于监听 web 应用程序中的 ServletContext HttpSession ServletRequest 等域对象的创建和销毁事件,以及监听这些域对象中的属性发生修改的事件

    2.3 分类

      a. 监听域对象自身的创建和销毁的事件监听器(ServletContextListener,HttpSessionListener,ServletRequestListener)

      b. 监听域对象中属性的增加和删除的事件监听器(ServletContextAttributeListener, HttSessionAttributeListener,ServletRequestAttributeListener)

      c. 监听绑定到 HttpSession 域中某个对象的状态的事件监听器 

    2.4 ServletContextListener(最常用的 Listener)  

      a. ServletContextListener 接口用于监听 ServletContext 对象的创建和销毁事件 

      b. 当 ServletContext 对象被创建后,激发  contextInitialize(ServletContextEvent sce) 方法

        Ⅰ. 可以在当前 WEB 应用被加载时对当前 WEB 应用的相关资源进行初始化操作:比如:创建数据库连接池,创建 Spring 的 IOC 容器,读取当前 WEB 应用的初始化参数;

      c. 当ServletContext 对象被销毁前,激发  contextDestroyed(ServletContextEvent sce)  方法(当前 WEB 应用从服务器中卸载的时候)

    2.5 HttpSessionListener

           a. 创建后激发  sessionCreated(HttpSessionEvent se)  方法

           b. 销毁前激发  sessionDestroyed(HttpSessionEvent se)  方法

    2.6 ServletRequestListener

      a. 创建后激发  requestInitialized(ServletRequestEvernt sre)  方法

      b. 销毁前激发  requestDeatroyed(ServletRequestEvent sre)  方法

    2.7 创建一个监听器

      a. Servlet 规范为每种事件监听器都定义了相应的接口,只需实现这些接口即可,web 服务器根据所实现的接口把他注册到相应的被监听对象,web 服务器根据在 web.xml 文件注册的顺序来加载和注册这些 Servlet 监听器

    2.8 属性监听器

      a. 如上所说那三个监听器,在此类监听器中可以得到属性值和属性名 getName(), getValue ,具体读者可以参看 API

  以上就是本次的内容,还是一样,谢谢大家愿意花时间阅读完我的文章,如果其内有写的不合适、不正确的地方还望大家指出!

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-12-10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档