过滤器监听器实操----6.21

实验内容
1.用过滤器或监听器实现:记录用户的IP地址和该用户访问过本站点内哪些资源。
2.用监听器实现:在页面上动态显示当前在线人数。
3.用过滤器或监听器实现:记录某个JSP/Servlet(例如index.jsp)自站点启动以来被访问的次数。

提示:
request.getRequestURI() 该方法用于提取被请求的资源的地址
request.getRemoteAddr() 该方法用于提取请求来自于什么IP地址。

第一题
filter文件:

package ch07;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class IP_find implements Filter
{
	private FilterConfig fc=null;
	public void init(FilterConfig fc) throws ServletException
	{
		this.fc=fc;
	}
	public void doFilter (ServletRequest servletrequest,ServletResponse servletresponse,FilterChain chain) throws IOException,ServletException
	{
		if (fc==null)
		{
			return;
		}
		HttpServletRequest request=(HttpServletRequest)servletrequest;
		HttpServletResponse response=(HttpServletResponse)servletresponse;
		String fromip=request.getRemoteAddr();

		//response.setContentType("text/html;charset=GBK"); IP_filter
		PrintWriter out=response.getWriter();
		out.print(fromip);
		out.print("=============================");
		String path = request.getContextPath();
 		String basePath = "==="+request.getRequestURL() ;
 		//request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+
 		out.print(basePath);
 		out.print("=============================");
			

			//response.sendRedirect("../index.htm");				

		chain.doFilter(servletrequest,servletresponse);					
	}
	public void destroy()
	{
		fc=null;
	}	
}

xml文件:

  <filter>
    <display-name>IP_find</display-name>
    <filter-name>IP_find</filter-name>
    <filter-class>ch07.IP_find</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>IP_find</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

jsp文件:
<% out.print("welcome~~~123"); %>

第二题和第三题:
xml文件:

	<listener>
		<listener-class>ch07.Count_renshu</listener-class>
	</listener>

login.jsp文件1:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%= "hello"%>

<a href="Logout.jsp">tuichu</a>
</body>
</html>

Logout.jsp文件:


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
session.invalidate();
%>
</body>
</html>

listener文件:

package ch07;

import java.io.PrintWriter;

import javax.servlet.*;
import javax.servlet.http.*;

public class Count_renshu implements HttpSessionListener
{
	int num=0;
	int count=0;
	public void sessionCreated(HttpSessionEvent hse)
	{
		num++;
		count++;
		System.out.println("当前在线人数:"+num);
		System.out.println("站点被访问了:"+count+"次");

	}
	public void sessionDestroyed(HttpSessionEvent hse)
	{
		num--;
		System.out.println("当前在线人数:"+num);
	}
	
}

posted @ 2021-06-21 17:12  网抑云黑胶SVIP用户  阅读(65)  评论(0编辑  收藏  举报