JavaWeb(39) : 过滤器与监听器应用案例

一、分IP统计访问次数

AListener.java :

package waf.yty.web.listener;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class AListener implements ServletContextListener {
	/**
	 * 服务器启动时创建Map,保存到ServletContext中
	 */
	public void contextInitialized(ServletContextEvent sce)  { 
		// 创建Map
		Map<String, Integer> map = new LinkedHashMap<String, Integer>();
		// 得到ServletContext
		ServletContext application = sce.getServletContext();
		// 把map保存到application中
		application.setAttribute("map", map);
	}

	public void contextDestroyed(ServletContextEvent sce)  { 
		// TODO Auto-generated method stub
	}
	
}

AFilter.java :

package waf.yty.web.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
 * 从application中获取Map
 * 从request中得到当前客户端的IP
 * 进行统计工作,结果保存到Map中  
 * @author yangtengyu
 *
 */
public class AFilter implements Filter {
	
	private FilterConfig config;

	public void destroy() {
		// TODO Auto-generated method stub
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		// 1.得到application中的map
		ServletContext app = config.getServletContext();
		Map<String, Integer> map = (Map<String, Integer>) app.getAttribute("map");
		// 2.从request中获取当前客户端的ip地址
		String ip = request.getRemoteAddr();
		// 3.查看map中是否存在这个ip对应访问次数。如果存在,把次数+1再保存回去。
		// 4.如果不存在这个ip,说明是第一次访问本站,设置访问次数为1。
		if (map.containsKey(ip)) { // ip存在于map,说明不是第一次访问
			int cnt = map.get(ip);
			map.put(ip, cnt+1);
		} else { // ip不存在于map,说明是第一次访问
			map.put(ip, 1);
		}
		app.setAttribute("map", map); // 把map再放回ServletContext中
		
		chain.doFilter(request, response); // 肯定放行
	}

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

}

show.jsp :

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
</head>
  
  <body>
<h1 align="center">显示结果</h1>
<table align="center" width="60%" border="1">
	<tr>
		<th>IP</th>
		<th>次数</th>
	</tr>
<c:forEach items="${map }" var="entry">
	<tr>
		<td>${entry.key }</td>
		<td>${entry.value }</td>
	</tr>
</c:forEach>	
</table>
  </body>
</html>

web.xml :

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>day21_3</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <filter>
    <display-name>AFilter</display-name>
    <filter-name>AFilter</filter-name>
    <filter-class>waf.yty.web.filter.AFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>AFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <listener>
    <listener-class>waf.yty.web.listener.AListener</listener-class>
  </listener>
</web-app>

二、权限的游戏

AdminFilter.java (此过滤器只对管理员放行,拦截除了管理员外的所有) :

web.xml中配置AdminFilter :

  <filter>
    <display-name>AdminFilter</display-name>
    <filter-name>AdminFilter</filter-name>
    <filter-class>waf.yty.web.filter.AdminFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>AdminFilter</filter-name>
    <url-pattern>/admin/*</url-pattern>
  </filter-mapping>
package waf.yty.web.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;

public class AdminFilter implements Filter {

	public void destroy() {
		// TODO Auto-generated method stub
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

		// 1.得到session
		HttpServletRequest req = (HttpServletRequest) request;
		// 2.判断sesison域中是否存在admin,如果存在,放行
		String name = (String) req.getSession().getAttribute("admin");
		if (name != null) {
			chain.doFilter(request, response);
		} else {
			req.setAttribute("msg", "不是管理员,黑山猪包子铺欢迎您");
			req.getRequestDispatcher("/login.jsp").forward(request, response);
		}
	}

	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}

UserFilter.java ( 此过滤器放行管理员与会员,拦截不充钱的游客 ) :

web.xml中配置UserFilter :

  <filter>
    <display-name>UserFilter</display-name>
    <filter-name>UserFilter</filter-name>
    <filter-class>waf.yty.web.filter.UserFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>UserFilter</filter-name>
    <url-pattern>/users/*</url-pattern>
  </filter-mapping>
package waf.yty.web.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;

public class UserFilter implements Filter {

	public void destroy() {
		
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		// 1.得到session
		HttpServletRequest req = (HttpServletRequest) request;
		// 2.判断sesison域中是否存在admin,如果存在,放行
		String name = (String) req.getSession().getAttribute("admin");
		if (name != null) {
			chain.doFilter(request, response);
			return;
		}
		// 3.判断sesison域中是否存在username,如果存在,放行,否则回到login.jsp!
		 name = (String) req.getSession().getAttribute("username");
		 if (name != null) {
			chain.doFilter(request, response);
		} else {
			req.setAttribute("msg", "不是User,别跟溜达猪一样");
			req.getRequestDispatcher("/login.jsp").forward(request, response);
		}
	}

	public void init(FilterConfig fConfig) throws ServletException {
		
	}

}

LoginServlet.java :

web.xml中配置LoginServlet :

  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>waf.yty.web.servlet.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
package waf.yty.web.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;

public class LoginServlet extends HttpServlet {

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		// 1.获取用户名
		String username = request.getParameter("username");
		// 2.判断用户名中是否包含YYRY
		
		// 3.包含,就是管理员
		
		// 4.不包含,普通会员
		
		// 5.把登陆的用户名称保存到session中
		if (username.contains("YYRY")) {
			request.getSession().setAttribute("admin", username);
		} else {
			request.getSession().setAttribute("username", username);
		}
	
		// 6.转发index.jsp
		request.getRequestDispatcher("/index.jsp").forward(request, response);


	}

}

login.jsp ( 登录页面 ) : 

  </head>
  
  <body>
<h1>登录</h1>
${msg }
<form action="${pageContext.request.contextPath }/LoginServlet" method="post">
用户名:<input type="text" name="username">
<input type="submit" value="登录">
</form>
  </body>
</html>

index.jsp :

  </head>
  
  <body>
<h1>你是你奶奶勺子</h1>
<a href="${pageContext.request.contextPath }/index.jsp">游客入口</a><br>
<a href="${pageContext.request.contextPath }/users/u.jsp">会员入口</a><br>
<a href="${pageContext.request.contextPath }/admin/a.jsp">管理员入口</a><br>
  </body>
</html>

a.jsp ( 位于WebRoot文件夹的admin文件夹下,与web.xml中AdminFilter过滤器拦截的URL相对应 ) :

  </head>
  
  <body>
<h1>欢迎死城管理员</h1>
<a href="${pageContext.request.contextPath }/index.jsp">游客入口</a><br>
<a href="${pageContext.request.contextPath }/users/u.jsp">会员入口</a><br>
<a href="${pageContext.request.contextPath }/admin/a.jsp">管理员入口</a><br>
  </body>
</html>

u.jsp ( 位于WebRoot文件夹的users文件夹下,与web.xml中UserFilter过滤器拦截的URL相对应 ) :

  </head>
  
  <body>
<h1>QQ黄钻会员!</h1>
<a href="${pageContext.request.contextPath }/index.jsp">游客入口</a><br>
<a href="${pageContext.request.contextPath }/users/u.jsp">会员入口</a><br>
<a href="${pageContext.request.contextPath }/admin/a.jsp">管理员入口</a><br>
  </body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值