zoukankan      html  css  js  c++  java
  • Filter实现字符集统一设置

    Filter实现字符集统一设置

    其实是对request和response请求进行了拦截

    1.创建Filter类,实现javax.Servlet接口

    doFilter方法

    [java] view plain copy
     
    1. //设置字符集  
    2.         request.setCharacterEncoding("GB18030");  
    3.     //继续执行  
    4.     chain.doFilter(request, reponse);  


    2.配置到web.xml中,请求request时,对所有jsp servlet进行统一设置(拦截)

    [html] view plain copy
     
    1. <filter>  
    2.         <filter-name>CharsetEncodingFilter</filter-name>  
    3.         <filter-class>com.bgt.drp.util.filter.CharsetEncodingFilter</filter-class>  
    4.     </filter>  
    5.       
    6.     <filter-mapping>  
    7.         <filter-name>CharsetEncodingFilter</filter-name>  
    8.         <url-pattern>*.jsp</url-pattern>  
    9.     </filter-mapping>  
    10.     <filter-mapping>  
    11.         <filter-name>CharsetEncodingFilter</filter-name>  
    12.         <url-pattern>/servlet/*</url-pattern>  
    13.     </filter-mapping>  

    为达到灵活配置,不用修改java代码就可以改变设置的字符集类型

    可以将字符集放到配置文件中,通过读取配置文件获取

    还可以配置Filter时,传参数(字符集作为参数),tomcat启动初始化时,获取到参数【采取】

    1.配置Filter时,传参数<init-param>标签

    [html] view plain copy
     
    1. <filter>  
    2.         <filter-name>CharsetEncodingFilter</filter-name>  
    3.         <filter-class>com.bgt.drp.util.filter.CharsetEncodingFilter</filter-class>  
    4.         <init-param>  
    5.             <param-name>encoding</param-name>  
    6.             <param-value>GBK</param-value>  
    7.         </init-param>  
    8.     </filter>  

    2.Init方法获取参数,doFilter设置字符集

    [java] view plain copy
     
    1. public class CharsetEncodingFilter implements Filter {  
    2.       
    3.     private String encoding;  
    4.       
    5.     @Override  
    6.     public void destroy() {  
    7.   
    8.     }  
    9.   
    10.     @Override  
    11.     public void doFilter(ServletRequest request, ServletResponse reponse,  
    12.             FilterChain chain) throws IOException, ServletException {  
    13.           
    14.         //设置字符集  
    15.         request.setCharacterEncoding(encoding);  
    16.         //继续执行  
    17.         chain.doFilter(request, reponse);  
    18.     }  
    19.   
    20.     @Override  
    21.     public void init(FilterConfig filterConfig) throws ServletException {  
    22.           
    23.         this.encoding = filterConfig.getInitParameter("encoding");  
    24.   
    25.     }  
    26.   
    27. }  

    每次request请求通过配置文件,都会拦截,读取参数,并完成对作用域字符集的统一设置,灵活可配置,避免重复

    扩:

    Filter可以看做是一种横切性的技术

    提供一种声明式服务,可插拔

    体现了职责链模式

    转载自:https://blog.csdn.net/songxuemeng/article/details/52434847

  • 相关阅读:
    GUI 之 JDialog弹窗
    GUI Swing 之 JFrame窗体
    GUI 键盘监听事件
    GUI 窗口监听事件
    GUI 鼠标监听事件,模拟画图工具
    shell编程
    Ubuntu20.04 Linux初识
    rlwrap的使用
    5个相见恨晚的Linux命令,每一个都非常实用
    Bash初识与常用命令
  • 原文地址:https://www.cnblogs.com/PengChengLi/p/9172901.html
Copyright © 2011-2022 走看看