Jetty响应字符编码
如何在对UTF-8的响应中设置默认字符编码?
我试过这个
System.setProperty("file.encoding", "UTF-8");
和这个
System.setProperty("org.eclipse.jetty.util.UrlEncoding.charset", "utf-8");
两者都没有任何效果 – 响应仍然与标题一起发送
Content-Type: text/html; charset=ISO-8859-1
我想对所有text / html响应执行此操作,理想情况下是代码而不是XML。 我正在使用Jetty 9。
Jetty文档声称它默认使用UTF-8,但这似乎是一个谎言。 如果执行正常的response.getWrite().println("Hello")
,则内容编码确定如下。
- 从
org/eclipse/jetty/http/encoding.properties
加载从content-type到content-encoding的默认映射:
// MimeTypes.java:155 ResourceBundle encoding = ResourceBundle.getBundle("org/eclipse/jetty/http/encoding"); Enumeration i = encoding.getKeys(); while(i.hasMoreElements()) { String type = i.nextElement(); __encodings.put(type,encoding.getString(type)); }
默认文件是:
text/html = ISO-8859-1 text/plain = ISO-8859-1 text/xml = UTF-8 text/json = UTF-8
-
Response.getWriter()
尝试使用该映射,但默认为ISO-8859-1
@Override public PrintWriter getWriter() throws IOException { if (_outputType == OutputType.STREAM) throw new IllegalStateException("STREAM"); if (_outputType == OutputType.NONE) { /* get encoding from Content-Type header */ String encoding = _characterEncoding; if (encoding == null) { encoding = MimeTypes.inferCharsetFromContentType(_contentType); if (encoding == null) encoding = StringUtil.__ISO_8859_1; setCharacterEncoding(encoding); }
所以你可以看到,对于text/html
它不会默认为UTF-8。 我认为没有办法从代码中更改默认值。 您可以做的最好是将encoding.properties
文件更改为:
text/html = UTF-8 text/plain = UTF-8 text/xml = UTF-8 text/json = UTF-8
但即便如此,如果它找到不在那里的编码,它将默认为ISO-8859-1。
response.setCharacterEncoding("UTF-8");
我为一个遗留应用程序创建了字符编码filter
public class CharacterEncodingFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if(req instanceof Request){ req.setCharacterEncoding("UTF-8"); } chain.doFilter(req, res); } @Override public void init(FilterConfig arg0) throws ServletException { } @Override public void destroy() { } }
在web.xml中,filter-mapping具有/ *的url-pattern。 这将通过CharacterEncodingFilter路由来自Web应用程序的所有请求。
CharacterEncoding CharacterEncoding my.app.filter.CharacterEncodingFilter CharacterEncoding /*
使用Writer()时很重要;
对我来说,如果我写
resp.getWriter().println("Return"); resp.setContentType("text/html; charset=UTF-8");
我不会工作
但是,如果我改变序列
resp.setContentType("text/html; charset=UTF-8"); resp.getWriter().println("Return");
它会好起来的