我是Client Server应用程序的初学者,并且在服务器端使用Java Servlet和在客户端使用JavaScript开发非常基本的应用程序。 我在客户端(index.html)使用AJAX的POST请求,如下所示:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.post("/Serve",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
}
);
});
});
</script>
</head>
<body>
<button>Send an HTTP POST request to a page and get the result back</button>
</body>
</html>
我正在使用GlassFish ver 4.1,Servlet代码(myServe.java)如下所示:
public class MyServe extends HttpServlet {
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException{
PrintWriter out = response.getWriter();
out.print("HI");
}
}
理想情况下,响应应该转到AJAX函数中的数据变量,它应该在按钮单击时显示,但警报屏幕只显示JS代码:
有谁能告诉我哪里出错了? web.xml文件也是这样的:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>MyServe</servlet-name>
<servlet-class>org.MyServe</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServe</servlet-name>
<url-pattern>/Serve</url-pattern>
</servlet-mapping>
</web-app>
答案 0 :(得分:1)
ajax请求是错误的控制器请通过从</ns3:endpoint>
移除/
来对ajax请求进行一些更正
Serve
我认为它会对你有所帮助。
答案 1 :(得分:0)
我还没有使用纯文本回复,建议使用xml,你可以尝试一下
public class MyServe extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException{
response.setContentType("text/plain;charset=UTF-8");
try(PrintWriter out = response.getWriter();){
out.print("HI");}
}
}
我不知道客户端(jquery)是否期望明确响应(有或没有头),但对于我提到的xml类型,设置内容类型是必不可少的。
<小时/> 另请注意,客户端正在调用/Serve/
/Serve
,而web.xml
已在http://[::1]/my_app/Serve
中注册
尝试将servlet称为完全限定名称(如/Serve
)而不是相对(http:://[::1]/Serve
)。如果网络应用尚未注册为根上下文,则客户将致电http://[::1]/my_app/Serve
而非实际/预期dat <-data.frame(fac1=factor(c("small","large"),levels=c("small","large","medium")),fac2=factor(c("medium","large"),levels=c("medium","large","small")),fac3=factor(c("small","medium"),levels=c("small","medium","large")))
Zl <- lapply(c("fac1","fac2","fac3"), function(nm) Matrix:::fac2sparse(dat[[nm]], "d",drop=F))
ZZ <- Reduce("+", Zl[-1], Zl[[1]])