我无法使用html / javascript在客户端之间进行通信,将html形式的数据发送到servlet,然后servlet重播json。我不知道我在哪里犯错。
想法是这样的:
console.log()
-正在使用它)从元素获取数据的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>
Servlet 我将doGet()和doPost()重定向到processRequest(),这是在创建新的“ Web应用程序”时在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.json()
更改为res.text()
,将一无所获。
如果将out.println(root)
更改为out.println("{\"name\":\"John\"}");
,我仍然什么也没得到。
谢谢:) (请客气,这是我第一次使用所有这些语言。我已经很困惑了。)
班级用户。添加班级以保持完整性。
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;}
}
由于@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
。
再次感谢您的耐心和耐心。
答案 0 :(得分:1)
第一个问题,我看到的是例外情况:java.lang.ClassNotFoundException: javax.json.Json
您需要将其包括在类路径中。
对于我使用过javax.json
的情况,请将YOUR_PROJECT/web/WEB-INF/lib
jar包含在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();
}
}
}
答案 1 :(得分:0)
不能为您建立json格式!
html中的每个表单都有一个称为onSubmit的函数。您可以使用它。
<form onsubmit="login_send()">
<button type="submit"></button>
</form>