我想理解 html页面如何调用servlet来向其主体添加元素但我找不到正确的方法来实现,你可以给我或参考我的一个例子这样做?
示例:
假设有一个html页面,其中包含一个包含以下按钮的表单:
name="I am"
value="the button"
示例场景:
- 点击此按钮
- 调用servlet
- 在此页面上添加一条消息,上面写着“我是按钮”
醇>
非常感谢任何指导。
答案 0 :(得分:2)
<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>
&#13;
<!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>
&#13;
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");
}
}
答案 1 :(得分:0)
您可以使用Ajax执行此操作。
在你的html页面中包含一个按钮,
<input type="submit" id="button1" value="the button" name="I am" onclick="showMsg()" />
实施ajax,
function showMsg() {
var buttonMsg = document.getElementById("button1").name + document.getElementById("button1").value;
$.ajax({
url: "yourservlet",
type: "post",
data:{'msgVar': buttonMsg} ,
cache: false,
success: function (data) {
//depends on the method you want to show your message
//the variable data contain the message you want
alert(data); //to show in popout message
}
});
}
假设您的servlet POST方法包含以下变量
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String message = request.getparameter("msgVar");
out.println(message);