JAVAWeb开发之Servlet-19.Filter

–Filter 简介 
–创建Filter的步骤 
–获得Filter的初始化参数 
–Filter 实例
 
?字符编码 Filter 
?权限验证 Filter
###########################################
? Filter 简介 
–Filter位于客户端和请求资源之间,在此起到过滤作用 
–请求资源可以是,Servlet、JSP页面、HTML页面等 
–他们在请求资源的前后来执行 
–请求和响应通过Filter可以被修改 
–Filter 常用在如下几个方面: 
? Session 管理 
? 权限验证 
? 日志记录 
? 字符编码转换
Filter 简介图示
JAVAWeb开发之Servlet-19.Filter
? 创建Filter的步骤
– Filter 接口 
? init 方法 
public void init(FilterConfig filterConfig) throws ServletException 
? doFilter 方法 
public void doFilter(ServletRequest request, 
ServletResponse response, 
FilterChain chain) 
throws java.io.IOException, 
ServletException 
? Destroy 方法 
public void destroy()

– 创建Filter步骤 
? 创建一个类实现Filter接口
 
– 方法: doFilter, init, destroy 
?在doFilter方法中处理逻辑 
– 参数: ServletRequest, ServletResponse, FilterChain 
? FilterChain 调用doFilter方法 
– 调用下一个过滤器或实际资源 
? 注册filter,来过滤Servlet 和Jsp 
–在web.xml中,使用 filter 和 filter-mapping
简单的Filter实例
JAVAWeb开发之Servlet-19.Filter 
调用WebRoot下面的testFilter.html测试Filter起作用了没?
JAVAWeb开发之Servlet-19.Filter Filter没有执行哈~
再次测试admin下的testFilter有没起作用?
JAVAWeb开发之Servlet-19.Filter JAVAWeb开发之Servlet-19.Filter pass herer~~~~~~在控制台打印出来了,但是页面没有显示Test Filter 1,证明被Filter拦截了。下面我们过滤链调用doFilter方法。
JAVAWeb开发之Servlet-19.Filter
再次执行页面。
JAVAWeb开发之Servlet-19.Filter
页面显示了Test Filter 1了
JAVAWeb开发之Servlet-19.Filter
结构与Servlet相似。
MyFilter.java
package com.michael.servlet;    

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 MyFilter implements Filter {    

        public void destroy() {    
        }    

        public void doFilter(ServletRequest arg0, ServletResponse arg1,    
                        FilterChain chain) throws IOException, ServletException {    
                System.out.println("pass here~~~~~~~~");    
                chain.doFilter(arg0, arg1);    
        }    

        public void init(FilterConfig arg0) throws ServletException {    
        }    


web.xml
<?xml version="1.0" encoding="UTF-8"?>    
<web-app version="2.4"    
        xmlns="http://java.sun.com/xml/ns/j2ee"    
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee    
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">    
        <filter>    
                <filter-name>MyFilter</filter-name>    
                <filter-class>com.michael.servlet.MyFilter</filter-class>    
        </filter>    
        <filter-mapping>    
                <filter-name>MyFilter</filter-name>    
                <url-pattern>/admin/*</url-pattern>    
        </filter-mapping>    
</web-app>
testFilter.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">    
<html>    
    <head>    
        <title>testFilter.html</title>    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    
        <meta http-equiv="description" content="this is my page">    
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">    
        <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->    
    </head>    
    <body>    
     <h1>Test Filter 1</h1>    
    </body>    
</html>
? 获得Filter的初始化参数 
–在web.xml配置文件的Filter声明中配置初始化参数
JAVAWeb开发之Servlet-19.Filter
JAVAWeb开发之Servlet-19.Filter
–在Filter实现类中获得初始化参数
JAVAWeb开发之Servlet-19.Filter
 JAVAWeb开发之Servlet-19.Filter
JAVAWeb开发之Servlet-19.Filter 
? Filter 实例 
–字符编码 Filter
JAVAWeb开发之Servlet-19.Filter
JAVAWeb开发之Servlet-19.Filter
测试一下提交的中文是否乱码?
JAVAWeb开发之Servlet-19.Filter
用户名显示为乱码
JAVAWeb开发之Servlet-19.Filter
下面我们将整个页面设置统一编码,用Filter来解决哈~
web.xml
<?xml version="1.0" encoding="UTF-8"?>    
<web-app version="2.4"    
        xmlns="http://java.sun.com/xml/ns/j2ee"    
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee    
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">    
        <filter>    
                <filter-name>MyFilter</filter-name>    
                <filter-class>com.michael.servlet.MyFilter</filter-class>    
                <init-param>    
                        <param-name>encoding</param-name>    
                        <param-value>gbk</param-value>    
                </init-param>    
        </filter>    
        <filter-mapping>    
                <filter-name>MyFilter</filter-name>    
                <url-pattern>/admin/*</url-pattern>    
        </filter-mapping>    
        <filter>    
                <filter-name>EncodingFilter</filter-name>    
                <filter-class>com.michael.servlet.EncodingFilter</filter-class>    
        </filter>    
        <filter-mapping>    
                <filter-name>EncodingFilter</filter-name>    
                <url-pattern>/*</url-pattern>    
        </filter-mapping>    
    <servlet>    
        <servlet-name>RegisterServlet</servlet-name>    
        <servlet-class>com.michael.servlet.RegisterServlet</servlet-class>    
    </servlet>    
    <servlet-mapping>    
        <servlet-name>RegisterServlet</servlet-name>    
        <url-pattern>/servlet/RegisterServlet</url-pattern>    
    </servlet-mapping>    
</web-app> 
register.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">    
<html>    
    <head>    
        <title>register.html</title>    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    
        <meta http-equiv="description" content="this is my page">    
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">    
        <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->    
    </head>    
    <body>    
        <form name="f1" id="f1" action="/Servlet_Filter/servlet/RegisterServlet" method="post">    
            <table border="0">    
                <tr>    
                    <td>Username:</td>    
                    <td><input type="text" name="username" id="login"></td>    
                </tr>    
                <tr>    
                    <td>Password:</td>    
                    <td><input type="password" name="password" id="password"></td>    
                </tr>    
                <tr>    
                    <td colspan="2" align="center"><input type="submit" value="Register"></td>    
                </tr>    
            </table>    
        </form>    
    </body>    
</html>
RegisterServlet.java
package com.michael.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 RegisterServlet extends HttpServlet {    
        /**    
         * Constructor of the object.    
         */
    
        public RegisterServlet() {    
                super();    
        }    
        /**    
         * Destruction of the servlet. <br>    
         */
    
        public void destroy() {    
                super.destroy(); // Just puts "destroy" string in log    
                // Put your code here    
        }    
        /**    
         * The doGet method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to get.    
         *    
         * @param request the request send by the client to the server    
         * @param response the response send by the server to the client    
         * @throws ServletException if an error occurred    
         * @throws IOException if an error occurred    
         */
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)    
                        throws ServletException, IOException {    
                doPost(request,response);    
        }    
        /**    
         * The doPost method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to post.    
         *    
         * @param request the request send by the client to the server    
         * @param response the response send by the server to the client    
         * @throws ServletException if an error occurred    
         * @throws IOException if an error occurred    
         */
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)    
                        throws ServletException, IOException {    
                String username = request.getParameter("username");    
                String password = request.getParameter("password");    
                response.setContentType("text/html");    
                PrintWriter out = response.getWriter();    
                out    
                                .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");    
                out.println("<HTML>");    
                out.println("    <HEAD><TITLE>A Servlet</TITLE></HEAD>");    
                out.println("    <BODY>");    
                out.print(username);    
                out.print(password);    
                out.println("    </BODY>");    
                out.println("</HTML>");    
                out.flush();    
                out.close();    
        }    
        /**    
         * Initialization of the servlet. <br>    
         *    
         * @throws ServletException if an error occurs    
         */
    
        public void init() throws ServletException {    
                // Put your code here    
        }    
}
EncodingFilter.java
package com.michael.servlet;    
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{    
        public void destroy() {    
                // TODO Auto-generated method stub    
        }    
        public void doFilter(ServletRequest request, ServletResponse response,    
                        FilterChain chain) throws IOException, ServletException {    
                request.setCharacterEncoding("gbk");    
                response.setCharacterEncoding("gbk");    
                chain.doFilter(request, response);    
        }    
        public void init(FilterConfig arg0) throws ServletException {    
                // TODO Auto-generated method stub    
        }    
}
可以正常显示中文了哈~
JAVAWeb开发之Servlet-19.Filter 
–权限验证 Filter
web.xml
<?xml version="1.0" encoding="UTF-8"?>    
<web-app version="2.4"    
        xmlns="http://java.sun.com/xml/ns/j2ee"    
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee    
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">    
        <filter>    
                <filter-name>MyFilter</filter-name>    
                <filter-class>com.michael.servlet.MyFilter</filter-class>    
                <init-param>    
                        <param-name>encoding</param-name>    
                        <param-value>gbk</param-value>    
                </init-param>    
        </filter>    
        <filter-mapping>    
                <filter-name>MyFilter</filter-name>    
                <url-pattern>/admin/*</url-pattern>    
        </filter-mapping>    
        <filter>    
                <filter-name>EncodingFilter</filter-name>    
                <filter-class>com.michael.servlet.EncodingFilter</filter-class>    
        </filter>    
        <filter-mapping>    
                <filter-name>EncodingFilter</filter-name>    
                <url-pattern>/*</url-pattern>    
        </filter-mapping>    
        <filter>    
                <filter-name>SessionFilter</filter-name>    
                <filter-class>com.michael.servlet.SessionFilter</filter-class>    
        </filter>    
        <filter-mapping>    
                <filter-name>SessionFilter</filter-name>    
                <url-pattern>/admin/*</url-pattern>    
        </filter-mapping>    
    <servlet>    
        <servlet-name>RegisterServlet</servlet-name>    
        <servlet-class>com.michael.servlet.RegisterServlet</servlet-class>    
    </servlet>    
    <servlet>    
        <servlet-name>LoginServlet</servlet-name>    
        <servlet-class>com.michael.servlet.LoginServlet</servlet-class>    
    </servlet>    
    <servlet-mapping>    
        <servlet-name>RegisterServlet</servlet-name>    
        <url-pattern>/servlet/RegisterServlet</url-pattern>    
    </servlet-mapping>    
    <servlet-mapping>    
        <servlet-name>LoginServlet</servlet-name>    
        <url-pattern>/servlet/LoginServlet</url-pattern>    
    </servlet-mapping>    
</web-app>
login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>    
<%    
String path = request.getContextPath();    
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";    
%>    
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">    
<html>    
    <head>    
        <base href="<%=basePath%>">    
        <title>My JSP 'login.jsp' starting page</title>    
        <meta http-equiv="pragma" content="no-cache">    
        <meta http-equiv="cache-control" content="no-cache">    
        <meta http-equiv="expires" content="0">         
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    
        <meta http-equiv="description" content="This is my page">    
        <!--    
        <link rel="stylesheet" type="text/css" href="styles.css">    
        -->    
    </head>    
    <body>    
        ${Login_Error }    
        <form name="f1" id="f1" action="/Servlet_Filter/servlet/LoginServlet" method="post">    
            <table border="0">    
                <tr>    
                    <td>Username:</td>    
                    <td><input type="text" name="username" id="login"></td>    
                </tr>    
                <tr>    
                    <td>Password:</td>    
                    <td><input type="password" name="password" id="password"></td>    
                </tr>    
                <tr>    
                    <td colspan="2" align="center"><input type="submit" value="Login"></td>    
                </tr>    
            </table>    
        </form>    
    </body>    
</html>
LoginServlet.java
package com.michael.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;    
import javax.servlet.http.HttpSession;    
public class LoginServlet extends HttpServlet {    
        /**    
         * Constructor of the object.    
         */
    
        public LoginServlet() {    
                super();    
        }    
        /**    
         * Destruction of the servlet. <br>    
         */
    
        public void destroy() {    
                super.destroy(); // Just puts "destroy" string in log    
                // Put your code here    
        }    
        /**    
         * The doGet method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to get.    
         *    
         * @param request the request send by the client to the server    
         * @param response the response send by the server to the client    
         * @throws ServletException if an error occurred    
         * @throws IOException if an error occurred    
         */
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)    
                        throws ServletException, IOException {    
                doPost(request,response);    
        }    
        /**    
         * The doPost method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to post.    
         *    
         * @param request the request send by the client to the server    
         * @param response the response send by the server to the client    
         * @throws ServletException if an error occurred    
         * @throws IOException if an error occurred    
         */
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)    
                        throws ServletException, IOException {    
                HttpSession session = request.getSession();    
                session.setAttribute("UserSession""user");    
                response.setContentType("text/html");    
                PrintWriter out = response.getWriter();    
                out    
                                .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");    
                out.println("<HTML>");    
                out.println("    <HEAD><TITLE>A Servlet</TITLE></HEAD>");    
                out.println("    <BODY>");    
                out.print("        Welcome you! ");    
                out.println("    </BODY>");    
                out.println("</HTML>");    
                out.flush();    
                out.close();    
        }    
        /**    
         * Initialization of the servlet. <br>    
         *    
         * @throws ServletException if an error occurs    
         */
    
        public void init() throws ServletException {    
                // Put your code here    
        }    
}
SessionFilter.java
package com.michael.servlet;    
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;    
import javax.servlet.http.HttpSession;    
public class SessionFilter implements Filter {    
        public void destroy() {    
                // TODO Auto-generated method stub    
        }    
        public void doFilter(ServletRequest request, ServletResponse response,    
                        FilterChain chain) throws IOException, ServletException {    
                HttpServletRequest hrequest = (HttpServletRequest)request;    
                HttpServletResponse hresponse = (HttpServletResponse)response;    
                HttpSession session = hrequest.getSession();    
                String session_Value = (String)session.getAttribute("UserSession");    
                if(session_Value!=null&&session_Value.length()>=0){    
                        chain.doFilter(request, response);    
                }else{    
                        hrequest.setAttribute("Login_Error""请登录");    
                        hrequest.getRequestDispatcher("/login.jsp").forward(hrequest, hresponse);    
                }    
        }    
        public void init(FilterConfig arg0) throws ServletException {    
                // TODO Auto-generated method stub    
        }    
}
没有登录的状态下直接访问admin目录下的testFilter.thml页面,页面显示“请登录”。
JAVAWeb开发之Servlet-19.Filter
下面我们输入用户名和密码进行模拟登录验证。
JAVAWeb开发之Servlet-19.Filter
页面显示登录成功!
JAVAWeb开发之Servlet-19.Filter
登录成功后我们再访问admin目录下的页面就可以正常访问了哈~
JAVAWeb开发之Servlet-19.Filter
#################################################





本文转自redking51CTO博客,原文链接:http://blog.51cto.com/redking/284703,如需转载请自行联系原作者
上一篇:SQL中删除重复数据问题


下一篇:freemarker如何获取当前时间或者时间戳?