1、jsp页面代码
使用jquery封装好的方法调用ajax更加方便,所以别忘记导入jquery,其中,url设置为接收请求的后台页面, 传输的数据类型为json格式,json内容可以从表单中获取,提交方式为post,在回调函数中根据返回值写对应的代码即可,比如页面跳转、更改页面某一个元素等等。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax Test</title>
<script src="js/jquery-3.3.1.js"></script>
<script src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
$.ajax({
url : "${pageContext.request.contextPath}/DoLogin", //后台查询验证的方法
dataTpye : "json",
data : {
"name" : $('#name').val(),
"pwd" : $('#pwd').val()
},
type : "post",
success : function(msg) {
//根据后台返回前台的msg给提示信息加HTML
if ("true" == msg) {
alert("success");
} else {
alert("failed");
}
},
error:function(){ //请求失败的回调方法
alert("请求失败,请重试");
}
});
});
});
</script>
</head>
<body>
<form action="" method="POST">
<input type="text" id="name">
<input type="text" id="pwd">
<input type="button" value="submit" id="btn">
</form>
<a href="${pageContext.request.contextPath}/DoLogin?name=admin&pwd=hello">测试链接</a>
</body>
</html>
2、servlet代码
使用response对象进行响应。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String path = request.getContextPath();
response.setContentType("text/html;charset=utf-8");
//response.setContentType("application/text; charset=utf-8");
request.setCharacterEncoding("utf-8");
System.out.println("in servlet");
PrintWriter out = response.getWriter();
String name = (String)request.getParameter("name");
String password = (String)request.getParameter("pwd");
if(name.equals(password)){
out.print("true");
}
else{
out.println("false");
}
System.out.print("cross");
}
结果图