我想了解 html 页面如何调用 servlet 来向其主体添加元素,但我找不到正确的方法来实现这一目标,您能给我一个示例吗?这样做吗?
<小时/>示例:
假设有一个 html 页面,其中包含一个带有以下按钮的表单:
name="I am"
value="the button"
<小时/>
示例场景:
<小时/>
- click this button
- call a servlet
- add a message to this page saying "I am the button"
非常感谢您的指导。
block 引用>
最佳答案
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$("#btn").click(function() {
$.post("buttonServlet", function (response) {
alert(response);
});
});
</script>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>My Button</title>
</head>
<body>
<input type="button" name="btn" id ="btn" value="The Button" />
</body>
</html>
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
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("/buttonServlet")
public class ButtonServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("I am the button");
}
}
关于java - HttpServlet - 将上下文添加到 html 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28163233/