我遇到的一些问题(2019.3.17)
声明:本人还是一个大三小白,有错误请谅解。
1. request.getParameter(“参数名”) 中文乱码解决方法
原因:Http请求传输时将url以ISO-8859-1编码,服务器收到字节流后默认会以ISO-8859-1编码来解码成字符流(造成中文乱码)。
如何解决:
1、获取URL的值为乱码(GET)
通过字符串和字节流转换时使用正确的编码获取中文参数:
String para=new String(request.getParameter("para").getBytyes("iso8859-1"),"gb2312");
或者,在服务端获取参数前,先设置解码方式。
<% /*jsp的最前面*/
request.setCharacterEncoding("UTF-8");
%>
这是通过转码的方式处理乱码问题,我们也可以通过Tomcat配置文件,设置URL编码集(URIEncoding)设置编码,这种方法也是一劳永逸的:
<Connector URIEncoding="UTF-8"
acceptCount="1500" connectionTimeout="20000"
enableLookups="false" maxSpareThreads="100"
maxThreads="1000" minSpareThreads="25" port="9082"
protocol="HTTP/1.1" useBodyEncodingForURI="true"/>
2、获取Form的值为乱码(POST)
使用过滤器
配置EncodingFilter;
public class EncodingFilter Implements Filter{
public void init(FilterConfig fconfig)throws ServletException{...}
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws Exception{
request.setCharacterEncoding("utf-8");//根据你的页面设置
System.out.println("------------Change Encoding OK!----------");
chain.doFilter(request,response);
}
public void destroy(){...}
}
2. 字符串比较问题
responseTest获取的字符串最前面带回车符