JSP之应用Servlet过滤器进行身份验证,jsp实现过滤器
分类:web前端

红色标记为关键代码.由于工程太大,我在这里只放有XML文件、JSP文件、过滤器
具体内容用论坛回复。 顺序为:JSP文件---过滤器---XML文件.

Filter是从Servlet2.3规范开始新增的功能,并在Servlet2.4规范中得到增强,接下来让我们一起来看看Filter的真实面目吧。

1、Servlet过滤器的作用描述
(1)在HttpServletRequest到达Servlet 之前,拦截客户的HttpServletRequest。
根据需要检查HttpServletRequest,也可以修改HttpServletRequest头和数据。
(2)在HttpServletResponse 到达客户端之前,拦截HttpServletResponse。
根据需要检查HttpServletResponse,可以修改HttpServletResponse头和数据。

java-Filter

 <%@ page contentType="text/html; charset=GBK" %>
<%@ taglib uri="" prefix="c" %>
<%
Object str= request.getAttribute("user");
pageContext.setAttribute("user",str);
%>
<html>
<head>
<title>

一. 概念

2、应用Servlet过滤器进行身份验证

过滤器是小型的Web组件,它们负责拦截请求以及响应,以便查看、提取或以某种方式操作正在客户机和服务器之间交换的数据。简单的说,过滤器就类似于客户端发送的web请求与服务器之间的防火墙,经过该防火墙验明正身后放可以传入后天进行进一步的数据请求。

过滤器

    过滤器就是在源数据和目的数据之间起过滤作用的中间组件。对Web应用来说,过滤器是一个驻留在服务器端的Web组件,它可以截取客户端和资源之间的请求与响应信息,并对这些信息进行过滤。

假设网站根目录下的login1.htm、longin1.jsp用于用户登录,而chap08目录下的文件需要用户登录后才能访问。

 

 </title>
</head>
<body bgcolor="#ffffff">
<h1>

 

(1)编写Servlet过滤器

过滤器其实是一个Java的类,然后实现了几个函数,创建filter文件的时候,创建Class文件即可,参考代码如下所示:

准备过滤

二. 执行流程

@WebFilter("/FilterStation")
public class FilterStation extends HttpServlet implements Filter {
private FilterConfig filterConfig;
public FilterStation() {
super();
}

package common;

 </h1>
<h1>${pageScope.user}</h1>
<form method="post" action="Example1.jsp">
<br>
 <input type="text" name="user" />
 <br>
<input type="submit" name="Submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>

    当Web容器接受到一个对资源的请求时,它就会判断是否有过滤器与这个资源相关联(这是一个自动的过程)。如果有,那么容器将把请求交给过滤器进行处理。在过滤器中,你可以改变请求的内容,或者重新设置请求的报头信息,然后再将请求发送给目标资源。当目标资源对请求作出响应时候,容器同样会将响应先转发给过滤器,再过滤器中,你可以对响应的内容进行转换,然后再将响应发送到客户端.。

public void destroy() {
}

  

文字

    如果有多个过滤器,则它会像一个链(根据web.xml中的位置)一样执行。

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpSession session=((HttpServletRequest)request).getSession();
response.setCharacterEncoding("gb2312");
if(session.getAttribute("me")==null){
PrintWriter out=response.getWriter();
out.print("<script>alert('请登录!');location.href='../login1.htm'</script>");
}
else{
// pass the request along the filter chain
chain.doFilter(request, response);
}
}

import java.io.IOException;  

 <%@ page contentType="text/html; charset=GBK" %>
<%@ taglib uri="" prefix="c" %>
<%
Object str= request.getAttribute("user");
pageContext.setAttribute("user",str);
%>
<html>
<head>
<title>
过滤器
</title>
</head>
<body bgcolor="#ffffff">
<h1>
准备过滤
package com.lgx.filtertext.dao;

    我们先看一个图:

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

import javax.servlet.Filter;  

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

 图片 1

}

import javax.servlet.FilterChain;  

public class Filter1 extends HttpServlet implements Filter {
   private FilterConfig filterConfig;
   //Handle the passed-in FilterConfig
   public void init(FilterConfig filterConfig) throws ServletException {
       this.filterConfig = filterConfig;
   }

 

(2)配置web.xml

import javax.servlet.FilterConfig;  

