javaweb doPost与doGet请求获取参数乱码问题
作者:互联网
在doPost请求中我们可以使用拦截器,Filter进行拦截,将编码改为utf-8
package web.filter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Map.Entry;
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.HttpServletResponse;
@WebFilter("/*")//拦截所有的请求路径
public class MyEncodingFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void destroy() {}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse mResponse=(HttpServletResponse) response;
mResponse.setHeader("content-type", "text/html;charset=utf-8");
//1.设置POST请求中文乱码的问题
HttpServletRequest hsr = (HttpServletRequest)request;
if(hsr.getMethod().equalsIgnoreCase("post")){
request.setCharacterEncoding("UTF-8");
}
chain.doFilter(request, response);
}
}
可以对request与response进行拦截,修改编码
doGet请求出现乱码例如下列代码
String category=request.getParameter(“category”);
在这里category获取会变为乱码,这里有我想到的有两种解决方案
在获得这个参数后,进行转码
byte[] buf = category.getBytes(“iso8859-1”);
category = new String(buf,“utf-8”);
即可获得正确的数据
另一种解决方法修改Tomcat中的server.xml文件
在Connector标签下,添加URIEncoding=“utf-8”
重新启动Tomcat
即可正确获得参数
标签:category,servlet,request,doPost,乱码,import,doGet,javax 来源: https://blog.csdn.net/admin0_0/article/details/106537047