过滤器与监听器 ----javaweb-10

Posted Charles_H

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了过滤器与监听器 ----javaweb-10相关的知识,希望对你有一定的参考价值。

Filter && Listener

1、过滤器

  过滤器:阻碍一些不符合要求的数据。

  常用在处理中文乱码、登录验证等

 

  1.1、初步使用Filter

  案例:我们将会通过Filter处理中文乱码

  代码展示:

    在这里,要注意继承的Filter接口是servlet的!以及三个固定的方法要写,还有filterChain也要写(作为中间商)

package com.charles.fillter;

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

public class CharacterEncodingFillter implements Filter {

    // 初始化
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("CharacterEncoding初始化");
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=UTF-8");

        System.out.println("执行前");
        // 让我们的请求继续走,不写则停下(中间商)
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("执行后");
    }

    // 销毁
    public void destroy() {
        System.out.println("CharacterEncoding销毁");
    }
}

  在web.xml中注册filter

  这里注意<url-pattern>的意思是 servlet下的所有请求都要经过这个过滤器

    <filter>
        <filter-name>CharacterEncodingFillter</filter-name>
        <filter-class>com.charles.fillter.CharacterEncodingFillter</filter-class>
    </filter>
    
    <filter-mapping>
        <filter-name>CharacterEncodingFillter</filter-name>
        <url-pattern>/servelet/*</url-pattern>
    </filter-mapping>

 

  1.2、简单的登录案例

  首先,我们先编写一个静态初始化参数,用来进行登录时对用户的验证

package com.charles.util;

public class Constant {
    public final static String Servelet_Name = "Servelet_Name";
}

 

  然后,我们编写过滤器:用来建议用户名是否为空

package com.charles.fillter;

import com.charles.util.Constant;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SysFillter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        if (request.getSession().getAttribute(Constant.Servelet_Name) == null){
            response.sendRedirect("/error.jsp");
        }

        filterChain.doFilter(request,response);
    }

    public void destroy() {

    }
}

 

  之后,我们开始依次编写Servlet(登录检验、注销后的跳转)

package com.charles.servelet;

import com.charles.util.Constant;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServelet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");

        if (username.equals("admin")){ // 登陆成功
            req.getSession().setAttribute(Constant.Servelet_Name, req.getSession().getId());
            resp.sendRedirect("/sys/success.jsp");
        } else { // 登陆失败
            resp.sendRedirect("/error.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
package com.charles.servelet;

import com.charles.util.Constant;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginOut extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object attribute = req.getSession().getAttribute(Constant.Servelet_Name);

        if (attribute != null){
            req.getSession().removeAttribute(Constant.Servelet_Name);
            resp.sendRedirect("/Login.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

 

  注册Servlet和Filter

    <servlet>
        <servlet-name>LoginServelet</servlet-name>
        <servlet-class>com.charles.servelet.LoginServelet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>LoginServelet</servlet-name>
        <url-pattern>/servlet/login</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>LoginOutServlet</servlet-name>
        <servlet-class>com.charles.servelet.LoginOut</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>LoginOutServlet</servlet-name>
        <url-pattern>/servlet/loginout</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>SysFilter</filter-name>
        <filter-class>com.charles.fillter.SysFillter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>SysFilter</filter-name>
        <url-pattern>/sys/*</url-pattern>
    </filter-mapping>

 

  最后,依次编写网页(登录网页、登录后的网页、错误网页)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="/servlet/login" method="post">
    用户名:<input type="text" name="username">
    <input type="submit" value="登陆">
</form>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>登陆成功!!</h1>

<p> <a href="/servlet/loginout">注销</a> </p>

</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h1>登陆失败!</h1>
<h3>失败原因:1.无权限 2.用户名错误</h3>

<a href="Login.jsp">返回登录页面</a>

</body>
</html>

 

  运行Tomcat后,结果展示:

  1、登录成功的效果

 

  2、登录失败的效果

 

2、监听器

  监听器用的比较少,这里用一个简单的案例来展示一下即可。

案例:监听访问该网页的次数,并打印内容次数至网页上

代码展示:

 

package com.charles.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

// 统计网站在线人数: 方法:统计session
public class OnlineCountListener implements HttpSessionListener {

    // 创建session监听
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext ctx = se.getSession().getServletContext();
        Integer onlineCount =(Integer) ctx.getAttribute("OnlineCount");

        if (onlineCount == null){
            onlineCount = new Integer(1);
        } else {
            int count = onlineCount.intValue();
            onlineCount = new Integer(count++);
        }
        ctx.setAttribute("onlineCount", onlineCount);
    }

    // 销毁session监听
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext ctx = se.getSession().getServletContext();
        Integer onlineCount =(Integer) ctx.getAttribute("OnlineCount");

        if (onlineCount == null){
            onlineCount = new Integer(0);
        } else {
            int count = onlineCount.intValue();
            onlineCount = new Integer(count--);
        }
        ctx.setAttribute("onlineCount", onlineCount);
    }
}

 

 

  注册listener(这里注意,注册只需要写代码的路径即可)

    <listener>
        <listener-class>com.charles.listener.OnlineCountListener</listener-class>
    </listener>

 

  网页设计

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <h1>当前有 <span style="color: red"><%=this.getServletConfig().getServletContext().getAttribute("onlineCount")%></span>人在线</h1>
  </body>
</html>

 

结果展示:

以上是关于过滤器与监听器 ----javaweb-10的主要内容,如果未能解决你的问题,请参考以下文章

过滤器与监听器知识总结

过滤器与监听器

JAVA Web基础4-过滤器与监听器

Struts的拦截器与xml中的过滤器作用上的区别是啥?监听器的作用?

我的Java之旅 第八课 Servlet 进阶API过滤器与监听器

JavaWeb---在线用户显示与管理---(监听器/过滤器)