如何使Servlet接受从JSP传递的非ASCII(阿拉伯,中文等)字符?
我尝试将以下内容添加到JSP的顶部:
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
并在servlet的每个post / get方法中添加以下内容:
request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8");
我试图添加一个执行上述两个语句而不是在servlet中执行的Filter。
坦白地说,这些功能过去曾经有用,但现在已经不起作用了。
我在Win&Linux机器上都在JDK1.6上使用tomcat 5.0.28 / 6.xx。
这是一个示例:JSP页面:
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <head> <title>Push Engine</title> </head> <body> Hello ${requestScope['val']} <form action="ControllerServlet" method="POST"> <table> <tr> <td>ABC</td> <td><input name="ABC" type="text" /></td> </tr> <tr> <td></td> <td><input type="submit" value="Submit"></td> </tr> </table> </form> </body> </html>
Servlet doGet方法:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String val = "request.getParameter('ABC') : " + request.getParameter("ABC"); System.out.println(val); request.setAttribute("val", val); request.getRequestDispatcher("index.jsp").forward(request, response); }
问题是: 在控制台中,值“ ???” 正在打印,但是,返回到包含正确的Unicode字的JSP页面的值
“ ???” 打印到控制台是我运行此测试的机器上的问题。我已经在另一台机器上运行了相同的示例,并且可以正常工作!
至此,您需要设置请求编码。
对于GET请求(参数通过请求URL传递),您需要在appserver级别进行配置。例如,在Tomcat 6.0中URIEncoding,将<Connector>元素的属性设置为/conf/server.xml即可UTF-8。
URIEncoding
<Connector>
/conf/server.xml
UTF-8
<Connector (...) URIEncoding="UTF-8" />
对于POST请求(其中的参数是“不可见”,通过请求体传递),你需要调用ServletRequest#setCharacterEncoding()与UTF-8 之前 收集的任何请求参数。最好的地方是在一个过滤器中,该过滤器被称为链中的 第一个 过滤器:
ServletRequest#setCharacterEncoding()
if (request.getCharacterEncoding() == null) { request.setCharacterEncoding("UTF-8"); } chain.doFilter(request, response);