servlet中解决中文乱码的方法

一、页面乱码问题的解决

1、jsp页面
在头文件中加入(UTF-8)编码格式:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
      <title>Title</title>
</head>
<body>
   <h1>请求失败</h1>
</body>
</html>

2、html页面

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

应用:

<!DOCTYPE html>
<html>
	<head>
			<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>标题</title>
	</head>
	<body>
		中文正文
	</body>
</html>

二、request请求的乱码问题

// 设置请求的中文编码格式为(UTF-8)
     request.setCharacterEncoding("utf-8");

应用:

public class EnglishServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置请求的中文编码格式为(UTF-8)
        request.setCharacterEncoding("utf-8");
        }

三、response相应的乱码问题

1、方式一:

//设置相应的中文编码格式为(UTF-8)
      response.setCharacterEncoding("utf-8");
//将设置的编码格式通知浏览器
      response.addHeader("content-type","text/html;charset=utf-8" );

2、方式二:

//合并为一个方法,设置编码格式(UTF-8)
   response.setContentType("utf-8");

应用:

public class EnglishServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           this.doGet(request,response);
            }
        
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //方式一:
       //设置相应的中文编码格式为(UTF-8)
              response.setCharacterEncoding("utf-8");
        //将设置的编码格式通知浏览器
              response.addHeader("content-type","text/html;charset=utf-8" );
     //方式二:        
        //合并为一个方法,设置编码格式(UTF-8)
              response.setContentType("utf-8");
                }

四、连接地址:

1、百度网盘:
链接:https://pan.baidu.com/s/1lCFu2esqEaHZqSo7saGqlg 提取码:esko
2、CSDN:
https://download.csdn.net/download/weixin_44624117/11438274

posted @ 2019-07-27 14:00  ah_lydms  阅读(175)  评论(0编辑  收藏  举报