bmb242 bmb242 - 7 months ago 135
Java Question

Null or empty JSON object from AJAX request

Ended up deleting another question I had posted earlier related to this, as it had become obsolete and there was another thing to address. The answer below is very clear, more so than other answers, and I believe this will be helpful for anyone else having similar confusion.

Essentially I want to use a String in Java that comes from client side JS. My JS alerts below work fine, however my JSON object is null or empty in my Servlet. I really just need one string passed to my servlet so I can run SQL queries, but am having a lot of trouble with it.

Thank you!

html file

<div class="jumbotron" id="jumboframe">
<h1>Enter your URL below</h1>
<input class="txtUrl" type="text" id="txtUrl" value="...." onfocus="if(this.value == '....') { this.value = ''; }"/>
<p><a class="btn btn-lg submitButton" href="testpage.html" onclick="getURL()" role="button">Start searching!</a></p>
</div>

<script>
function getURL() {
var urlString = document.getElementById("txtUrl").value;
var params = {url: urlString};


$.ajax({
type: "POST",
url: "testpage.html",
contentType: "application/json",
dataType: "text", // "JSON" here doesn't call alerts below
data: {
'url': urlString
},

success: function(data) {
alert("did it!");
alert(JSON.stringify(params));
alert(JSON.stringify(data));
}
});
}
</script>


Java servlet

public class JavaServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

PrintWriter out = response.getWriter();

StringBuilder builder = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}

out.println(builder.toString());
String url = request.getParameter("url");
Map<String, String[]> map = request.getParameterMap(); // empty {}
out.println(map.toString()); // null
out.println(url); // null


web.xml

<servlet>
<servlet-name>JavaServlet</servlet-name>
<servlet-class>path.to.my.JavaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JavaServlet</servlet-name>
<url-pattern>/testpage.html</url-pattern>
</servlet-mapping>


Thanks again

Answer

If you want to get a Json from the request data, then you should pass it as an String, then, your html might look like this (I've changed the servlet path to JavaServlet.do)

<div class="jumbotron" id="jumboframe">
            <h1>Enter your URL below</h1>
            <input class="txtUrl" type="text" id="txtUrl" value="...." onfocus="if(this.value == '....') { this.value = ''; }"/>
            <p><a class="btn btn-lg submitButton" href="#" onclick="getURL()" role="button">Start searching!</a></p>
        </div>

        <script>
            function getURL() {
                var urlString = document.getElementById("txtUrl").value;
                var params = {url: urlString};

                var jsonDataStr = JSON.stringify(params); // Here you get the json String
            $.ajax({
                    type: "POST",
                    url: "JavaServlet.do",
                    contentType: "application/json",
                    dataType: "text", // "JSON" here doesn't call alerts below * Because the servlet thrown an error, you should handle it *
                    data: jsonDataStr,
                    success: function(data) {
                        alert("Your URL is " + data); // **get the response text**
                        alert("Handle it");
                    },
                    error: function(data) { // Handle the error
                        alert(data.error().getResponseHeader());
                    }
                });
            }
        </script>

Now, the JavaServlet will receive a Json as String, you will have to parse it (Use a third party library like Gson).

public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

    PrintWriter out = response.getWriter();

    StringBuilder builder = new StringBuilder();
    BufferedReader reader = request.getReader();
    String line;
    while ((line = reader.readLine()) != null) {
        builder.append(line);
    }

    String jsonString = builder.toString(); // get the json from client
    UrlDto urlDto = new Gson().fromJson(UrlDto.class,jsonString); // parse you json to Java object
    String yourUrl = urlDto.getUrl();
    out.print(yourUrl); // **Set the response text**
    out.close();        

WEB.XML and UrlDto

class UrlDto {
    private String url;
    // G&S ...
}

    <servlet>
        <servlet-name>JavaServlet</servlet-name>
        <servlet-class>servlet.JavaServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>JavaServlet</servlet-name>
        <url-pattern>/JavaServlet.do</url-pattern>
    </servlet-mapping>

I hope this help you