javascript - 将 JSON 对象传递给 Java 类,而不使用 servlet

标签 javascript java json ajax web

我有一个 HTML 格式的表单,我使用 JavaScript 获取其值。我将其转换为对象,如下所示(仅在 JavaScript 中):

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

现在,我希望使用 Ajax(或任何其他相关方法)将此对象发送到 Java(不是 SERVLET) 我有。我正在尝试通过以下方式做到这一点:

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

但是上面的代码似乎不起作用。 F12 调试器(浏览器的调试工具)显示:错误 404:找不到资源。

有什么建议为什么这行不通吗?我希望从我的 JavaScript 发送该对象并在我的 Java 代码中接收它以进行进一步处理。另外,请注意我使用的是 IE

编辑: 以下是我的 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>

最佳答案

您的 404 表示服务器无法匹配请求 URL 中的资源。您说您不想使用 Servlet,但正在尝试 POST 到 Servlet。

您的 URL 应类似于/logHandler/。在您使用的任何 Java Web 框架中,您都可以将 servlet(或其他一些处理程序)映射到该 URL。基本上你不能直接从客户端处理一个类。

关于javascript - 将 JSON 对象传递给 Java 类,而不使用 servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32473634/

相关文章:

javascript - 将多个项目添加到上下文菜单

javascript - 未能在 for 循环中使用 setTimeout

ios - 如何根据页码排列 JSON 解析数组?

json - 如何在 Glassfish 4 上创建一个简单的 JSON Jersey 2.x RESTful Web 服务?

java - 如何通过COM调用Java方法

java http请求所需的字符串参数 'Username'不存在

ASP.NEt 在 IE 中滚动时 Tab 键顺序丢失

javascript - mysql在报告时间之间工作时间不方便

java - 如何为 Vaadin 应用程序的 UI 组件生成唯一 ID?

java - 运行任何 LWJGL 代码时出现 EXCEPTION_ACCESS_VIOLATION