欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

jsp 解决ajax乱码的问题

程序员文章站 2022-04-17 14:04:54
...
<%@page import="java.io.OutputStream"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<%
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <button onclick="test()">测试</button>    
</body>

<script src="js/jquery-1.4.2.min.js"></script>
    <script>
        function test(){
            $.ajax({
                 type: "GET",
                 url: "testCookie",
                 data: {username:encodeURIComponent("燕子"), //编码content:encodeURIComponent("彩虹金刚")},
                 dataType: "json",

                 success: function(data){
                    console.log(data);
                 }
            });
        }
    </script>
</html>

服务器端

package my.jsp.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.text.MessageFormat;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyCookie extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {   
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "text/html;charset=UTF-8");//响应头  这样就可以解决返回值乱码的问题

        Enumeration<String> paramNames = request.getParameterNames();// 获取所有的参数名
        while (paramNames.hasMoreElements()) {
            String name1 = paramNames.nextElement();// 得到参数名
            String value1 = request.getParameter(name1);// 通过参数名获取对应的值
            System.out.println(MessageFormat.format("{0}={1}", URLDecoder.decode(name1,"utf-8"), URLDecoder.decode(value1,"utf-8")));//解码
        }


        PrintWriter out = response.getWriter();
        out.print("蛤蛤蛤");         
        //释放资源
        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }



}