当前位置: 首页 > 知识库问答 >
问题:

如何在javascript和servlet之间发送和接收json数据?

崔单弓
2023-03-14
    null
//first I add the listener
document.querySelector('#login_form').addEventListener('submit',(e)=>{
    e.preventDefault();
    login_send(e.target);
});
//then the function to run on submit
function login_send(form){
    console.log(form2json(form));
    //I get the content: {"email":"a@b.c","pass":"aoeu"}
    fetch('login',{
        method:'POST',
        headers:{
            'Accept':'application/json, text/plain, */*',
            'Content-type':'application/json'},
        body: form2json(form)
    })
    .then((res) =>res.json())
    .then((data) => {
        console.log("I got: "+data);//for now, just printing the data
    })
    .catch((err) => console.error(err));
}
//this is my handcrafted "form to json" string formatter,
//surely there is a better (correct?) way of doing it.
function form2json(form){
    let js="{";
    let last=form.length-1;
    for (i=0;i<last;i++){
        js+="\""+form.elements[i].name+"\":\""+form.elements[i].value+"\"";
        if(i+1<last) js+=",";
    }
    js+="}";
    return js;
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>Login Servlet</servlet-name>
        <servlet-class>com.cactusstore-1.ui.Login</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Login Servlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
</web-app>
...
import javax.json.*;
...
public class Login extends HttpServlet {
    protected void processRequest(HttpServletRequest req,
            HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("application/json;charset=UTF-8");
        try (PrintWriter out = res.getWriter()) {
            //an object with three fields.
            User u = new User(
                    req.getParameter("email"),
                    "10010099",
                    req.getParameter("pass")
            );
            //construct json answer.
            //based on https://www.youtube.com/watch?v=BPMVC999HTs
            JsonObject root;
            JsonObjectBuilder rootBuilder = Json.createObjectBuilder();
            JsonObjectBuilder userBuilder = Json.createObjectBuilder();
            userBuilder
                    .add("name",u.getName())
                    .add("email", u.getEmail())
                    .add("sid", u.getSId());

            root = rootBuilder.add("login", userBuilder).build();
            //write response to out
            out.println(root);
            out.flush();
            out.close();
        }
    }
}

我希望得到json,但我得到了这个错误:

custom.js:23 SyntaxError: Unexpected end of JSON input

看起来我的servlet没有返回任何东西。如果我用res.json()更改res.text(),我什么也得不到。如果我用out.println(“{\”name\“:\”john\“}”)更改out.println(root),我仍然一无所获。

谢谢:)(请客气,这是我第一次学习这些语言。而我已经很困惑了)。

public class User {
    private String email;
    private final String session_id;
    private String name;
    public User(String email, String id, String name) {
        this.email = email;
        this.session_id= id;
        this.name = name;
    }
    public String getName() {return name;}
    public String getEmail(){return email;}
    public String getSId()  {return session_id;}
    public void   setName (String name) {this.name=name;}
    public void   setEmail(String email){this.email=email;}
}
25-May-2019 01:11:57.354 SEVERE [http-nio-8080-exec-1] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [Login Servlet] in context with path [/cactusstore-1] threw exception [Servlet execution threw an exception] with root cause
    java.lang.ClassNotFoundException: javax.json.Json
        at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1363)
        at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1186)
        at com.cactusmania.ui.Login.processRequest(Login.java:66)
        at com.cactusmania.ui.Login.doPost(Login.java:93)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:836)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1839)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.base/java.lang.Thread.run(Thread.java:834)
System.out.println("YOUR EMAIL: "+req.getParameter("email"));

我在catalina.out中获得您的电子邮件:null

再次感谢你对我的耐心和时间。

共有1个答案

贝钧
2023-03-14

我看到的第一个问题是异常:java.lang.ClassNotFoundException:javax.json.json,您需要在类路径中包含它。在your_project/web/web-inf/lib文件夹中包含您正在使用的javax.json-1.0.jarjar。

YOUR_PROJECT
|
|__web
   |
   |__WEB-INF
      |
      |__lib
         |  javax.json-1.0.jar

