Search code examples
javajsposgiaemsling

How to Set UTF-8 response on doPost() call?


I Am trying to have a JSON response back to the page with UTF-8 data, as it is what i have posted from the Form to my osgi servlet. The Servlet code is as shown below:

import org.json.simple.JSONArray;
    import org.json.simple.JSONObject;    

@SlingServlet(paths="/bin/JsonOsgiCall", methods = "POST", metatype=true)
public class JsonOsgiCall extends org.apache.sling.api.servlets.SlingAllMethodsServlet {
     private static final long serialVersionUID = 2598426539166788515L;
     protected final Logger log = LoggerFactory.getLogger(this.getClass());

     @Override
     protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServerException, IOException {
    response.setContentType("text/html; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();
    JSONObject jsonobj = new JSONObject();

    try { 

        jsonobj.put("testint", 30);
        jsonobj.put("myjspstring", request.getParameter("userinmsg"));
        jsonobj.put("myjspstati","`İş hayatında ne çok engelle karşılaşıldığını,`");
        JSONArray list = new JSONArray();
        list.add("message 1");
        list.add("message 2");
        jsonobj.put("messages", list);
       log.info("*** JSON Object with ***" + jsonobj.toJSONString());
       //out.println(jsonobj.toJSONString());
       out.println(jsonobj);  
    } 
 catch (Exception e) {
    e.printStackTrace();
}
}
}

And my JSP Form code shown as below:

<%@include file="/libs/foundation/global.jsp"%><%
    %><%@page session="false" %>
    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ page import="org.json.simple.JSONObject,java.io.PrintWriter,java.util.*"%>
    <%
    %>CALL OSGI SERVICE FOR JSON RESPONSE
    <cq:includeClientLib js="granite.csrf.standalone"/>
    <head>
    <meta charset="UTF-8" />
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Editer les sous-titres</title>
    </head>
    <body>
    <form id="submitForm" method="POST" action="/bin/JsonOsgiCall">
        <textarea name="userinmsg" autocomplete="off" type="text" id="userinmsg" rows="4" cols="30" style="width: 450px; margin-left: 25px;">
        </textarea>
        <br/>

        <p style="margin-left: 420px;"><input name="submitmsg" type="submit"  id="submitmsg" value="Call JSON Service" /></p>

      </form>
    </body>

But when I submit the Form and see the output that has resulted back to the page is like with ANSI format. Where the the JSON data that I have added in the:

jsonobj.put("myjspstati","İş hayatında ne çok engelle karşılaşıldığını,");

In between code snippet is coming fine back to page. But where as the form submitted same code is breaking when it received into servlet with:

request.getParameter(userinmsg)

How can I get the UTF enabled data that can be properly sent to Servlet and can do the JSON object with same.

formsubmit ServletResponse

Debugging in my browser Developer tools Request Headers Request Headers

Response Response Headers


Solution

  • you can see your charset is being broken(as the ServerSide json data with utf-8 is resulted correct and you have a doubt in your request.getParameter()) when it is getting transferred after form submission.

    Try adding <input type="hidden" name="_charset_" value="UTF-8"/> where browser will fill-in the submitted character encoding as the field's value.

    Modified your form alone along with hidden input for charset utf-8

    <form id="submitForm" method="POST" action="/bin/JsonOsgiCall">
                <textarea name="userinmsg" autocomplete="off" type="text" id="userinmsg" rows="4" cols="30" style="width: 450px; margin-left: 25px;">
                </textarea>
                <br/>
        <input type="hidden" name="_charset_" value="UTF-8"/>
                <p style="margin-left: 420px;"><input name="submitmsg" type="submit"  id="submitmsg" value="Call JSON Service" /></p>
    
              </form>
    

    Another way of handling it at AEM level Felix Config

    Set your charset to UTF-8 in Apache Sling Request Parameter Handling Default Parameter Encoding as shown below screenshot. Felix Charset

    ~Hope it works