我想从servlet响应在JSP页面被捕获。我使用JavaScript这一点。下面是代码:
test Servlet.Java:
package com.test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
String testString = "Load Check";
//request.setAttribute("test", testString);
//request.getRequestDispatcher("").include(request, response);
response.getWriter().write("Test Success");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
test.jsp的
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Test JSP</title>
</head>
<body>
<script type="text/javascript">
function callServeltAndGetResponse(){
var servlet = new XMLHttpRequest();
servlet.onreadystatechange = function(){
var servletResponse = servlet.responseText;
document.getElementById("response").innerHTML = servletResponse;
}
servlet.open('GET','TestServlet',true);
}
</script>
<form onSubmit="javascript:callServletAndGetResponse()">
<input type=submit>
</form>
<div id="response"></div>
</body>
</html>
在上面的jsp页面中,divcontent不是由JavaScript虽然写的servlet的响应变化。我究竟做错了什么?
你需要阻止默认表单提交过程或页面将重新加载
尝试:
<form onSubmit="javascript:callServletAndGetResponse(); return false">