在做JSP系统时经常遇到的就是编码问题
而这个服务器可以是Tomcat、Weblogic,Tomcat服务器默认的编码为iso-8859-1,Weblogic默认的编码为UTF-8,所以程序运行时要注意编码设置
现在我们以一个jsp页面的代码,解释这些编码设置pageEncoding="UTF-8"说的是页面的编码,比如标题栏<title>还有其它内容等等
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">这代码说的是上下文编码,若我们设置charset="UTF-8",那我们在点击这个页面跳到的那个Servlet或者jsp页面就要用"request.setCharacterEncoding("UTF-8");"和"String newsbody = new String(request.getParameter("editorValue").getBytes("iso-8859-1"),"UTF-8");"意思是设置接收到的字符串编码为UTF-8,响应的编码设置,可以用response.setContentType("text/html;charset=UTF-8");
<%@page import="java.net.URLDecoder"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'test.jsp' starting page</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<style type="text/css">
.news {
width: 800px;
margin: 0 auto;
}
</style>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=GBK");
String newsbody = new String(request.getParameter("editorValue").getBytes("iso-8859-1"),"UTF-8");
%>
<div class="news">
<%=newsbody%>
</div>
</body>
</html>
String newsbody = new String(request.getParameter("editorValue").getBytes("iso-8859-1"),"UTF-8");
给一个编码过滤器参考
import java.io.IOException;
import java.nio.charset.Charset;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @description: 编码过滤器, 解决get或post方式的乱码问题
*/
(filterName = "encodingFilter", urlPatterns = "/*")
public class EncodingFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(EncodingFilter.class);
private String encode = "UTF-8";// 默认编码集
private String containers_encode="ISO8859-1";//web容器编码
public void destroy() {
logger.info("====过滤器正在销毁====");
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
if (httpRequest.getMethod().equals("POST")) {
logger.debug("post请求,直接设置编码");
// 直接设置编码
request.setCharacterEncoding(encode);
} else {
// 重写HttpServletRequestWrapper进行内部转码
logger.debug("get请求,尝试转码");
request = new Request(httpRequest);
}
// 设置返回客户端编码
response.setCharacterEncoding(encode);
chain.doFilter(request, response);// 交替权利给下一个过滤器或servlet服务
}
class Request extends HttpServletRequestWrapper {
/* 构造函数 */
public Request(HttpServletRequest request) {
super(request);
}
private HttpServletRequest getHttpServletRequest() {
return (HttpServletRequest) super.getRequest();
}
/**
* 转换由表单读取的数据的内码
*
* @param str
* @return
*/
private String changeEncode(String str) {
if (needEncoding(str)) {
try {
byte[] bytes = str.getBytes(containers_encode);
logger.debug("数据:{} 转码结果:{}", str,
new String(bytes, encode));
return new String(bytes, encode);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
return str;
}
/* 判断字符串是否需要转码 */
private boolean needEncoding(String str) {
/* 如果为汉字,则不需要转码 */
return Charset.forName(containers_encode).newEncoder().canEncode(str);
}
/* 单个参数 */
public String getParameter(String arg) {
String value = getHttpServletRequest().getParameter(arg);
if (value != null) {
return changeEncode(getHttpServletRequest().getParameter(arg));
}
return getHttpServletRequest().getParameter(arg);
}
/* 多个参数 */
public String[] getParameterValues(String arg) {
String values[] = getHttpServletRequest().getParameterValues(arg);
if (values != null) {
for (int i = 0; i < values.length; i++) {
values[i] = changeEncode(values[i]);
}
}
return values;
}
}
public void init(FilterConfig config) throws ServletException {
logger.debug("====编码过滤器启动====");
/* 读取配置参数的编码集 */
String encoding = config.getInitParameter("encode");
if (StringUtils.isNotBlank(encoding)) {
this.encode = encoding;
}
}
}