Kyle
Kyle

Reputation: 1578

My ajax POST is not being sent to my servlet

I've been studying a lot about servlets and I've created one that should receive some positions from my web app, but due to my lack of experience with servlets I have no idea on how to fix it. Plus I don't know where I should put my HTML app anyway, I've heard that it should be in the WebContent folder, and there it is, but it doesn't work. Could you help me?

UPDATE: I'm trying to upload some information that will be transformed by my servlet into a txt file, to avoid uploading a file per say: "...I've created one that should receive some positions from my web app..."

Server: Apache Tomcat 7.0
Eclipse EE Mars

Thanks in advance.

My whole project is here: DropBox

P.S.: I posted the snippet below only for observation, but I can't use script because I don't own the businesses where the libraries are, if you want to see it check it on the link above this PostScript.

My HTML with AJAX

<body>
  <div id="navgrid">
    <div id="header">Header</div>
    <div id="tree1">
      <ul class="jqtree_common jqtree-tree">
        <li class="jqtree_common jqtree-folder">
          <div class="jqtree-element jqtree_common"><a class="jqtree_common jqtree-toggler">â–¼</a><span class="jqtree_common jqtree-title jqtree-title-folder">node1</span>
          </div>
          <ul class="jqtree_common ">
            <li class="jqtree_common">
              <div class="jqtree-element jqtree_common"><span class="jqtree-title jqtree_common">child1</span>
              </div>
            </li>
            <li class="jqtree_common">
              <div class="jqtree-element jqtree_common"><span class="jqtree-title jqtree_common">child2</span>
              </div>
            </li>
          </ul>
        </li>
        <li class="jqtree_common jqtree-folder">
          <div class="jqtree-element jqtree_common"><a class="jqtree_common jqtree-toggler">â–¼</a><span class="jqtree_common jqtree-title jqtree-title-folder">node2</span>
          </div>
          <ul class="jqtree_common ">
            <li class="jqtree_common">
              <div class="jqtree-element jqtree_common"><span class="jqtree-title jqtree_common">child3</span>
              </div>
            </li>
          </ul>
        </li>
      </ul>
    </div>
  </div>
  <script type="text/javascript">
  </script>

  <script>
    $(document).ready(function() {

      var POSITIONS;

      //var data is a dynamic JSON file that should be created in the backend.
      var data = [{
        label: 'node1',
        id: 1,
        children: [{
          label: 'child1',
          id: 2
        }, {
          label: 'child2',
          id: 3
        }]
      }, {
        label: 'node2',
        id: 4,
        children: [{
          label: 'child3',
          id: 5
        }]
      }];
      $('#tree1').tree({
        data: data,
        autoOpen: true,
        dragAndDrop: true
      });


      console.log($('#tree1').tree('toJson')); //This will give you the loading jqtree structure.

      $('#tree1').bind(
        'tree.move',
        function(event) {
          event.preventDefault();
          // do the move first, and _then_ POST back.
          event.move_info.do_move();
          console.log($(this).tree('toJson')); //this will give you the latest tree.
          POSITIONS = $(this).tree('toJson');
          alert(POSITIONS);
          $.post('http://sistema.agrosys.com.br/sistema/labs/CSS_HTML/', {
            tree: $(this).tree('toJson')
          });
          alert("done"); //this will post the json of the latest tree structure.
        }
      );

      var data = new FormData();
      data.append("JqTree", POSITIONS);
      alert('Sending: ' + POSITIONS);
      $.ajax({
        url: '/JqTree',
        type: 'POST',
        data: data,
        cache: false,
        dataType: 'json',
        processData: false,
        contentType: false,
        success: function(response) {
          alert("file has been successfully sent\n\n" + POSITIONS);
        },
        error: function(jqXHR, textStatus, errorThrown) {
          alert('ERRORS: ' + textStatus);
        }
      });

    });
  </script>
</body>

My Servlet

import java.io.IOException;
import java.io.PrintWriter;

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

public class Hello extends HttpServlet {
private static final long serialVersionUID = 1L;
public Hello() {}

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

    response.setContentType("text/html");
    PrintWriter out=response.getWriter();

    out.print("<html><body>");
    out.print("<h3>Hello Servlet</h3>");
    out.print("</body></html>");
}

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     String position = request.getParameter("JqTree");

     PrintWriter writer = new PrintWriter("Positions.txt", "UTF-8");
     writer.println(position);
     writer.close();
}

}

and my web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee"  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

<display-name>JqTree</display-name>


<welcome-file-list>


<welcome-file>index.html</welcome-file>    
<welcome-file>index.htm</welcome-file>    
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>

<servlet>

<description></description>

<display-name>Hello</display-name>
<servlet-name>Hello</servlet-name>
<servlet-class>Hello</servlet-class>
</servlet>

<servlet-mapping>  
<servlet-name>Hello</servlet-name>
<url-pattern>/Hello</url-pattern>
</servlet-mapping>

</web-app>

Upvotes: 0

Views: 393

Answers (1)

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51711

You need to change your AJAX call to

$.ajax({
    url: '/JqTree/Hello',

where /JqTree is the context root of your web app, plus /Hello which is the <url-pattern> configured for your Hello Servlet in your /WEB-INF/web.xml file.


  1. Your $.ajax() call is using post so you must remember that only doPost() would get called.
  2. Your doPost() doesn't return any output yet your $.ajax() call expects a dataType: 'json' back. This at times can cause the request to fail silently.
  3. I believe you're trying to upload files. If yes, you can't just read the file contents using request.getParameter(). You have to write your Servlet code differently to process multipart/form-data which varies whether you're running under a Servlet 3.0 or 2.x container.

Upvotes: 1

Related Questions