springmvc 解決中文亂碼問題

Hanyta發表於2024-05-14
  1. 自定義過濾器

    • 自定義實現Filter介面
    public class MyCharacterFilter implements Filter {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void doFilter(ServletRequest servletRequest,
                             ServletResponse servletResponse,
                             FilterChain filterChain) throws IOException, ServletException {
            //這裡加入對編碼的處理
            servletRequest.setCharacterEncoding("utf-8");
            //放行請求,這個規則和前面講過的java web的過濾器一樣
            filterChain.doFilter(servletRequest, servletResponse);
        }
    
        @Override
        public void destroy() {
    
        }
    }
    
    • 配置web.xml
    <filter>
        <filter-name>myCharacterFilter</filter-name>
        <filter-class>com.web.filter.MyCharacterFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>myCharacterFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
  2. springmvc中的過濾器處理中文

    • 修改web.xml檔案
    <!--配置Spring提供的過濾器,解決中文亂碼問題-->
    <filter>
        <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    

相關文章