   //Process the request/response pair
   public void doFilter(ServletRequest request, ServletResponse response,
                        FilterChain filterChain) {
       String[] strUser = {"江泽民同志", "胡锦涛同志", "奶奶的", "我拷", "他XX的"};
       String str = "";

三. 实例及解析

<filter>
<filter-name>filterstation</filter-name>
<filter-class>zhou.FilterStation</filter-class>
</filter>

import javax.servlet.ServletException;  

       try {
           request.setCharacterEncoding("GBK");
           HttpServletRequest hsrq = (HttpServletRequest) request;
           String user = hsrq.getParameter("user");

    我们来看一个登录的例子,它需要用到两个过滤器,一个是转换编码格式,一个是判断是否登录。

<filter-mapping>
<filter-name>filterstation</filter-name>
<url-pattern>/chap08/*</url-pattern>
</filter-mapping>

import javax.servlet.ServletRequest;  

           if (user == null || user.equals("")) {

    先看一下这个例子的时序图:

(3)login1.htm代码

import javax.servlet.ServletResponse;  

           } else {
               StringBuffer sb = new StringBuffer(user);
               for (int i = 0; i < strUser.length; i++) {
                   str = strUser[i];
                   if (sb.indexOf(str) == -1) {
                       hsrq.setAttribute("user", sb.toString());
                   } else {
                       sb.replace(sb.indexOf(str), sb.indexOf(str) + 3, "xxx");
                       hsrq.setAttribute("user", sb.toString());
                   }

 图片 2

<html>
<head>
<title>用户登录</title>
</head>
<body>
<form method="POST" action="login1.jsp">
<p>用户名:<input type="text" name="user" size="18"></p>
<p>密码:<input type="text" name="pass" size="20"></p>
<p><input type="submit" value="提交" name="ok">
<input type="reset" value="重置" name="cancel"></p>
</form>
</body>
</html>

publicclass filter implements Filter 

               }
           }
           filterChain.doFilter(request, response);
       } catch (ServletException sx) {
           filterConfig.getServletContext().log(sx.getMessage());
       } catch (IOException iox) {
           filterConfig.getServletContext().log(iox.getMessage());
       }
   }

 

(4)login1.jsp代码

{  

   //Clean up resources
   public void destroy() {
   }
}  

接下来我们看一下源码:

<%@ page contentType="text/html;charset=GB2312" %>
<html>
<head><title>Session 应用演示</title></head>
<%
if (request.getParameter("user")!=null && request.getParameter("pass")!=null)
{
String strName=request.getParameter("user");
String strPass=request.getParameter("pass");
if (strName.equals("admin") && strPass.equals("admin"))
{
session.setAttribute("login","OK");
session.setAttribute("me",strName);
response.sendRedirect("chap08/welcome.jsp");

    private FilterConfig filterConfig;  

注:此“XML”代码是在运行时出现的,

   login.jsp

}
else
{
out.print("<script>alert('用户名或密码错误');location.href='login1.htm'</script>");
}
}
%>
</html>

  

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="" xmlns:xsi="" xsi:schemaLocation=" " version="2.4">
 <display-name>Web</display-name>
 <filter>
   <filter-name>filter1</filter-name>
   <filter-class>com.lgx.filtertext.dao.Filter1</filter-class>
 </filter>
 <filter-mapping>
   <filter-name>filter1</filter-name>
   <url-pattern>/*</url-pattern>
 </filter-mapping>
 <servlet>
   <description>Added by JBuilder to compile JSPs with debug info</description>
   <servlet-name>debugjsp</servlet-name>
   <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
   <init-param>
     <param-name>classdebuginfo</param-name>
     <param-value>true</param-value>
   </init-param>
   <load-on-startup>3</load-on-startup>
 </servlet>
 <servlet-mapping>
   <servlet-name>debugjsp</servlet-name>
   <url-pattern>*.jsp</url-pattern>
 </servlet-mapping>
</web-app>

[java] <pre class="java" name="code"><%@ page language="java" contentType="text/html; charset=GB18030" 
    pageEncoding="GB18030"%> 
<% 
    String command = request.getParameter("command"); 
    if ("login".equals(command)) { 
        if ("dan".equals(request.getParameter("userId")) 
                && "123".equals(request.getParameter("password"))) { 
 
            //登陆成功将用户信息放到session中  
            session.setAttribute("user_name", 
                    request.getParameter("userId")); 
 
            //设置超时,单位:秒  
            session.setMaxInactiveInterval(6000); 
 
            //重定向到主控页面  
            response.sendRedirect(request.getContextPath() + "/main.jsp"); 
        } 
    } 
%> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=GB18030"> 
<title>登录</title> 
<SCRIPT language=JavaScript> 
    function init() { 
        loginForm.userId.focus(); 
    } 
 
</SCRIPT> 
</head> 
<body onload=init()> 
    <FORM name="loginForm"> 
        <input type="hidden" name="command" value="login">     
        用户名:   
        <INPUT name="userId" value="dan" type="text" size="20"   maxlength="20">  
        密   码:  
        <INPUT name="password"   value="123" type="password" size="21" maxlength="20">  
        <input type="submit" onclick="submitForm()" value="提交" name="login" id="login"> 
    </FORM> 
</body> 
</html> 
<pre class="java" name="code"><%@ page language="java" contentType="text/html; charset=GB18030"
 pageEncoding="GB18030"%>
<%
 String command = request.getParameter("command");
 if ("login".equals(command)) {
  if ("dan".equals(request.getParameter("userId"))
    && "123".equals(request.getParameter("password"))) {

注意:从Servlet3.0开始,配置Servlet除了通过在web.xml文件中进行配置,还可以通过使用@WebServlet注解进行配置。同样的,配置Filter也可以通过@WebFilter注解方式进行。

    public void doFilter(ServletRequest request, ServletResponse response,  

注:这一处代码是配置过滤器的,不过JBuilder2005里面Tomcat容器已自动配置

   //登陆成功将用户信息放到session中
   session.setAttribute("user_name",
     request.getParameter("userId"));

@WebFilter(filterName="/FilterStation",urlPatterns={"/welcome.jsp","/a.jsp"})
public class FilterStation implements Filter {

            FilterChain chain) throws IOException, ServletException 

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="" xmlns:xsi="" xsi:schemaLocation=" " version="2.4">
 <display-name>Web</display-name>
 <filter>
   <filter-name>filter1</filter-name>
   <filter-class>com.lgx.filtertext.dao.Filter1</filter-class>
 </filter>
 <filter-mapping>
   <filter-name>filter1</filter-name>
   <url-pattern>/*</url-pattern>
 </filter-mapping>
</web-app>

   //设置超时,单位:秒
   session.setMaxInactiveInterval(6000);

  ----

      {  

   //重定向到主控页面
   response.sendRedirect(request.getContextPath() + "/main.jsp");
  }
 }
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>登录</title>
<SCRIPT language=JavaScript>
 function init() {
  loginForm.userId.focus();
 }

}

  /*

</SCRIPT>
</head>
<body onload=init()>
 <FORM name="loginForm">
  <input type="hidden" name="command" value="login"> 
  用户名: 
  <INPUT name="userId" value="dan" type="text" size="20" maxlength="20">
  密   码:
  <INPUT name="password" value="123" type="password" size="21" maxlength="20">
  <input type="submit" onclick="submitForm()" value="提交" name="login" id="login">
 </FORM>
</body>
</html>

 

  再这里读取参数,并进行响应的过滤操作

   CharsetEncodingFilter.java

  */

[java] package 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 CharsetEncodingFilter implements Filter { 
 
    private String encoding; 
     
    @Override 
    public void destroy() { 
         
    } 
 
    @Override 
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, 
            FilterChain filterChain) throws IOException, ServletException { 
        //设置字符集  
        servletRequest.setCharacterEncoding(encoding); 
        filterChain.doFilter(servletRequest, servletResponse); 
         
    } 
 
    @Override 
    public void init(FilterConfig filterConfig) throws ServletException { 
        //取得初始化参数  
        this.encoding = filterConfig.getInitParameter("encoding"); 
    } 
 

package filter;

        chain.doFilter(request, response);//放行。让其走到下个链或目标资源中  

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

    public void init(FilterConfig filterConfig) throws ServletException {  

 private String encoding;
 
 @Override
 public void destroy() {
  
 }

        System.out.println("初始化了");  

 @Override
 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
   FilterChain filterChain) throws IOException, ServletException {
  //设置字符集
  servletRequest.setCharacterEncoding(encoding);
  filterChain.doFilter(servletRequest, servletResponse);
  
 }

        this.filterConfig = filterConfig;  

 @Override
 public void init(FilterConfig filterConfig) throws ServletException {
  //取得初始化参数
  this.encoding = filterConfig.getInitParameter("encoding");
 }

    }  

}
 
