javascriptjavajsonajax

Pass JSON object to Java Class without the use of a servlet


I have a form in an HTML, the values for which I am obtaining using JavaScript. I am converting it to an object as the following ( in JavaScript only):

var obj = {
            LogReference:logrefgenerator(),
            ReferenceNumber : ""
}

Now, I wish to send this object using Ajax(or any other for that matter) to a Java Class (NOT A SERVLET) which I have. I am trying to do this by :

    $.ajax({
    url: 'Resource',
    type: 'POST',                                                      
    dataType :'json',
    data: obj1,
    success: function(result) {
        alert('SUCCESS');
    },
    error: function(){
        alert('Error');
}});

But the code above somehow does not seem to be working. The F12 debugger(Browser's Debugging Tool) says : Error 404: Resource not found.

Any suggestions why this wont work? I wish to send the object from my JavaScript and receive it in my Java Code for further processing. Also, Please note that I am using IE.

EDIT: following is my Resource.java:

    public class Resource extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public Resource(String obj1) {
        // TODO Auto-generated constructor stub
        System.out.println(obj1);
        System.out.println("inside resource!");
    }
}

web.XML:

    <?xml version="1.0" encoding="ISO-8859-1"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="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_3_0.xsd" metadata-complete="true" version="3.0">
  <display-name>Welcome to Tomcat</display-name>
  <description>
     Welcome to Tomcat
  </description>
</web-app>

Solution

  • Your 404 indicates that the server cannot match a resource at the request URL. You say you do not wish to use a Servlet but are trying to POST to one.

    Your URL should be something like /logHandler/. In whatever Java web framework you are using you would then map the servlet (or some other handler) to that URL. You cannot address a class directly from the client basically.