首页 文章

无法从JSP向Servlet发送特殊字符(UTF-8):显示问号

提问于
浏览
6

我在将一个特殊字符(如cyrillic或umlauts)从jsp发送到servlet时遇到问题 . 我非常感谢你的帮助 .

这是我做的:

  • 在jsp中定义了utf-8字符集:
<%@ page language="java" contentType="text/html; charset=utf-8" 
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
 ...

<div class="authentication">
  <form name="registerForm" action="register" method="get" accept-charset="UTF-8">
    <input type="input" name="newUser" size="17"/>
    <input type="submit" value="senden" />
  </form>
</div>
 ...
  • 在server.xml中为Connector设置Tomcat URIEncoding
<Connector URIEncoding="UTF-8" ...
  • 在servlet内部 - 将CharacterEncoding设置为UTF并读取请求
public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{

request.setCharacterEncoding("UTF-8");
String username = request.getParameter("newUser");
System.out.println("encoding: "+request.getCharacterEncoding());

System.out.println("received: "+username);
  • 以下是使用时显示的内容: Однако
encoding: UTF-8
received: ??????

我错过了什么吗?我想servlet无法正确解码String,但我不知道为什么会发生这种情况 . 我已经遵循了关于这个主题的所有建议,但没有运气 .

提前致谢 .

1 回答

  • 9

    一切都很好看 . 只需将 System.out.println() 控制台配置为将字节流解释为UTF-8 .

    如果您正坐在像Eclipse这样的IDE中,那么可以通过将Window> Preferences> General> Workspace> Text File Encoding设置为UTF-8来实现 . 对于其他环境,您应该更加具体,以便我们可以告诉您如何配置它 .

相关问题