public void destroy() {
System.out.println(“过滤器销毁…”);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println(“进行过滤器开发…”);
// 只要在这里加 先解决post请求乱码
request.setCharacterEncoding(“utf-8”);// 请求
response.setCharacterEncoding(“utf-8”);// 响应
response.setContentType(“text/html;charset=utf-8”);// 响应
// get提交乱码处理
chain.doFilter(new MyRequest((HttpServletRequest) request), response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println(“过滤器初始化…”);
}
class MyRequest extends HttpServletRequestWrapper {
HttpServletRequest request;
public MyRequest(HttpServletRequest request) {
super(request);
this.request = request;
}
@Override
public String getParameter(String name) {
String value = request.getParameter(name);
// 先判断是否为空
if (value == null) {
return null;
}
// 再判断提交方法
if (!request.getMethod().equals(“GET”)) {
return value;
}
// get提交
try {
value = new String(value.getBytes(“iso8859-1”), “utf-8”);
} ca
《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》
【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享
tch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return value;
}
@Override
public String[] getParameterValues(String name) {
String[] oldValues = request.getParameterValues(name);
String[] newValues = null;
if (oldValues != null) {
newValues = new String[oldValues.length];
if (!request.getMethod().equals(“GET”)) {
return oldValues;
}
if (newValues != null) {
try {
for (int i = 0; i < oldValues.length; i++) {
String value = oldValues[i];
value = new String(value.getBytes(“iso8859-1”),
“utf-8”);
newValues[i] = value;
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return newValues;
}
@Override
public Map<String, String[]> getParameterMap() {
// 1.拿到客户端的值
Map<String, String[]> oldMap = request.getParameterMap();
// 2.新map
Map<String, String[]> newMap = new HashMap<String, String[]>();
// 3.拿出oldMap
Set<Entry<String, String[]>> entrySet = oldMap.entrySet();
for (Entry<String, String[]> entry : entrySet) {
// 4.获取键
String key = entry.getKey();
// 5.获取值
String[] values = entry.getValue();
// 新的数组和原数组一样大
String[] newValues = new String[values.length];
// 6.判断值是否为空
if (values == null) {
newMap.put(key, new String[] {});// 初始化
continue;
}
// 7.取出values里面每一个值进行转码
try {
for (int i = 0; i < values.length; i++) {
String value = values[i];
value = new String(value.getBytes(“iso8859-1”), “utf-8”);
// value = new String(value.getBytes(“iso8859-1”),
// request.getCharacterEncoding());
newValues[i] = value;
}
newMap.put(key, newValues);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return newMap;
}
}
}
在web.xml配置过滤器:
Set Character Encoding
com.wb.filter.TestFilter
encoding
UTF-8
文章评论