`

Filter

    博客分类:
  • web
 
阅读更多
package com.demo.Filter;

import java.io.IOException;

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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class LogFilter implements Filter {

	private FilterConfig config;

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		ServletContext context = this.config.getServletContext();
		System.out.println("读取XML配置参数:" + config.getInitParameter("user"));
		HttpServletRequest hrequest = (HttpServletRequest) request;
		context.log("截获用户请求地址:" + hrequest.getServletPath());
		context.log("截获用户IP地址:" + hrequest.getRemoteAddr() + ":"
				+ hrequest.getRemotePort());
		request.getRequestDispatcher("result.jsp").forward(request, response);
		// chain.doFilter(request, response);
	}

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

	public void destroy() {
		// TODO Auto-generated method stub
		this.config = null;
	}
}

<?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">
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<filter>
		<filter-name>logFilter</filter-name>
		<filter-class>com.demo.Filter.LogFilter</filter-class>
		<init-param>
			<param-name>user</param-name>
			<param-value>admin</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>logFilter</filter-name>
		<url-pattern>/logFilter</url-pattern>
	</filter-mapping>
</web-app>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics