hooyantsing's Blog

第73次课程_监听器与过滤器

字数统计: 2.6k阅读时长: 14 min
2019/10/30

源辰76班

第73次课程

2019.10.30

内容

监听器与过滤器[廖彦]

1.过滤器

89ced8c42d44c9acba6c228f05423a77.png

LoginFilter.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.yc.damai.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.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
* 过滤器也是服务器组件
* 配置同servlet一样有两种:
*        web.xml
*     注解:@WebFilter("/loginFilter")
*/
public class LoginFilter implements Filter {
    /**
     * 销毁方法
     */
    public void destroy() {

    }

    /**
     * 过滤器逻辑规则
     * FilterChain chain 过滤器链对象
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // place your code here
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpSession session = httpRequest.getSession();
        if(session.getAttribute("loginedUser") == null){
            request.setAttribute("msg", "请先登录系统!");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            return;
        }
        // pass the request along the filter chain
        chain.doFilter(request, response);
    }

    /**
     * 初始化方法
     */
    public void init(FilterConfig fConfig) throws ServletException {

    }
}

配置方法:

注释:

1
@WebFilter("/LoginFilter")

WEB-INF/web.xml

1
2
3
4
5
6
7
8
9
10
11
<!-- 过滤器配置 -->
<filter>
    <filter-name>权限访问控制过滤器</filter-name>
    <filter-class>com.yc.damai.servlet.LoginFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>权限访问控制过滤器</filter-name>
    <!-- 配置该过滤器要拦截请求地址(资源路径)  -->
    <url-pattern>/cart.jsp</url-pattern>
    <url-pattern>/olist.jsp</url-pattern>
</filter-mapping>

2.监听器

5e22fcf7451003a0ccc44e0786d63b97.png

410dfd76f64a10081d07397fb631989f.png

OnLineListener.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.yc.damai.servlet;
import java.util.HashSet;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import  javax.servlet.http.HttpSessionAttributeListener;
import  javax.servlet.http.HttpSessionBindingEvent;
/**
* 用户在线监听器
* 监听器没有资源路径
*/
@WebListener
public class OnLineListener implements  HttpSessionAttributeListener {
    
    private HashSet<Object> userSet = new  HashSet<>();
    /**
     * 新增属性触发的事件方法
     */
    public void  attributeAdded(HttpSessionBindingEvent e)  {
         //每一次登陆,保存登录的用户对象到一个集合中
        if("loginedUser".equals(e.getName())) {
           userSet.add(e.getValue());
           //获取应用上下文对象 也就是jsp的application
           ServletContext application =  e.getSession().getServletContext();
           if(application.getAttribute("onlineUserSet")  == null) {
               application.setAttribute("onlineUserSet",  userSet);
           }
        }
    }
    /**
     * 移除属性触发的事件方法
     */
    public void  attributeRemoved(HttpSessionBindingEvent e)   {
          if("loginedUser".equals(e.getName())) {
             userSet.remove(e.getValue());
         }
    }
    /**
     * 修改属性触发的事件方法
     */
    public void  attributeReplaced(HttpSessionBindingEvent e)   {
         // TODO Auto-generated method stub
    }
}

**3.**案例

[对现有大麦(damai)电商项目代码进行改造,根据MVC模式开发”我的订单”(olist)页面]

652cac04951541ab05afd146aaead828.png

Header.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<%@page import="java.util.*"%>
<%@page  import="com.yc.damai.util.DBHelper"%>
<%@ page language="java"  contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<div class="container header">
    
    
<div class="span5">
       <div class="logo">
           <a href="index.jsp">
               <img  src="image/r___________renleipic_01/logo.png" alt="依依不舍"/>
           </a>
       </div>
    </div>
    <div class="span9">
<div class="headerAd">
    <img src="image/header.jpg" width="320"  height="50" alt="正品保障" title="正品保障"/>
