针对Request:
在写方法之前先敲:request.setCharacterEncoding("utf-8")
@WebServlet("/RequestDemo9")
public class RequestDemo9 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
Object msg = request.getAttribute("msg");
System.out.println(msg);
System.out.println("demo9在访问...");
}
针对Response:
Step1.需要设置编码
Step2.需要告知浏览器,服务器发送消息的编码格式
以下三种方法本质上是相同的,都能解决response乱码问题,其三者是语言提供更简洁的递进。
法一:
response.setCharacterEncoding("utf-8");
response.setHeader("content-type","text/html;charset=utf-8");
法二:
response.setHeader("content-type","text/html;charset=utf-8");
法三:
response.setContentType("text/html;charset=utf-8");
由于法三最简单,故也是经常使用的方法。