有没有办法在嵌入式tomcat中设置响应编码?到目前为止,我只能找到设置URI编码。但我需要设置响应编码。
令人惊讶的是,独立的tomcat默认以UTF-8发送数据。
答案 0 :(得分:0)
您可以创建过滤器来设置响应编码
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
public class MyFilter implements Filter{
public void init(FilterConfig arg0) throws ServletException {}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
resp.setCharacterEncoding("text/plain; charset=UTF-8");
chain.doFilter(req, resp);//sends request to next resource
}
public void destroy() {}
}
答案 1 :(得分:0)
创建过滤器:
`package charsetFilter.classes;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class CharsetFilter implements Filter{
private String encoding;
public void init(FilterConfig config) throws ServletException{
encoding = config.getInitParameter("requestEncoding");
if( encoding==null ) encoding="UTF-8";
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain next)
throws IOException, ServletException{
// Respect the client-specified character encoding
// (see HTTP specification section 3.4.1)
if(null == request.getCharacterEncoding())
request.setCharacterEncoding(encoding);
/**
* Set the default response content type and encoding
*/
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
next.doFilter(request, response);
}
public void destroy(){}
}`
在web.xml中添加此过滤器为:
`<filter>
<filter-name>CharsetFilter</filter-name>
<filter-class>charsetFilter.classes.CharsetFilter</filter-class>
<init-param>
<param-name>requestEncoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharsetFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>`
HTML-meta标签应该写在所有HTML文件中:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fi">
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
将您的servlet设置为:
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
处理servlet请求为:
String input = new String(request.getParameter("foo").getBytes("iso-8859-1"), "utf-8");
String input = URLDecoder.decode(request.getParameter("keyWord"), "UTF-8");
如果您仍有问题,请告诉我