吴裕雄--天生自然轻量级JAVA EE企业应用开发Struts2Sping4Hibernate整合开发学习笔记:Filter介绍

<%--
网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
author  yeeku.H.lee kongyeeku@163.com
version  1.0
Copyright (C), 2001-2016, yeeku.H.Lee
This program is protected by copyright laws.
Program Name:
Date: 
--%>

<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Filter测试</title>
    <meta name="website" content="http://www.crazyit.org" />
</head>
<body>
<h2>Filter页面</h2>
</body>
</html>
<%--
网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
author  yeeku.H.lee kongyeeku@163.com
version  1.0
Copyright (C), 2001-2016, yeeku.H.Lee
This program is protected by copyright laws.
Program Name:
Date: 
--%>

<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>登录页面</title>
    <meta name="website" content="http://www.crazyit.org" />
</head>
<body>
<h2>登录页面</h2>
<%
if(request.getAttribute("tip") != null)
{
    out.println("<font color='red'>" 
        + request.getAttribute("tip")
        + "</font>");
}
%>
<form method="post" action="proLogin.jsp">
用户名:<input type="text" name="name"/><br/>
<input type="submit" value="登录"/>
</form>
</body>
</html>
<%--
网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
author  yeeku.H.lee kongyeeku@163.com
version  1.0
Copyright (C), 2001-2016, yeeku.H.Lee
This program is protected by copyright laws.
Program Name:
Date: 
--%>

<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title> 登录页面 </title>
    <meta name="website" content="http://www.crazyit.org" />
</head>
<body>
<h2>登录页面</h2>
<%
session.setAttribute("user" 
    , request.getParameter("name"));
%>
登录成功,可以访问该应用的其他页面
</body>
</html>
<?xml version="1.0" encoding="GBK"?>
<!-- 定义生成文件的project根元素,默认的target为空 -->
<project name="web" basedir="." default="">
    <!-- 定义三个简单属性 -->
    <property name="src" value="src"/>
    <property name="classes" value="classes"/>
    <!-- 定义一组文件和目录集 -->
    <path id="classpath">
        <fileset dir="lib">
            <include name="**/*.jar"/>
        </fileset>
        <pathelement path="${classes}"/>
    </path>
    <!-- 定义compile target,用于编译Java源文件 -->
    <target name="compile" description="编译Java源文件">
        <!-- 先删除classes属性所代表的文件夹 -->
        <delete dir="${classes}"/>
        <!-- 创建classes属性所代表的文件夹 -->
        <mkdir dir="${classes}"/>
        <copy todir="${classes}">
            <fileset dir="${src}">
                <exclude name="**/*.java"/>
            </fileset>
        </copy>
        <!-- 编译Java文件,编译后的class文件放到classes属性所代表的文件夹内 -->
        <javac destdir="${classes}" debug="true" includeantruntime="yes"
            deprecation="false" optimize="false" failonerror="true">
            <!-- 指定需要编译的Java文件所在的位置 -->
            <src path="${src}"/>
            <!-- 指定编译Java文件所需要第三方类库所在的位置 -->
            <classpath refid="classpath"/>
        </javac>
    </target>
</project>
<?xml version="1.0" encoding="GBK"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
    http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">


    <!-- 定义Filter -->
    <filter>
        <!-- Filter的名字,相当于指定@WebFilter
            的filterName属性 -->
        <filter-name>log</filter-name>
        <!-- Filter的实现类 -->
        <filter-class>lee.LogFilter</filter-class> 
    </filter>
    <!-- 定义Filter拦截的URL地址 -->
    <filter-mapping>
        <!-- Filter的名字 -->
        <filter-name>log</filter-name>
        <!-- Filter负责拦截的URL,相当于指定@WebFilter
            的urlPatterns属性 -->
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 定义Filter -->
    <filter>
        <!-- Filter的名字 -->
        <filter-name>authority</filter-name>
        <!-- Filter的实现类 -->
        <filter-class>lee.AuthorityFilter</filter-class>
        <!-- 下面三个init-param元素配置了三个参数 -->
        <init-param>
            <param-name>encoding</param-name>
            <param-value>GBK</param-value>
        </init-param>
        <init-param>
            <param-name>loginPage</param-name>
            <param-value>/login.jsp</param-value>
        </init-param>
        <init-param>
            <param-name>proLogin</param-name>
            <param-value>/proLogin.jsp</param-value>
        </init-param>
    </filter>
    <!-- 定义Filter拦截的URL地址 -->
    <filter-mapping>
        <!-- Filter的名字 -->
        <filter-name>authority</filter-name>
        <!-- Filter负责拦截的URL -->
        <url-pattern>/*</url-pattern>
    </filter-mapping>


</web-app>
package lee;

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

import java.io.*;
/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee kongyeeku@163.com
 * @version  1.0
 */
