Bad character encoding when sending via AJAX

I have a Struts2 application with some encoding problems. My JSP page displays 2 forms; when I submit the first (a simple, regular form that reloads the full page), non-standard characters, such as áor ñ, are sent and displayed correctly. However, when I do the same with the second form (which is sent via AJAX), the data becomes corrupted ( Ãí, Ã!etc.).

main.jsp:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    ...
    <s:head theme="ajax"/>
</head>
<body>
    <!-- This form is sent via regular HTTP request -->
    <s:form theme="simple" enctype="multipart/form-data">
        <s:textfield key="field1" name="var1"/>
        <s:submit key="send" action="SAVE_ACTION"/>
    </s:form>
    <div id="ajaxContainer">
         <jsp:include file="ajax-part.jsp"/>
    </div>
</body>
</html>

Ajax-part.jsp

<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!-- This form is sent via AJAX -->
<s:form enctype="multipart/form-data" theme="ajax" action="AJAX_ACTION" acceptcharset="UTF-8">
    <s:textfield key="field2" name="var2"/>
    <s:submit key="send" targets="ajaxContainer"/>
</s:form>

As you can see, I encoded UTF-8 encoding everywhere. I also checked that the files are actually UTF-8 encoded. And DOJO (which is used for AJAX requests) is also configured in UTF-8 because it <s:head theme="ajax"/>becomes:

<script language="JavaScript" type="text/javascript">
    // Dojo configuration
    djConfig = {
        baseRelativePath: "/myApp/struts/dojo",
        isDebug: false,
        bindEncoding: "UTF-8",
        debugAtAllCosts: false
    };
</script>

Tomcat 6; -Dfile.encoding=UTF-8 (appart , UTF-8 ISO-8859-1).

Google Chrome, IE8, , , - webapp.

? AJAX?

+3
1

!

AJAX Firebug ( , Quaternion) : Dojo GET URL-. , Struts2 URL- , ; , , API- Servlet.

URIEncoding="UTF-8" <Connector> Tomcat server.xml, Apache Tomcat.

- , , , AJAX:

new String(myData.getBytes("ISO-8859-1"), "UTF-8");
+8

Source: https://habr.com/ru/post/1781791/


All Articles