</div> </div>
<div class="span10 last">
       <div class="topNav clearfix">
           <ul>
                  
                  <li id="headerLogin"  class="headerLogin" style="display:  list-item;">
                      当前在线人数:${onlineUserSet==null ? 0 : onlineUserSet.size()}个
                  </li>
                  <li id="headerLogin"  class="headerLogin" style="display:  list-item;">
                  <%if(session.getAttribute("loginedUser")==null){%>
                      <a href="login.jsp">登录</a>|
                  <%} else { %>
                      <%-- JSP 注释 :使用  EL 表达式 输出 session 中的 loginedUser 的  username --%>
                      ${loginedUser.username}|
                  <%} %>
                  </li>
                  <li id="headerLogin"  class="headerLogin" style="display:  list-item;">
                      <a  href="orders.s?op=olist">我的订单</a>|
                  </li>
                  <li id="headerRegister"  class="headerRegister" style="display:  list-item;">
                  <a href="logout.s">退出</a>|
               </li>
               
               
               
               
               <li id="headerUsername"  class="headerUsername">
                  ${loginedUser.username}
               </li>
               <li id="headerLogout"  class="headerLogout">
                  <a>[退出]</a>|
               </li>
                      <li>
                          <a>会员中心</a>
                          |
                      </li>
                      <li>
                          <a>购物指南</a>
                          |
                      </li>
                      <li>
                          <a>关于我们</a>
                          
                      </li>
           </ul>
       </div>
       <div class="cart">
           <a  href="cart.jsp">购物车</a>
       </div>
           <div class="phone">
               客服热线:
               <strong>96008/53277764</strong>
           </div>
    </div>
    
<div class="span24">
       <ul class="mainNav">
                  <li>
                      <a href="index.jsp">首页</a>
                      |
                  </li>
                  
                  <%
                      String cSql = "select  * from category";
                      List<Map<String,Object>> clist =  DBHelper.selectList(cSql);
                      pageContext.setAttribute("clist", clist);
                      for(Map<String,Object>  row : clist) {
                  %>
                  <li><a  href="clist.jsp?cid=<%=row.get("cid")%>"><%=row.get("cname")%></a>|</li>
                  <%}%>
                          
       </ul>
    </div>
</div>

OrdersServlet.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.yc.damai.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.google.gson.Gson;
import com.yc.damai.bean.Result;
import com.yc.damai.bean.Orders;
import com.yc.damai.biz.BizException;
import com.yc.damai.biz.OrdersBiz;
import com.yc.damai.util.DBHelper;

@WebServlet("/orders.s")
public class OrdersServlet extends BaseServlet {
    private static final long serialVersionUID = 1L;

    private OrdersBiz biz = new OrdersBiz();

    // 查询  127.0.0.1/191026_Servlet/orders.s?op=olist
    public void olist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(request.getSession().getId());
        @SuppressWarnings("unchecked")
        Map<String,Object> user = (Map<String, Object>) request.getSession().getAttribute("loginedUser");
        // 有风险
        Integer uid = (Integer) user.get("uid");
        List<Orders> list = biz.queryByUid(uid.longValue());
        request.setAttribute("olist", list);
      request.getRequestDispatcher("olist.jsp").forward(request, response);
    }
}

OrdersBiz.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.yc.damai.biz;

import java.util.List;

import com.yc.damai.bean.Orders;
import com.yc.damai.dao.OrdersDao;

public class OrdersBiz {

    private OrdersDao dao = new OrdersDao();

    public List<Orders> queryByUid(Long uid){
        return dao.selectByUid(uid);
    }
}

OrdersDao.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.yc.damai.dao;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

import com.yc.damai.bean.Orders;
import com.yc.damai.bean.User;
import com.yc.damai.util.DBHelper;

public class OrdersDao {

