SpringMVC的亂碼與時間轉換

shaonianbz發表於2018-04-03

post亂碼

在web.xml配置檔案中新增如下程式碼(程式碼位置:最前面)

<!-- 解決post亂碼(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>

get亂碼

在Tomcat的server.xml中修改為如下即可:
這裡寫圖片描述

表單提交時間轉換

SpringMVC的表單提交,時間預設只支援yyyy/MM/dd型別的。
解決辦法:在命令控制器封裝引數的類中重寫initBinder(HttpServletRequest request,
ServletRequestDataBinder binder)方法

public class CommandController extends AbstractCommandController{

    //指定引數繫結到那個javaBean
    public CommandController(){
        this.setCommandClass(User.class);
    }

    @Override
    protected ModelAndView handle(HttpServletRequest request,
            HttpServletResponse response, Object command, BindException errors)
            throws Exception {
        //把命令物件強制轉化為User物件
        User user=(User) command;
        ModelAndView mv=new ModelAndView();
        mv.addObject("user", user);
        mv.setViewName("index");
        return mv;
    }

    @Override
    /**
     * SpringMVC 時間轉換
     */
    protected void initBinder(HttpServletRequest request,
            ServletRequestDataBinder binder) throws Exception {
        //得到提交表單的時間
        String str = request.getParameter("birthday");
        if(str.contains("/")){
            binder.registerCustomEditor(Date.class, 
                    new CustomDateEditor(new SimpleDateFormat("yyyy/MM/dd"), true));
        }else if(str.contains("-")){
            binder.registerCustomEditor(Date.class, 
                    new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
        }
    }
}

相關文章