@WebFilter(filterName="authority"
    , urlPatterns={"/*"}
    , initParams={
        @WebInitParam(name="encoding", value="GBK"),
        @WebInitParam(name="loginPage", value="/login.jsp"),
        @WebInitParam(name="proLogin", value="/proLogin.jsp")})
public class AuthorityFilter implements Filter
{
    // FilterConfig可用于访问Filter的配置信息
    private FilterConfig config;
    // 实现初始化方法
    public void init(FilterConfig config)
    {
        this.config = config;
    }
    // 实现销毁方法
    public void destroy()
    {
        this.config = null;
    }
    // 执行过滤的核心方法
    public void doFilter(ServletRequest request,
        ServletResponse response, FilterChain chain)
        throws IOException,ServletException
    {
        // 获取该Filter的配置参数
        String encoding = config.getInitParameter("encoding");
        String loginPage = config.getInitParameter("loginPage");
        String proLogin = config.getInitParameter("proLogin");
        // 设置request编码用的字符集
        request.setCharacterEncoding(encoding);            //
        HttpServletRequest requ = (HttpServletRequest)request;
        HttpSession session = requ.getSession(true);
        // 获取客户请求的页面
        String requestPath = requ.getServletPath();
        // 如果session范围的user为null,即表明没有登录
        // 且用户请求的既不是登录页面,也不是处理登录的页面
        if( session.getAttribute("user") == null
            && !requestPath.endsWith(loginPage)
            && !requestPath.endsWith(proLogin))
        {
            // forward到登录页面
            request.setAttribute("tip" , "您还没有登录");
            request.getRequestDispatcher(loginPage)
                .forward(request, response);
        }
        // "放行"请求
        else
        {
            chain.doFilter(request, response);
        }
    }
}
package lee;

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

import java.io.*;

/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee kongyeeku@163.com
 * @version  1.0
 */

@WebFilter(filterName="log"
    ,urlPatterns={"/*"})
public class LogFilter implements Filter
{
    // FilterConfig可用于访问Filter的配置信息
    private FilterConfig config;
    // 实现初始化方法
    public void init(FilterConfig config)
    {
        this.config = config;
    }
    // 实现销毁方法
    public void destroy()
    {
        this.config = null;
    }
    // 执行过滤的核心方法
    public void doFilter(ServletRequest request,
        ServletResponse response, FilterChain chain)
        throws IOException,ServletException
    {
        // ---------下面代码用于对用户请求执行预处理---------
        // 获取ServletContext对象,用于记录日志
        ServletContext context = this.config.getServletContext();
        long before = System.currentTimeMillis();
        System.out.println("开始过滤...");
        // 将请求转换成HttpServletRequest请求
        HttpServletRequest hrequest = (HttpServletRequest)request;
        // 输出提示信息
        System.out.println("Filter已经截获到用户的请求的地址: " +
            hrequest.getServletPath());
        // Filter只是链式处理,请求依然放行到目的地址
        chain.doFilter(request, response);
        // ---------下面代码用于对服务器响应执行后处理---------
        long after = System.currentTimeMillis();
        // 输出提示信息
        System.out.println("过滤结束");
        // 输出提示信息
        System.out.println("请求被定位到" + hrequest.getRequestURI() +
            "   所花的时间为: " + (after - before));
    }
}
原文地址:https://www.cnblogs.com/tszr/p/12364005.html