各位好,小弟有两个档案,一个是tryJSP.jsp,另一个是servlet档(TryServlet.java)
JSP档里面有个按钮,点下去后会用$.ajax post的方式连到Servlet档
$.ajax post的url是 "/Eclipse专案的名称/TryServlet",
Servlet档里面有宣告一个字串(String ss = "Hello"),
然后Servlet会传回该字串到JSP档案,JSP档案会将该字串使用alert的方式显示出来。
只是现在按下去后没有success,而是跑到$.ajax的error区段,且console显示下列讯息:
java.lang.ClassNotFoundException: TryServlet
想请问该怎么解决这个问题,有把url改成"/TryServlet",但结果还是一样 ~"~
程式码如下:
【TryServlet.java】
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public TryServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String send_back = "Hello";
PrintWriter out = response.getWriter();
out.print(send_back);
out.flush();
out.close();
}
}
【tryJSP.jsp】
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript"
src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<title>Insert title here</title>
</head>
<body>
<input type="button" id="query" value="Click me" />
<script type="text/javascript">
$("#query").click(function() {
$.ajax({
type : "POST",
url : " /MyProjectName/TryServlet",
data : {
},
dataType : "text",
success : function(string_back) {
alert(string_back);
},
error : function(xhr, textStatus, error) {
console.log(xhr);
alert("连线错误,请重新查询");
console.log(error);
},
//请求完成时执行的函式(不论结果是success或error)
complete : function() {
alert("done");
}
});
});
</script>
</body>
</html>
【web.xml】
..
..
<servlet>
<description></description>
<display-name>TryServlet</display-name>
<servlet-name>TryServlet</servlet-name>
<servlet-class>TryServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TryServlet</servlet-name>
<url-pattern>/TryServlet</url-pattern>
</servlet-mapping>
<servlet>
..
..