   AuthFilter.java

  

[java] package 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; 
import javax.servlet.http.HttpSession; 
 
public class AuthFilter implements Filter { 
 
    public void destroy() { } 
 
    public void doFilter(ServletRequest request, ServletResponse response, 
            FilterChain chain) throws IOException, ServletException { 
        HttpServletRequest req = (HttpServletRequest) request; 
        HttpServletResponse res = (HttpServletResponse) response; 
        String requestURI = req.getRequestURI().substring( 
                req.getRequestURI().indexOf("/", 1), 
                req.getRequestURI().length()); 
        if (!"/login.jsp".equals(requestURI)) { 
            HttpSession session = req.getSession(false); 
            if (session == null || session.getAttribute("user_name") == null) { 
                res.sendRedirect(req.getContextPath() + "/login.jsp"); 
                return; 
            } 
        } 
        // 继续访问其他资源  
        chain.doFilter(req, res); 
    } 
 
    public void init(FilterConfig filterConfig) throws ServletException {} 
 

package filter;

    public void destroy() {  

import java.io.IOException;

        System.out.println("销毁了");  

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

 public void destroy() { }

 

 public void doFilter(ServletRequest request, ServletResponse response,
   FilterChain chain) throws IOException, ServletException {
  HttpServletRequest req = (HttpServletRequest) request;
  HttpServletResponse res = (HttpServletResponse) response;
  String requestURI = req.getRequestURI().substring(
    req.getRequestURI().indexOf("/", 1),
    req.getRequestURI().length());
  if (!"/login.jsp".equals(requestURI)) {
   HttpSession session = req.getSession(false);
   if (session == null || session.getAttribute("user_name") == null) {
    res.sendRedirect(req.getContextPath() + "/login.jsp");
    return;
   }
  }
  // 继续访问其他资源
  chain.doFilter(req, res);
 }

Filter可以过滤某一个Servlet或者JSP文件,或者顾虑一组Servlet或者JSP文件,这些功能是在web.XML文件中进行配置。

 public void init(FilterConfig filterConfig) throws ServletException {}

web.xml参考代码:

}  

<?xmlversion="1.0"encoding="UTF-8"?>

Web.xml

<web-appversion="2.5" 

  

xmlns="" 

[html] <?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns:xsi="" xmlns="" xmlns:javaee="" xmlns:web="" xsi:schemaLocation=" " version="2.4"> 
     
