gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 22:57:47 30 4
gpt4 key购买 nike

问题

我无法开始使用 html/javascript 将表单数据作为 json 发送到 servlet,然后 servlet 重放 json 的客户端之间的通信。我不完全知道我在哪里做错了。

思路是这样的:

  • JavaScript 从表单中获取数据,将其解析为 json,然后将其发送到 servlet。
  • 在服务器端,servlet 读取发送的json,采取一些行动。生成另一个 json,并重播它。
  • 回到客户端,读取 json 并以此为基础绘制一些 html。 (现在,我只是console.log()-ing)

客户端

从元素获取数据的 javascript 代码:

//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;
}

服务器

web.xml 文件,将 url 连接到 java 类:

<?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>

小服务程序当您创建新的“Web 应用程序”时,我将 doGet() 和 doPost() 重定向到 processRequest(),这是 Netbeans 中默认给出的。

...
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.text() 更改 res.json(),我什么也得不到。如果我将 out.println(root) 更改为 out.println("{\"name\":\"John\"}");,我仍然会得到什么都没有。

谢谢 :)(请客气,这是我第一次接触所有这些语言。我已经很困惑了)。


编辑1

Class User 添加类以确保完整性。

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;}
}

编辑2

感谢@vladwoguer,我找到了日志,现在我知道我在使用 Json 类时遇到了问题,奇怪的是 Netbeans 会自动完成函数名称,并且不会在编辑器中显示任何错误。

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)

如果我注释掉所有 Json 包含及其使用,只留下:

System.out.println("YOUR EMAIL: "+req.getParameter("email"));

我在 catalina.out 中获取了 YOUR EMAIL: null

再次感谢您花时间和耐心等待我。

最佳答案

第一个问题 我看到的是异常:java.lang.ClassNotFoundException: javax.json.Json您需要将其包含在类路径中。将您正在使用的 javax.json jar 包含在 YOUR_PROJECT/web/WEB-INF/lib 文件夹中,在我的例子中我使用了 javax.json-1.0.jar

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

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

第二个问题是您将 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();
}
}
}

关于javascript - 如何在javascript和servlet之间发送和接收json数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56301890/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com