    public List<Orders> selectByUid(Long uid) {

        String sql = "select * from orders where uid=?";
        List<Map<String,Object>> list = DBHelper.selectList(sql, uid);
        List<Orders> ret = new ArrayList<>();
        for(Map<String,Object> row : list){
            Orders o = new Orders();
            try {
                BeanUtils.populate(o, row);
            } catch (IllegalAccessException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
            ret.add(o);
        }
        return ret;
    }

}

olist.jsp

此版本老师所写,由于引入新的jstl标签语言,产生了未知错误。olist_Fixbug.jsp使用了基本的JSP,对此进行了改正。

使用了”jstl标签语言“。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<%@ page language="java"  contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <!-- 导入jstl 核心标签库  alt + /  代码提示 -->
<%@ taglib  uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%>   
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"  content="text/html; charset=UTF-8"/>
<title>大麦商城</title>
<link href="css/common.css" rel="stylesheet"  type="text/css"/>
<link href="css/cart.css" rel="stylesheet"  type="text/css"/>
</head>
<body>
<%@ include file="/common/Header.jsp" %>
<div class="container cart">
       <div class="span24">
       
           <div class="step step1">
               <ul>
                  
                  <li   class="current"></li>
                  <li  >订单列表</li>
               </ul>
           </div>
               <table>
                  <tbody>
                  <!--  items 使用 el 表达式传入    var 循环遍历         -->
                  <c:forEach  items="${olist}" var="o">
                      <tr>
                          <th colspan="5">
                          订单号:${o.oid }
                          金额:<font  color="red">${o.total} </font>
                          状态 :
                              <a  href="pay.jsp?oid=64"><font color="red">付款</font></a>
                          </th>
                      </tr>
                      <tr>
                          <th>图片</th>
                          <th>商品</th>
                          <th>价格</th>
                          <th>数量</th>
                          <th>小计</th>
                      </tr>
                      <tr>
                          <td width="60">
                              <img  src="products/1/cs10001.jpg"/>
                          </td>
                          <td>
                              <a  target="_blank">韩版连帽加厚毛衣女外套</a>
                          </td>
                          <td>
                              228.0
                          </td>
                          <td  class="quantity" width="60">
                                 1                         
                          </td>
                          <td width="140">
                              <span  class="subtotal">¥228.0</span>
                          </td>
                      </tr>
                  </c:forEach>
               </tbody>
               
           </table>
               
           
       </div>
       
    </div>
<%@ include file="/common/Footer.jsp" %>
</body>
</html>

olist_Fixbug.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<%@page import="com.yc.damai.bean.Orders"%>
<%@ page language="java"  contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <!-- 导入jstl 核心标签库  alt + /  代码提示 -->
<%@ taglib  uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%>   
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"  content="text/html; charset=UTF-8"/>
<title>大麦商城</title>
<link href="css/common.css" rel="stylesheet"  type="text/css"/>
<link href="css/cart.css" rel="stylesheet"  type="text/css"/>
</head>
<body>
<%@ include file="/common/Header.jsp" %>
<div class="container cart">
       <div class="span24">
       
           <div class="step step1">
               <ul>
                  
                  <li   class="current"></li>
                  <li  >订单列表</li>
               </ul>
           </div>
               <table>
                  <tbody>
                  <!--  items 使用 el 表达式传入    var 循环遍历         -->
                  <%
                      List<Orders> list =  (List<Orders>)request.getAttribute("olist");
                      for(Orders o : list) {
                  %>
                      <tr>
                          <th colspan="5">
                          订单号:<%=o.getOid() %>
                          金额:<font  color="red"><%=o.getTotal() %> </font>
                          状态 :
                              <a  href="pay.jsp?oid=64"><font color="red">付款</font></a>
                          </th>
                      </tr>
                      <tr>
                          <th>图片</th>
                          <th>商品</th>
                          <th>价格</th>
                          <th>数量</th>
                          <th>小计</th>
                      </tr>
                      <tr>
                          <td width="60">
                              <img  src="products/1/cs10001.jpg"/>
                          </td>
                          <td>
                              <a  target="_blank">韩版连帽加厚毛衣女外套</a>
                          </td>
                          <td>
                              228.0
                          </td>
                          <td  class="quantity" width="60">
                                 1                         
                          </td>
                          <td width="140">
                              <span  class="subtotal">¥228.0</span>
                          </td>
                      </tr>
                  <%} %>
               </tbody>
               
           </table>
               
           
       </div>
       
    </div>
<%@ include file="/common/Footer.jsp" %>
</body>
</html>
CATALOG