Java Web过滤器详解

 更新时间:2017年08月28日 14:34:26   作者:cityhuntshou  
这篇文章主要为大家详细介绍了Java WEB过滤器的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

过滤器是什么玩意?

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

过滤器的应用场景:
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>

运行效果:

访问结果:

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

相关文章

  • Spring Boot集成sa-token的项目实践

    Spring Boot集成sa-token的项目实践

    本文主要介绍了Spring Boot集成sa-token的项目实践,实现了基本的登录和权限控制功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-05-05
  • 浅谈java多态的实现主要体现在哪些方面

    浅谈java多态的实现主要体现在哪些方面

    下面小编就为大家带来一篇浅谈java多态的实现主要体现在哪些方面。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-09-09
  • 使用@Value值注入及配置文件组件扫描

    使用@Value值注入及配置文件组件扫描

    这篇文章主要介绍了使用@Value值注入及配置文件组件扫描方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • 两种JAVA实现短网址服务算法

    两种JAVA实现短网址服务算法

    这篇文章介绍了两种JAVA实现短网址服务算法,一种是基于MD5码的,一种是基于自增序列的,需要的朋友可以参考下
    2015-07-07
  • Java @Accessors注解图文详解

    Java @Accessors注解图文详解

    @Accessors用于改变@Data生成的getter和setter方法的生成结果,下面这篇文章主要给大家介绍了关于Java @Accessors注解的相关资料,需要的朋友可以参考下
    2023-02-02
  • Spring Gateway基础教程

    Spring Gateway基础教程

    本文主要总结Spring Gateway的基础用法,内容包括网关、Spring Gateway工作流程、Spring Cloud Gateway搭建、路由配置方式、负载均衡实现、断言工厂这几个部分,感兴趣的朋友跟随小编一起看看吧
    2023-11-11
  • spring中@ComponentScan自动扫描并指定扫描规则

    spring中@ComponentScan自动扫描并指定扫描规则

    本文主要介绍了spring中@ComponentScan自动扫描并指定扫描规则,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-04-04
  • Java Spring分别实现定时任务方法

    Java Spring分别实现定时任务方法

    这篇文章主要为大家详细介绍了Java与Spring设置动态定时任务的方法,定时任务的应用场景十分广泛,如定时清理文件、定时生成报表、定时数据同步备份等
    2022-07-07
  • spring cloud整合ribbon问题及解决方案

    spring cloud整合ribbon问题及解决方案

    很多小伙伴在整合ribbon都出了相同的问题,今天特地为大家整理了该问题的解决方案,文中有非常详细的图文解说,对出现同样问题的小伙伴们很有帮助,需要的朋友可以参考下
    2021-05-05
  • 关于Java日期工具类的编写

    关于Java日期工具类的编写

    这篇文章主要介绍了关于Java日期工具类的编写,在Java开发中,经常会遇到处理日期相关的数据,那么今天我们来自己写一个工具类,文中有详细的实例代码以及实现思路,需要的朋友可以参考下
    2023-05-05

最新评论