如何解码Cookie

时间:2017-08-15 09:49:39

标签: spring cookies unicode

我通过将其编码为UTF-8来保存String格式的列表。但我看到{}: ...还有更多符号在Cookie值中。

%7B%22evt%22%3A%5B%5D%2C%22exc%22%3A%5B%5D%2C%22tourQuantity%22%3A%221%22%2C%22tourId%22%3A%22067e61623b6f4ae2a1712470b63dff00%22%2C%22room%22%3A%7B%22accId%22%3A%226%22%2C%22roomTypeId%22%3A%225%22%7D%7D

以上是cookie中的存储值。

public ResponseEntity < ModelAndView > saveReservation(@RequestBody String reservation, HttpServletRequest request,
  HttpServletResponse response) throws Exception {
  Cookie cookie = new Cookie("tourReservation", URLEncoder.encode(reservation, "UTF-8"));
  cookie.setMaxAge(24 * 60 * 60);
  cookie.setPath("/tour/reservation");
  response.addCookie(cookie);
  List < ? > list = service.saveRes(reservation);
  if (list.size() > 0) {
    .........
    return new ResponseEntity < ModelAndView > (model, HttpStatus.OK);
  }
  return new ResponseEntity < ModelAndView > (new ModelAndView("tour"), HttpStatus.BAD_REQUEST);
}

如何以良好的格式获取列表字符串?我还使用了StringEscapeUtils,我收到了错误java.lang.IllegalArgumentException: An invalid character [34] was present in the Cookie value

org.apache.commons.lang.StringEscapeUtils.unescapeJava(reservation)

1 个答案:

答案 0 :(得分:2)

保持原样。在JavaScript中获取Cookie值并使用unescape(str)decodeURIComponent(str)函数解码它。

注意:不推荐使用unescape(),因此您可以改为使用decodeURIComponent()