欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java Web过滤器详解

程序员文章站 2024-02-25 20:09:15
过滤器是什么玩意? 所谓过滤器,其实就是一个服务端组件,用来截取用户端的请求与响应信息。 过滤器的应用场景: 1.对用户请求进行统一认证,保证不会出现用户账户安全性问...

过滤器是什么玩意?

所谓过滤器,其实就是一个服务端组件,用来截取用户端的请求与响应信息。

过滤器的应用场景:
1.对用户请求进行统一认证,保证不会出现用户账户安全性问题

2.编码转换,可在服务端的过滤器中设置统一的编码格式,避免出现乱码

3.对用户发送的数据进行过滤替换

4.转换图像格式

5.对响应的内容进行压缩

其中,第1,2场景经常涉及。

Java Web过滤器详解

login.jsp

<%@ page language="java" import="java.util.*" contenttype="text/html; charset=utf-8"%>
<%
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>
 <form action="<%=path %>/servlet/loginservlet" method="post" >
  用户名:<input type="text" name="username" />
 密码:<input type="password" name="password" />
 <input type="submit" value="登录" />
 </form>
 </body>
</html>

success.jsp

<%@ page language="java" import="java.util.*" pageencoding="utf-8" contenttype="text/html; charset=utf-8"%>
<%
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 'index.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>
  
 </body>
</html>

failure.jsp

<%@ page language="java" import="java.util.*" contenttype="text/html; charset=utf-8"%>
<%
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>
 登录失败,请检查用户名或密码!
 </body>
</html>

loginfilter.java

package com.cityhuntshou.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 loginfilter implements filter {
  private filterconfig config;
  public void destroy() {
    

  }

  public void dofilter(servletrequest arg0, servletresponse arg1,
      filterchain arg2) throws ioexception, servletexception {
    httpservletrequest request = (httpservletrequest) arg0;
    httpservletresponse response = (httpservletresponse) arg1;
    httpsession session = request.getsession();
    
    
    //过滤器实际应用场景之二-----编码转换
    
    string charset = config.getinitparameter("charset");
    
    if(charset == null)
    {
      charset = "utf-8";
    }
    
    request.setcharacterencoding(charset);
    
    string nologinpaths = config.getinitparameter("nologinpaths");
    
    
    
    if(nologinpaths != null)
    {
    string[] strarray = nologinpaths.split(";");
    for(int i = 0; i < strarray.length; i++)
    {
      //空元素,放行
      if(strarray[i] == null || "".equals(strarray[i]))
        continue;
        
      if(request.getrequesturi().indexof(strarray[i]) != -1)
      {
      arg2.dofilter(arg0, arg1);
      return;
      }
    }
    }
    if(request.getrequesturi().indexof("login.jsp") != -1
        || request.getrequesturi().indexof("loginservlet") != -1)
    {
      arg2.dofilter(arg0, arg1);
      return;
    }
    
    if(session.getattribute("username") != null)
    {
      arg2.dofilter(arg0, arg1);
    }
    else 
    {
      response.sendredirect("login.jsp");
    }
  }

  public void init(filterconfig arg0) throws servletexception {
    config = arg0;

  }

}

loginservlet.java

package com.cityhuntshou.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 {

    
  }

  /**
   * 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");
    //new string(username.getbytes("iso-8859-1"),"utf-8")
    system.out.println(username);
    if("admin".equals(username) && "admin".equals(password))
    {
      //校验通过
      httpsession session = request.getsession();
      session.setattribute("username", username);
      response.sendredirect(request.getcontextpath()+"/success.jsp");
    }
    else 
    {
      //校验失败
      response.sendredirect(request.getcontextpath()+"/failure.jsp");
    }
  }

  /**
   * initialization of the servlet. <br>
   *
   * @throws servletexception if an error occurs
   */
  public void init() throws servletexception {
    // put your code here
  }

}

web.xml

<?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">
 <display-name></display-name>
 <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>loginservlet</servlet-name>
  <servlet-class>com.cityhuntshou.servlet.loginservlet</servlet-class>
 </servlet>

 <servlet-mapping>
  <servlet-name>loginservlet</servlet-name>
  <url-pattern>/servlet/loginservlet</url-pattern>
 </servlet-mapping>  
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
  <filter>
    <filter-name>loginfilter</filter-name>
    <filter-class>com.cityhuntshou.filter.loginfilter</filter-class>
    <init-param>
      <param-name>nologinpaths</param-name>
      <param-value>login.jsp;failure.jsp;loginservlet</param-value>
    </init-param>
    <init-param>
      <param-name>charset</param-name>
      <param-value>utf-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>loginfilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

运行效果:

Java Web过滤器详解

Java Web过滤器详解

Java Web过滤器详解

Java Web过滤器详解

访问结果:

Java Web过滤器详解

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。