我正在尝试测试具有特殊字符的Servlet,该Servlet部署在jetty 9中。 我将一个带有单引号字符的String发布到Servlet。虽然我已经提到在Servlet中使用UTF-8字符编码,但Servlet无法打印单引号字符。我不知道下面的代码有什么问题:
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class SpecialCharacterServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
BufferedReader in = new BufferedReader(
new InputStreamReader(request.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
主要方法
public static void main(String s[]) {
try {
HttpURLConnection conn = (HttpURLConnection) new URL("http://localhost:8080/test/SpecialCharacterServlet").openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=*****");
String str = "Hello ‘World’";
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(str);
dos.flush();
dos.close();
InputStream is = conn.getInputStream();
byte[] content = new byte[is.available()];
is.read(content);
}catch(Exception e) {
System.out.println(e);
}
}
输出不显示单引号字符,输出为Hello World
,在那里有一些块。
答案 0 :(得分:1)
您需要删除隐含字符集但未定义字符集的任何操作。
在main()
中使用OutputStreamWriter将OutputStream包装为显式字符集声明。这可以确保通过OutputStreamWriter写入的所有内容都在正确的字符集中:
osw = OutputStreamWriter(conn.getOutputStream(), "UTF-8");
osw.write(str);
在您的servlet中,告诉您的inputStream从" UTF-8"解码:
BufferedReader in = new BufferedReader(
new InputStreamReader(request.getInputStream(), "UTF-8"));
System.out也需要进行字符集转换。这在DOS控制台上尤其麻烦。而是将结果写入文本文件,并在一个好的文本编辑器(如Notepad ++)中检查结果。同样,在写入文本文件时,在编写器的构造函数中设置字符集。