JavaWeb filters and listeners

My website: Welcome to Austria

Filters and Listeners

filter

The role of the filter

Filter filter, developers can implement user before accessing a target resource access requests and responses to intercept. Simply put, it is to be achieved before the web container to access a resource interception related processing can also be intercepted before processing a resource to return a response to the web container;

The preparation steps

Write a class to implement the Filter interface and all interface methods to achieve;

Use annotations configuration or configuration in web.xml [@WebFilter ( "Path Filter")] is not recommended

Implementation process

1. matched filter will go, then a Servlet

2. matched filter will go (web.xml)

Life cycle

Services and destruction with the same Servlet

Born (instantiation and initialization):

The default is instantiated and initialized when the project deployment, the benefits can improve efficiency, Fiter are singletons

Filter chain

That is, a plurality of filters

Note: in the Servlet can not repeat the request, but may be repeated inside the filter, the filter sequentially performed in accordance with the order of about xml configuration

Other configurations of the filter

Filter for a request, a request to perform a filtering

Redirect: repeated requests, multiple times

Forward: a request to perform a

FilterConfig

ServletConfig - get the Servlet initialization parameters

FilterConfig - get Filter initialization parameters

Login achieve interception

Achieve only function behind the login page to access, use filters demo

package com.ifueen.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.HttpServletResponse;

public class LoginFilter implements Filter{

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

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain arg)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
	HttpServletRequest request = (HttpServletRequest) req;
	HttpServletResponse response = (HttpServletResponse) resp;
	Object name = request.getSession().getAttribute("name");
	if (name==null) {
		response.sendRedirect("/index.jsp");
	}
	
	//放行
	arg.doFilter(req, resp);
	
	}

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

web.xml Configuration

<!-- 权限过滤 -->

	<filter>
		<filter-name>login</filter-name>
		<filter-class>com.ifueen.filter.LoginFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>login</filter-name>
		<url-pattern>/system/*</url-pattern>
	</filter-mapping>

Implements a character codec filter

Our tomcat will automatically encode and decode when using get request, but when using the post will not, so we filters to a codec

package com.ifueen.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 EnCodingFilter implements Filter{

	FilterConfig config;	//定义全局的config
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain arg)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		String encoding = config.getInitParameter("encoding");
		req.setCharacterEncoding(encoding);
		resp.setContentType("text/html;charset="+encoding);
		arg.doFilter(req, resp);//执行Servlet代码
		
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		// TODO Auto-generated method stub
		this.config = config;
	}
	
}

web.xml Configuration

<!-- 编码问题过滤 -->
	<filter>
		<filter-name>encoding</filter-name>
		<filter-class>com.ifueen.filter.EnCodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>utf-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

Monitor

Listener object creation and destruction

Create and destroy objects listening ServletContext
the ServletContext object creation and destruction:
Created: server startup, WEB server for each application to create a web project objects belonging to the ServletContext
destruction: Server shut down or remove items from the server when

public class MyServletContextListener implements ServletContextListener{
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("ServletContext对象被创建了...");
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("ServletContext对象被销毁了...");
	}
}

Property change listeners

ServletContextAttributeListener listening to the Context

HttpSessionAttributeListener listening to the Session

ServletRequestAttributeListener listens for requests

Demo

Achieve a statistical number of online listeners

package com.ifueen.listener;

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

public class MyListener implements HttpSessionListener{

	int count = 1000000;
	
	@Override
	public void sessionCreated(HttpSessionEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("开始监听");
		count+=100;
		arg0.getSession().getServletContext().setAttribute("count", count);
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent arg0) {
		// TODO Auto-generated method stub
		count-=100;
		arg0.getSession().getServletContext().setAttribute("count", count);
		System.out.println(count);
	}
	

}

jsp page

<%@ page pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>在线人数</title>
</head>
<body>
	<h2>当前在线人数:<%=application.getAttribute("count")%></h2>
	<input type="button" value="登出" οnclick="location='logout'" />
</body>
</html>

web.xml Configuration

<!-- 监听器的配置 -->
	<listener>
		<listener-class>com.ifueen.listener.MyListener</listener-class>
	</listener>
Published 87 original articles · won praise 7 · views 20000 +

Guess you like

Origin blog.csdn.net/f2315895270/article/details/100084456