0

e.g. take this example https://alvinalexander.com/blog/post/servlets/how-put-object-request-httpservletrequest-servlet

request.setAttribute("YOUR_KEY", yourVariable);

How to make yourVariable to be a UFT-8 code string ?

Thanks !

user3552178
  • 2,719
  • 8
  • 40
  • 67

1 Answers1

1

In Java Servlets, request-scoped variables are internal to the JVM, so you don't have to worry about encoding them. They're just regular Java strings, which are internally stored as a series of 16-bit characters. You only have to worry about encoding strings as UTF-8 (or decoding them from UTF-8) when sending them outside of the JVM (or receiving them from outside of the JVM). You could encode a Java string into a byte buffer using UTF-8, but then it would just be a byte buffer, not a string. You're best off treating strings within the JVM as regular String instances and only UTF-8 encoding them when sending them to a destination that expects UTF-8. If you're using the string in a JSP, then (assuming that the JSP is using UTF-8) the string will be encoded as UTF-8 during the rendering of the JSP.

Willis Blackburn
  • 8,068
  • 19
  • 36
  • well, i plan to have UTF-8 string in the request attributes at interceptor, then in controller i take them out, and put in response. – user3552178 Dec 09 '19 at 12:34
  • 1
    In a servlets app you really should not be doing any UTF-8 encoding/decoding by yourself. That's the servlet engine's job. You should just deal with `java.lang.String`. If you find that you have to convert to/from UTF-8 yourself then probably the servlet engine is configured to use the wrong encoding. Possibly see https://stackoverflow.com/questions/12723339/utf-8-encoding-in-jsp-page/49380092 – Willis Blackburn Dec 09 '19 at 15:23