关于 jsp java servlet 中文汉字乱码的解决方法

在servlet类中的get,post最前面加上

req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");

这里写图片描述

这里写图片描述

对接收到的汉字字符串转码

        String name = req.getParameter("name");
        String deptName = req.getParameter("deptName");
        name = new String(name.getBytes("ISO-8859-1"), "UTF-8");
        deptName = new String(deptName.getBytes("ISO-8859-1"), "UTF-8");

这里写图片描述

完整样例:

package servlet;

import Dao.DeptDao;
import Dao.EmpDao;
import entity.Emp;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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.io.PrintWriter;
import java.io.UnsupportedEncodingException;

public class EmpServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        if("listEmp".equals(action)){
            listEmp(req,resp);
        }
    }

    private void listEmp(HttpServletRequest req, HttpServletResponse resp){
        JSONArray result = EmpDao.listEmp();
        PrintWriter pw = null;
        try {
            pw = resp.getWriter();
            pw.println(result);
            pw.flush();
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        if("addEmp".equals(action)){
            try {
                addEmp(req,resp);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void addEmp(HttpServletRequest req, HttpServletResponse resp) throws JSONException, UnsupportedEncodingException {
        String name = req.getParameter("name");
        String deptName = req.getParameter("deptName");
        name = new String(name.getBytes("ISO-8859-1"), "UTF-8");
        deptName = new String(deptName.getBytes("ISO-8859-1"), "UTF-8");

        int deptId = DeptDao.reConvert(deptName);
        JSONObject result = EmpDao.addEmp(name,deptId);
        try {
            PrintWriter pw = resp.getWriter();
            pw.println(result);
            pw.flush();
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(关于 jsp java servlet 中文汉字乱码的解决方法)