Eniss
Eniss

Reputation: 913

How to Decode Unicode Characters from Cookie

I am saving a list in String format by encoding it to UTF-8. But I see that {, }, :... and more symbols are in cookie value.

%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

Above one is the stored value in the 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);
}

How can I get my list string in a good format? I also used StringEscapeUtils, I got an error java.lang.IllegalArgumentException: An invalid character [34] was present in the Cookie value.

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

Upvotes: 0

Views: 2567

Answers (1)

Alican Balik
Alican Balik

Reputation: 1294

Leave as it is. Get the cookie value in JavaScript and use unescape(str) or decodeURIComponent(str) function to decode it.

Note: unescape() is deprecated so you may use decodeURIComponent() instead.

Upvotes: 2

Related Questions