Web——Servlet处理请求参数中文乱码问题
方法:
用post方法设置编码
//Post方式下,设置编码,防止中外文乱码方法
request.setCharacterEncoding("UTF-8");
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Post方式下,设置编码,防止中外文乱码方法
request.setCharacterEncoding("UTF-8");
}
需要注意的是,设置编码这一句代码必须在所有的获取参数动作之前
package com.atguigu.servlets;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class AddServlet extends HttpServlet {
@Override
//帮助我们相应post请求
//直接输入 dopost 回车 ok
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Post方式下,设置编码,防止中外文乱码方法
request.setCharacterEncoding("UTF-8");
String fname = request.getParameter("fname");
String priceStr = request.getParameter("price");
Integer price = Integer.parseInt(priceStr);
String fcountStr = request.getParameter("fcount");
Integer fcount = Integer.parseInt(fcountStr);
String remark = request.getParameter("remark");
System.out.println("fname = "+fname);
System.out.println("price = "+price);
System.out.println("fcount = "+fcount);
System.out.println("remark = "+remark);
}
}
用get方法设置字符编码
//1.将字符串打散成字节数组
byte[] bytes=fname.getBytes("ISO-8859-1");
//2.将字节数组按照设定的编码重新组装成字符串
fname = new String(bytes,"UTF-8");
package com.atguigu.servlets;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class AddServlet extends HttpServlet {
@Override
//帮助我们相应post请求
//直接输入 dopost 回车 ok
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fname = request.getParameter("fname");
//1.将字符串打散成字节数组
byte[] bytes=fname.getBytes("ISO-8859-1");
// 2.将字节数组按照设定的编码重新组装成字符串
fname = new String(bytes,"UTF-8");
String priceStr = request.getParameter("price");
Integer price = Integer.parseInt(priceStr);
String fcountStr = request.getParameter("fcount");
Integer fcount = Integer.parseInt(fcountStr);
String remark = request.getParameter("remark");
System.out.println("fname = "+fname);
System.out.println("price = "+price);
System.out.println("fcount = "+fcount);
System.out.println("remark = "+remark);
}
}
我们在来看我们的运行结果:
向表单中填入数据,从后台中查看
此刻我们成功了,实现了中文字符编码!!!