zoukankan      html  css  js  c++  java
  • Java Web中解决乱码的方式

    Java Web中解决乱码的方式

    方式一:添加编码过滤器

    package com.itmacy.dev.filter;
    
    import javax.servlet.*;
    import javax.servlet.annotation.WebFilter;
    import java.io.IOException;
    
    /**
     * 编码过滤器
     * @author itmacy
     * @Date 2020/10/21
     */
    @WebFilter(urlPatterns = "/*")
    public class SetCharacterEncodingFilter implements Filter {
        private String newCharset;
        public void init(FilterConfig filterConfig) throws ServletException {
            if (filterConfig.getInitParameter("newcharset") != null) {
               newCharset = filterConfig.getInitParameter("newcharset");
            }else {
                newCharset = "utf-8";
            }
            System.out.println("过滤器初始化参数:" + newCharset);
        }
    
        public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
            req.setCharacterEncoding(newCharset); // 统一请求编码
            resp.setContentType("text/html;charset=" + newCharset); // 统一响应编码
            filterChain.doFilter(req,resp);
        }
    
        public void destroy() {
    
        }
    }
    
    

    方式二:web.xml文件配置编码过滤器

      <filter>
        <filter-name>SetCharacterEncoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
          <param-name>encoding</param-name>
          <param-value>UTF-8</param-value>
        </init-param>
      </filter>
      <filter-mapping>
        <filter-name>SetCharacterEncoding</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping> 
    
  • 相关阅读:
    Uboot启动流程分析(四)
    git更新提交到仓库
    MSM8953通过ADB进行AT指令操作
    Uboot启动流程分析(五)
    去除字符串中多个空格,保留一个空格
    socket握手SYN和ACK理解
    Redhat6更改yum源 (转)
    form提供的两种数据传输方式 get和post method=”post“和method=”get”
    linux误删除恢复(未验证)
    web前端学习路线
  • 原文地址:https://www.cnblogs.com/itmacy/p/13919433.html
Copyright © 2011-2022 走看看