【问题标题】:Receive POST request sending JSON in jsp from javascript从javascript接收在jsp中发送JSON的POST请求
【发布时间】:2017-07-10 04:27:07
【问题描述】:

我制作了一个带有输入的 HTML 页面。我通过 javascript 获取值,创建一个 JSON,然后我想通过 ajax 发送它。我还有一个 JSP 应用程序,它在 java 中运行一个方法,接收这个 JSON 并读取它,以便将它存储在数据库中。问题是我不知道如何在我的 jsp 应用程序中接收来自 ajax 的调用并将其发送到我在 java 中的方法。有人可以帮我弄这个吗?

Javascript:

alert("I am about to POST this:\n\n" + dat);

$.ajax({
    url: '/path/to/file',
    type: 'POST',
    dataType: 'JSON',
    data: dat,
})
.done(function() {
    console.log("success");
})
.fail(function() {
    console.log("error");
})
.always(function() {
    console.log("complete");
});
`

JSP:

'<%@ page language="java" import="connection.JsonHandler" %>
<%
String json = request.getParameter("dat");;
JsonHandler gson = new JsonHandler();
gson.ReadJson(json);
%>

Java:

package connection;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.GsonBuilder;
import entidades.User;
import java.lang.reflect.Type;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;

public class JsonHandler {
    public Gson CreateJson(String values) {
        Gson gson = new GsonBuilder().create();
        gson.toJson("Hello", System.out);
        gson.toJson(123, System.out);   
        return gson;
    }

    public void ReadJson(String json){
        Gson gson = new Gson();
        Type type = User.class;
        gson.fromJson(json,type);
    }
}

【问题讨论】:

  • 你试过什么代码?您没有发布任何代码
  • 对不起,我真的很陌生,所以我没有做太多

标签: javascript java json ajax jsp


【解决方案1】:

您可以编写一个 servlet,它将接受您的 POST 请求。请参考I couldn't get the POST value in servlet page?How to get the data from ajax request in servlet page?

【讨论】:

    猜你喜欢
    • 2016-09-29
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    • 2012-12-04
    • 2017-04-02
    • 1970-01-01
    相关资源
    最近更新 更多