ie8兼容性問題(七) js參數值中文情況下無法傳到controller

項目中遇到這樣一個問題,要實現一個下載功能,參數有兩個,一個id,一個標題。其中標題是中文。

js寫法:
var params = {
  "id": "0001",
  "title": "需求響應速率概述"
}
window.open("downloadFilesController.do?download&id=" + params.id + "&title=" + params.title);

controller寫法:
@controller
@requestMapping("/downloadFilesController")
public class downloadFilesController{
  @requestMapping(params = "download")
  public void download(
    HttpServeletRequest request,
    HttpServletResponse response,
    @RequestParam("id") String id,
    @RequestParam("title") String title
  ) {
    commonFileDownBizc.downloadFile(request, response, id, title);
   }
}

這段代碼在chrome中是沒有問題的。但是在ie8中就會報錯。原因是這樣的。ie8中是不能通過get方法傳遞中文參數到controller的。所以需要在js中給中文參數進行轉碼,轉爲Unicode號,然後到controller中進行解碼,再傳遞給biz層。

js寫法:
var params = {
  "id": "0001",
  "title": encodeURI(encodeURI("需求響應速率概述"))
}
window.open("downloadFilesController.do?download&id=" + params.id + "&title=" + params.title);

controller寫法:
@controller
@requestMapping("/downloadFilesController")
public class downloadFilesController{
  @requestMapping(params = "download")
  public void download(
    HttpServeletRequest request,
    HttpServletResponse response,
    @RequestParam("id") String id,
    @RequestParam("title") String title
  ) {
    title = URLDecoder.decode(title, "utf-8");
    commonFileDownBizc.downloadFile(request, response, id, title);
   }
}

注意: 轉碼一定要兩次轉碼。第一次將三字節的中文轉爲帶%的單字節,第二次將%看做轉義字符進行第二次轉碼。具體的網上有很多文獻可以參考。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章