zoukankan      html  css  js  c++  java
  • java:Filter、Listener 自定义拦截器和过滤器应用

    一,Filter

    FilterEncoding 过滤器,统一设置servlet的编码格式。

    package com.dkt.filter;
    
    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;
    
    public class FilterEncoding  implements Filter{
    	private String encoding;
    	public void destroy() {
    		
    	}
    
    	public void doFilter(ServletRequest request, ServletResponse response,
    			FilterChain chain) throws IOException, ServletException {
    		request.setCharacterEncoding(encoding);
    		response.setCharacterEncoding(encoding);
    		chain.doFilter(request, response);
    		
    	}
    
    	public void init(FilterConfig filterConfig) throws ServletException {
    		//   encoding 在web.xml中配置。开启服务器即加载
    		 encoding = filterConfig.getInitParameter("encoding");
    		 System.out.println(encoding);
    	}
    
    	
    }
    FilterLogin 过滤器,访问页面时,过滤没有登录的用户,跳转到登录页面
    package com.dkt.filter;
    
    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.http.HttpServletRequest;
    import javax.servlet.http.HttpSession;
    
    public class FilterLogin  implements Filter{
    
    	public void doFilter(ServletRequest request, ServletResponse response,
    			FilterChain chain) throws IOException, ServletException {
    		HttpServletRequest hrequest = (HttpServletRequest)request;
    		HttpSession session = hrequest.getSession();
    		Object name = session.getAttribute("name");
    		if (("").equals(name)||name==null) {
    			session.setAttribute("error", "*您还没有登录,请先登录");
    			/*
    			 * 从goodsinfo文件夹下的goodsone页面中,跳转到loginFilter.jsp页面时,需向外跳一级
    			 * request.getRequestDispatcher("../loginFilter.jsp").forward(request, response);
    			 * 从WEB-INF文件下的userinfo文件夹下的userone.jsp页面跳到loginFilter.jsp页面。
    			 * 需要向外跳两级。且WEB-INF文件夹的文件不能再外部通过http直接访问,
    			 * 只能通过内部request的方式跳转页面
    			 */
    			//request.getRequestDispatcher("loginFilter.jsp").forward(request, response);
    			request.getRequestDispatcher("loginFilter.jsp").forward(request, response);
    		}else {
    			chain.doFilter(request, response);
    		}
    	}
    
    	public void destroy() {
    		
    	}
    
    	public void init(FilterConfig arg0) throws ServletException {
    		
    	}
    
    }

    二,Listener

    ListenerOnline 监听器,监听在线人数。并存在application作用域中
    package com.dkt.listener;
    
    import javax.servlet.http.HttpSession;
    import javax.servlet.http.HttpSessionAttributeListener;
    import javax.servlet.http.HttpSessionBindingEvent;
    import javax.servlet.http.HttpSessionEvent;
    import javax.servlet.http.HttpSessionListener;
    
    public class ListenerOnline implements HttpSessionAttributeListener,
    HttpSessionListener{
    	private static int count;//统计在线人数
    	
    	public void attributeAdded(HttpSessionBindingEvent se) {
    		HttpSession session = se.getSession();
    		Object username = session.getAttribute("name");
    		if (username!=null&&!("").equals(username)) {
    			count++;
    			session.getServletContext().setAttribute("count", count);
    		}
    		
    	}
    
    	public void attributeRemoved(HttpSessionBindingEvent se) {
    		
    	}
    
    	public void attributeReplaced(HttpSessionBindingEvent se) {
    		
    	}
    
    	public void sessionCreated(HttpSessionEvent se) {
    		
    	}
    
    	public void sessionDestroyed(HttpSessionEvent se) {
    		if (count>0) {
    			count--;
    			se.getSession().getServletContext().setAttribute("count", count);
    		}
    	}
    
    }
    ListenerR 简单实用监听器
    package com.dkt.listener;
    
    import javax.servlet.ServletRequestAttributeEvent;
    import javax.servlet.ServletRequestAttributeListener;
    import javax.servlet.ServletRequestEvent;
    import javax.servlet.ServletRequestListener;
    
    public class ListenerR implements ServletRequestAttributeListener,
    ServletRequestListener{
    
    	public void attributeAdded(ServletRequestAttributeEvent srae) {
    		System.out.println("属性添加");
    	}
    
    	public void attributeRemoved(ServletRequestAttributeEvent srae) {
    		System.out.println("属性移除");
    	}
    
    	public void attributeReplaced(ServletRequestAttributeEvent srae) {
    		System.out.println("属性替换");
    	}
    
    	public void requestDestroyed(ServletRequestEvent sre) {
    		System.out.println("销毁");
    	}
    
    	public void requestInitialized(ServletRequestEvent sre) {
    		System.out.println("初始化");
    	}
    
    }

    三,servlet

    TestEncodingTwo 验证FilterEncoding 和 ListenerR 
    package com.dkt.servlet;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class TestEncodingTwo extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doPost(request, response);
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    
    		response.setContentType("text/html");
    		String name = request.getParameter("name");
    		String hobby = request.getParameter("hobby");
            System.out.println(name+"----"+hobby);	
            request.setAttribute("name", name);
            request.setAttribute("hobby", hobby);
            /*
    			 初始化
    			属性替换
    			销毁
    			初始化
    			属性替换
    			星星----男
    			属性添加
    			属性添加
    			销毁
             */
    	}
    
    }
    

      LoginServlet 

    package com.dkt.servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import com.dkt.dao.UserJdbc;
    
    public class LoginServlet extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doPost(request, response);
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    
    		response.setContentType("text/html");
    		request.setCharacterEncoding("utf-8");
    		response.setCharacterEncoding("utf-8");
    		HttpSession session = request.getSession();
    		String op = request.getParameter("op");
    		System.out.println("op----------->"+op);
    		if (("login").equals(op)) {
    			String name = request.getParameter("name");
    			String password = request.getParameter("password");
    			Boolean bool = new UserJdbc().validate(name, password);
    			if (bool) {
    				session.setAttribute("name", name);
    				request.getRequestDispatcher("/WEB-INF/userinfo/userone.jsp").forward(request, response);
    			}else {
    				request.getRequestDispatcher("../../loginFilter.jsp").forward(request, response);
    			}
    		}else if (("a").equals(op)) {
    			request.setAttribute("aaa", "apple");
    			PrintWriter out = response.getWriter();
    			out.print("apple");//responseText;
    			out.flush();
    			out.close();
    		}else if(("exit").equals(op)){
    			Object name = session.getAttribute("name");
    			session.invalidate();//销毁session
    			request.getRequestDispatcher("/WEB-INF/userinfo/userone.jsp").forward(request, response);
    		}
    		
    		
    		
    	}
    
    }  

    四,jsp

    loginFilter.jsp

    <%@ 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 'MyJsp.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>
      <body>
    	<form action="LoginServlet?op=login" method="post">
    	   <span style="font-size: 12px;color: red;">${error }</span><br/>
    		用户名:<input type="text" name = "name" value=""><br/><br/>
    		密  码:<input type="password" name = "password"  ><br/>
    		<input type="submit" value="登录">    
    	   <input type="reset" value="重置"><br/>
    	</form>
        <form action="LoginServlet?op=exit" method="post">
        <input type="submit" value="退出" />
        </form>
      </body>
    </html>
    

     index.jsp

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%@page import="com.dkt.entity.UserInfo"%>
    <%@ taglib uri="hello" prefix="hello" %>
    <%
    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 'index.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>
      
      <body>
          用户信息:${name }<br/>
        当前在线人数:${count }
        <hr/>
      
    
      </body>
    </html>
    

      

     

    五,web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" 
    	xmlns="http://java.sun.com/xml/ns/javaee" 
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    	
    	<!-- 配置登录过滤器 -->
    	<filter>
    			<filter-name>loginfilter</filter-name>
    			<filter-class>com.dkt.filter.FilterLogin</filter-class>
    	</filter>
    	<!-- 过滤器适用于多个页面时,可重复多个filter-mappingm,以提供多个页面进行过滤 -->
    	<filter-mapping>
    			<filter-name>loginfilter</filter-name>
    			<url-pattern>/try.jsp</url-pattern>
    	</filter-mapping>
    	<filter-mapping>
    			<filter-name>loginfilter</filter-name>
    			<url-pattern>/goodsinfo/*</url-pattern><!-- 过滤goodsinfo文件夹下的所有文件 -->
    	</filter-mapping>
    	<filter-mapping>
    			<filter-name>loginfilter</filter-name>
    			<url-pattern>/WEB-INF/userinfo/*</url-pattern><!-- 过滤WEB-INF文件夹下的userinfo文件夹下的所有文件 -->
    	</filter-mapping>
    	<filter-mapping>
    			<filter-name>loginfilter</filter-name>
    			<url-pattern>/FilterServlet</url-pattern><!-- 过滤servlet -->
    	</filter-mapping>
    	<!-- 当访问temp.jsp页面时会先执行过滤器,如果用户已登录则可访问
    	    如果没用登录,session里面没有存name属性,则跳到登录页面,让用户登录.
    	    登录成功在跳到temp.jsp
    	 -->
    	 <!-- 初始化过滤器,统一设置编码格式 -->
    	<filter>
    			<filter-name>filterEncoding</filter-name>
    			<filter-class>com.dkt.filter.FilterEncoding</filter-class>
    			<!-- 过滤初始化,设置servlet的编码格式 -->
    			<init-param>
    					<param-name>encoding</param-name>
    					<param-value>utf-8</param-value>
    			</init-param>
    	</filter>
    	<filter-mapping>
    			<filter-name>filterEncoding</filter-name>
    			<url-pattern>/servlet/*</url-pattern>
    <!-- 过滤servlet下的所有servlet,初始化设置编码格式 此servlet下不是包名,是下面的mapping中的url-pattern路径 -->
    	</filter-mapping>
    	
    	<!-- request监听 -->
    	<listener>
    		<listener-class>com.dkt.listener.ListenerR</listener-class>
    	</listener>
    	<listener>
    		<listener-class>com.dkt.listener.ListenerOnline</listener-class>
    	</listener>
    	
    
      <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.dkt.servlet.LoginServlet</servlet-class>
      </servlet>
      <servlet>
        <servlet-name>TestEncodingTwo</servlet-name>
        <servlet-class>com.dkt.servlet.TestEncodingTwo</servlet-class>
      </servlet>
    <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/LoginServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>TestEncodingTwo</servlet-name> <url-pattern>/servlet/TestEncodingTwo</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>

      

  • 相关阅读:
    js随机生成
    黑客代码雨效果
    HTML5 <details> 标签
    fieldset标签——使用(很少使用)
    jQuery总结
    vue element Cascader 级联选择器 选择任意一级选项 点击收起,点击label选中等问题详解
    Vue、element-ui的resetFields()方法重置表单无效问题及解决办法
    常用正则表达式(字符)
    一、日常经验记录
    python-opencv学习第二章
  • 原文地址:https://www.cnblogs.com/nn369/p/8056451.html
Copyright © 2011-2022 走看看