Rob*_*itt 1 java unicode servlets utf-8
我从我的HTML页面获取一个字符串到我的Java HTTPServlet.根据我的要求,我得到显示中文字符的ASCII码:
"可以告诉我" (没有空格)
如何将此字符串转换为Unicode?
HTML代码:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Find information</title>
<link rel="stylesheet" type="text/css" href="layout.css">
</head>
<body>
<form id="lookupform" name="lookupform" action="LookupServlet" method="post" accept-charset="UTF-8">
<table id="lookuptable" align="center">
<tr>
<label>Question:</label>
<td><textarea cols="30" rows="2" name="lookupstring" id="lookupstring"></textarea></td>
</tr>
</table>
<input type="submit" name="Look up" id="lookup" value="Look up"/>
</form>
Run Code Online (Sandbox Code Playgroud)
Java代码:
request.setCharacterEncoding("UTF-8");
javax.servlet.http.HttpSession session = request.getSession();
LoginResult lr = (LoginResult) session.getAttribute("loginResult");
String[] question = request.getParameterValues("lookupstring");
Run Code Online (Sandbox Code Playgroud)
如果我打印问题[0],那么我得到这个值:"可以告诉我"
没有ASCII显示汉字的代码.ASCII不代表中文字符.
如果您已有Java字符串,则它已具有所有字符(US,LATIN,CHINESE)的内部表示形式.然后,您可以使用UTF-8或UTF-16表示将该Java字符串编码为Unicode :
String s ="可以告诉我";(编辑:此行不会在没有中文字符的系统上正确显示)
String s = "\u53ef\u4ee5\u544a\u8bc9\u6211";
byte utfString = s.getBytes("UTF-8");
Run Code Online (Sandbox Code Playgroud)
现在,我查看您更新的问题,您可能正在寻找StringEscapeUtils类.它来自Apache Commons Text.而将未逸出你的HTML实体成一个Java字符串:
String s = StringEscapeUtils.unescapeHtml("& #21487;& #20197;& #21578;& #35785;& #25105;"); // without spaces
Run Code Online (Sandbox Code Playgroud)