Java Web过滤器详解

发布时间 - 2026-01-11 02:59:52    点击率:

过滤器是什么玩意?

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

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

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

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

4.转换图像格式

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

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

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过滤器处理乱码  # JavaWeb之Filter过滤器详解  # Java web过滤器验证登录防止未登录进入界面  # Java Web Filter 过滤器学习教程(推荐)  # javaweb中Filter(过滤器)的常见应用  # 传智播客java web 过滤器  # 服务端  # 可在  # 之二  # 用户发送  # 大家多多  # 实际应用  # 性问题  # 请检查  # 器中  # 出现乱码  # base  # href  # head  # Transitional  # EN  # meta  # http  # equiv  # starting  # pragma 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: Laravel Octane如何提升性能_使用Laravel Octane加速你的应用  如何注册花生壳免费域名并搭建个人网站?  公司网站制作需要多少钱,找人做公司网站需要多少钱?  html文件怎么打开证书错误_https协议的html打开提示不安全【指南】  Laravel数据库迁移怎么用_Laravel Migration管理数据库结构的正确姿势  手机网站制作平台,手机靓号代理商怎么制作属于自己的手机靓号网站?  如何快速选择适合个人网站的云服务器配置?  js实现点击每个li节点,都弹出其文本值及修改  如何有效防御Web建站篡改攻击?  Edge浏览器提示“由你的组织管理”怎么解决_去除浏览器托管提示【修复】  如何将凡科建站内容保存为本地文件?  如何在宝塔面板中创建新站点?  Laravel定时任务怎么设置_Laravel Crontab调度器配置  UC浏览器如何切换小说阅读源_UC浏览器阅读源切换【方法】  Midjourney怎么调整光影效果_Midjourney光影调整方法【指南】  网站广告牌制作方法,街上的广告牌,横幅,用PS还是其他软件做的?  夸克浏览器网页跳转延迟怎么办 夸克浏览器跳转优化  如何快速搭建支持数据库操作的智能建站平台?  网站优化排名时,需要考虑哪些问题呢?  高防服务器租用如何选择配置与防御等级?  如何在腾讯云免费申请建站?  Python制作简易注册登录系统  详解免费开源的DotNet二维码操作组件ThoughtWorks.QRCode(.NET组件介绍之四)  详解jQuery停止动画——stop()方法的使用  Laravel Pest测试框架怎么用_从PHPUnit转向Pest的Laravel测试教程  Laravel如何使用Gate和Policy进行权限控制_Laravel权限判定与策略规则配置  如何在宝塔面板中修改默认建站目录?  Laravel中DTO是什么概念_在Laravel项目中使用数据传输对象(DTO)  西安市网站制作公司,哪个相亲网站比较好?西安比较好的相亲网站?  独立制作一个网站多少钱,建立网站需要花多少钱?  laravel怎么使用数据库工厂(Factory)生成带有关联模型的数据_laravel Factory生成关联数据方法  Laravel怎么配置S3云存储驱动_Laravel集成阿里云OSS或AWS S3存储桶【教程】  Python自然语言搜索引擎项目教程_倒排索引查询优化案例  香港服务器如何优化才能显著提升网站加载速度?  三星网站视频制作教程下载,三星w23网页如何全屏?  如何获取PHP WAP自助建站系统源码?  高端建站如何打造兼具美学与转化的品牌官网?  laravel怎么通过契约(Contracts)编程_laravel契约(Contracts)编程方法  用v-html解决Vue.js渲染中html标签不被解析的问题  免费视频制作网站,更新又快又好的免费电影网站?  WEB开发之注册页面验证码倒计时代码的实现  什么是JavaScript解构赋值_解构赋值有哪些实用技巧  如何快速辨别茅台真假?关键步骤解析  iOS正则表达式验证手机号、邮箱、身份证号等  Laravel如何实现多级无限分类_Laravel递归模型关联与树状数据输出【方法】  html5audio标签播放结束怎么触发事件_onended回调方法【教程】  ,怎么在广州志愿者网站注册?  Laravel如何为API编写文档_Laravel API文档生成与维护方法  香港服务器网站推广:SEO优化与外贸独立站搭建策略  ,网页ppt怎么弄成自己的ppt?