Spring MVC接收UTF-8 POST資料的時候出現亂碼

今日隨筆

環境
- Spring 4.1.6
- Tomcat 7

今天遇到了Spring的UTF8亂碼問題
database是utf-8格式,但是前端JSP在顯示網頁的時候顯示是一堆???
網頁端的部分解法單純,在網頁開頭加上個宣告就好

home.html
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
  
...

但加上這宣告之後反倒是spring接收的時候POST參數的時候出了問題

Spring接收POST參數的方法如下

home.java
@RequestMapping(value = "/myFunc", method = RequestMethod.POST)
    public String save_alias(HttpServletRequest request,
            @RequestParam(value = "memo") String alias_name,
            RedirectAttributes attributes
            ) {

使用內建的annotation去進行參數的bind

後來簡單的找到一個方法,在web.xml裏面加入charset的filter

web.xml
...
   <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <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>
        <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
      </init-param>
    </filter>
    <filter-mapping>
      <filter-name>characterEncodingFilter</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>
...

不過這年頭還用xml設定去解這問題實在是有點low

之後找找看應該有用annotation就能解的方法

comments powered by Disqus