  <filter> 
    <filter-name>CharsetEncodingFilter</filter-name> 
    <filter-class>filter.CharsetEncodingFilter</filter-class> 
    <init-param> 
      <param-name>encoding</param-name> 
      <param-value>GB18030</param-value> 
    </init-param> 
  </filter> 
  <filter-mapping> 
    <filter-name>CharsetEncodingFilter</filter-name> 
    <url-pattern>*.jsp</url-pattern> 
  </filter-mapping> 
  <filter-mapping> 
    <filter-name>CharsetEncodingFilter</filter-name> 
    <url-pattern>/servlet/*</url-pattern> 
  </filter-mapping> 
   
  <filter> 
    <filter-name>AuthFilter</filter-name> 
    <filter-class>filter.AuthFilter</filter-class> 
  </filter> 
  <filter-mapping> 
    <filter-name>AuthFilter</filter-name> 
    <url-pattern>*.jsp</url-pattern> 
  </filter-mapping> 
   
  <filter-mapping> 
    <filter-name>AuthFilter</filter-name> 
    <url-pattern>/servlet/*</url-pattern> 
  </filter-mapping> 
     
</web-app> 
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xmlns:javaee="" xmlns:web="" xsi:schemaLocation=" " version="2.4">
   
  <filter>
    <filter-name>CharsetEncodingFilter</filter-name>
    <filter-class>filter.CharsetEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>GB18030</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharsetEncodingFilter</filter-name>
    <url-pattern>*.jsp</url-pattern>
  </filter-mapping>
  <filter-mapping>
   <filter-name>CharsetEncodingFilter</filter-name>
   <url-pattern>/servlet/*</url-pattern>
  </filter-mapping>
 
  <filter>
   <filter-name>AuthFilter</filter-name>
   <filter-class>filter.AuthFilter</filter-class>
  </filter>
  <filter-mapping>
   <filter-name>AuthFilter</filter-name>
   <url-pattern>*.jsp</url-pattern>
  </filter-mapping>
 
  <filter-mapping>
   <filter-name>AuthFilter</filter-name>
   <url-pattern>/servlet/*</url-pattern>
  </filter-mapping>
   
</web-app>

xmlns:xsi="" 

Filter中主要有三个方法init(),doFilter(),destroy()

xsi:schemaLocation=" 

  1.init(FilterConfigfilterConfig)    

;

    Web容器调用该方法该方法来初始化过滤器。容器在调用该方法时,向过滤器传递

  <display-name></display-name>

FilterConfig对象,利用FilterConfig对象可以得到ServletContext对象,以及部署描述符中配置的过滤器的初始化参数。图片 3

  

 

<filter>  

从图中可以看出来Listener,Filter,Servlet及Tomcat的一个启动顺序。

    <filter-name>filter</filter-name>  

    2.doFilter(ServletRequestrequest, ServletResponse response,FilterChain chain)

    <filter-class>common.filter</filter-class>  

    这是Filter的主要方法,其中的request和response和servlet里的参数一样,至于chain是用于后面对请求的转发的,该参数的chain.doFilter方法是一种回调过程。

    <init-param>  

    该方法以chain.doFilter()为界限,先执行前面的代码,然后执行chain.doFilter()方法来将请求传递给下一个Filter(如果没有Filter了就传递给Servlet),等到这条链执行完后,再往回执行后面的代码,它是使用回调来实现的。   

        <param-name>param1</param-name>  

     大家可以通过下面的图来进行理解:

        <param-value>value在这里呢</param-value>  

 图片 4

    </init-param>  

 

</filter>  

3.destroy()

 

     这个方法servlet的destroy()方法一样,都是当服务器断开的时候才执行该销毁方法,Filter也是实例化一次,多次调用。

<filter-mapping>  

 

    <filter-name>filter</filter-name>  

摘自 赵丹丹的专栏

    <url-pattern>/ms/*</url-pattern>

 // <servlet-name></servlet-name>

    <dispatcher>REQUEST</dispatcher><!-- 没有配置dispatcher就是默认request方式的 -->  

    <dispatcher>FORWARD</dispatcher>  

    <dispatcher>ERROR</dispatcher>  

    <dispatcher>INCLUDE</dispatcher>  

</filter-mapping>  

  

  

  

  <servlet>

    <description>This is the description of my J2EE component</description>

    <display-name>This is the display name of my J2EE component</display-name>

    <servlet-name>myservlet</servlet-name>

    <servlet-class>myservlet</servlet-class>

  </servlet>

  <servlet>

    <description>This is the description of my J2EE component</description>

    <display-name>This is the display name of my J2EE component</display-name>

    <servlet-name>SecondServlet</servlet-name>

    <servlet-class>SecondServlet</servlet-class>

  </servlet>

  <servlet-mapping>

    <servlet-name>myservlet</servlet-name>

    <url-pattern>/ms/one/myservlet</url-pattern>

  </servlet-mapping>

  <servlet-mapping>

    <servlet-name>SecondServlet</servlet-name>

    <url-pattern>/ms/tow/SecondServlet</url-pattern>

  </servlet-mapping>

 

  <welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>

</web-app>


再<filter-mapping> 映射节点中,如果我们对某一个Servlet文件进行过滤,可以设置

<servlet-name>TargetFilterServletFileName</servlet>

TargetFilterServletFileName表示将要进行过滤的Servlet文件,

如果要对一组文件记性过滤,可以设置
<url-pattern>/FilePath</url-pattern>其中*表示上一级路径下的所有文件,

比如:/mm/servletForder/* 表示对/mm/servletForder/之后的所有文件进行过滤,

 

再web.xml配置文件中,需要注意的一点是:如果使用过滤文件,那么Filter的配置必须放到 <servlet>节点之前

 

 

Jason

2014年05月11日

本文由10bet手机官网发布于web前端,转载请注明出处:JSP之应用Servlet过滤器进行身份验证,jsp实现过滤器

上一篇:JSP和Oracle数据库连接问题集锦,解析jdbc处理oracle的clob字段的详解 下一篇:jsp另外五大内置对象之response
猜你喜欢
热门排行
精彩图文