1. 程式人生 > >ie8相容性問題(七) js引數值中文情況下無法傳到controller

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);
   }
}

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