这样,当您导出war文件并将其部署到tomcat上时,jar wil在类路径上可用。

第二个问题是,您将JSON传递给服务器,并尝试使用req.getParameter获取参数,但您真正需要的是解析JSON并获取如下所示的值:

 StringBuilder sb = new StringBuilder();
 BufferedReader br = req.getReader();
 String str = null;
 while ((str = br.readLine()) != null) {
     sb.append(str);
 }

 String json = sb.toString();


 JsonReader jsonReader = Json.createReader(new StringReader(json));
 JsonObject jsonObject = jsonReader.readObject();
 jsonReader.close();

 // an object with three fields.
 User u = new User(jsonObject.getString("email"), "10010099", jsonObject.getString("pass"));
public class Login extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("application/json;charset=UTF-8");
        try (PrintWriter out = res.getWriter()) {

            StringBuilder sb = new StringBuilder();
            BufferedReader br = req.getReader();
            String str = null;
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }

            String json = sb.toString();


            JsonReader jsonReader = Json.createReader(new StringReader(json));
            JsonObject jsonObject = jsonReader.readObject();
            jsonReader.close();

            // an object with three fields.
            User u = new User(jsonObject.getString("email"), "10010099", jsonObject.getString("pass"));

            // construct json answer.
            // based on https://www.youtube.com/watch?v=BPMVC999HTs
            JsonObject root;
            JsonObjectBuilder rootBuilder = Json.createObjectBuilder();
            JsonObjectBuilder userBuilder = Json.createObjectBuilder();
            userBuilder.add("name", u.getName()).add("email", u.getEmail()).add("sid", u.getSId());

            root = rootBuilder.add("login", userBuilder).build();
            // write response to out
            out.println(root);
            out.flush();
            out.close();
        }
    }
}
 类似资料:
  • 本文向大家介绍如何与服务器之间发送和接收JSON数据,包括了如何与服务器之间发送和接收JSON数据的使用技巧和注意事项,需要的朋友参考一下 JavaScript可以将网络请求发送到服务器并加载JSON。JS使用称为AJAX的东西来做到这一点。AJAX代表异步JavaScript和XML。JS具有一个API,可提取以将GET(接收)和POST(发送)信息发送到服务器。 您可以通过以下方式使用访存来获

  • 我正在做一个基本的投票系统,其中我有2个HTML页面(都在同一个域上)。在第1页上有两个按钮,用户可以从中选择一个。第2页我想在一个图形中显示所选的选项。目标是,如果在第1页上点击了一个按钮,第2页上的数据就会自动更新,而不会刷新整个页面。 为了做到这一点,我尝试将单击的选项保存在LocalStorage中。我通过使用编写变量来获得数据。但是,当我得到数据时,我必须手动刷新第2页,以便结果显示。有

  • 本文向大家介绍JavaScript 通过POST发送和接收JSON数据,包括了JavaScript 通过POST发送和接收JSON数据的使用技巧和注意事项,需要的朋友参考一下 示例 6 提取请求承诺最初将返回Response对象。它们将提供响应头信息,但它们不直接包含响应主体,而响应主体可能尚未加载。可以使用诸如Response对象上的方法来等待响应主体加载,然后对其进行解析。.json()

  • 问题内容: 使用Ajax,我试图仅将Json数据发送到节点服务器,不进行任何处理,仅在发送时发出警报,在接收到时发出警报: 这是我的html5:具有onclick函数的简单按钮,可触发该函数使用ajax调用 这是节点服务器的一部分:用于创建服务器并侦听某些操作 没有警报被触发,所以我不认为ajax正在尝试发送信息。 问题答案: 在服务器端尝试此操作: 在客户端: 希望这对你有用

  • 问题内容: 我正在尝试为请求和响应应用程序创建桌面客户端。 我能够轻松地执行GET请求。但是我想知道是否有人可以帮助我确定如何进行JSON请求和响应。并将其解析为字符串,从那里我可以锻炼如何将其全部切开 问题答案: Json.net在.net世界中无处不在。