1

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

bburc
  • 169
  • 1
  • 2
  • 13
  • 1
    Possible duplicate of [Retrieving JSON Object Literal from HttpServletRequest](http://stackoverflow.com/questions/1548782/retrieving-json-object-literal-from-httpservletrequest) You are correctly creating the StringBuilder with the POST data. See the link to see what else you might do with it. – Robert Moskal May 02 '16 at 02:09

1 Answers1

1

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

  • Thank you for the help! May I ask the point of changing the url-pattern for the servlet? I previously had it directed to a blank html file that will eventually show a response after the string has been processed and queried in postgresql. – bburc May 02 '16 at 04:53
  • I am just unsure how to handle the "yourUrl" String variable you made after that point. I initialized a new object from a class within the same package as the servlet, but get nothing from method calls, or any types of print statements – bburc May 02 '16 at 05:59
  • I've changed the url-pattern because it was a little confusing. Be aware that you're making an asynchronous call, so the response may not be available when you make the page redirect. The success and error should be handle by the sucess and error handlers in the ajax call. See the edit. Now the servlet set the response text and the ajax call receive it as 'data' in the success handler. – Gumby brain specialist May 02 '16 at 14:08
  • Excellent I got everything to work! This has been a huge headache this weekend for a big personal project, and I've never worked with server side Java before. I was missing the big picture regarding this issue and your code helped me see what was happening. Have my string in my source code ready for the next steps, thank you! – bburc May 02 '16 at 14:43