以前一直不太清楚web后台和前端是如何进行交互的。经过这几天的捣腾大概已经搞明白了之间是如何进行数据传递的了。
项目的目录结构:
前端部分
add.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB2312">
<title>test</title>
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var xml_data = {
"tag":"2","sql":"select * from tableA limit 1;","base":"4"}
$(function(){
$("#btn").click(function(){
$.ajax({
url: "http://localhost:8080/HtmlProject/servlet/addServlet",
type:"POST",//请求方式POST
data:"json1="+JSON.stringify(xml_data),//传过去后台的json 这里注意前面加一个"json1="
dataType:"json", //预期从服务器中接受的数据类型
error:function(XMLHttpRequest, textStatus, errorThrown){
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
},
success:function(data){
alert("success");
}
});
});
});
</script>
</head>
<body>
<form id="form1" method="post">
<input type="button" value="查询" id="btn"/>
<ul id="ul1"></ul>
</form>
</body>
</html>
前端的html页面有几点要注意的:
- 要记得引入jQuery文件
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
苦逼的我好几次忘了引入这个js文件,导致ajax提交请求的时候没有任何反应 var xml_data = {"tag":"2","sql":"select * from tableA limit 1;","base":"4"}
这个是要向后台发送请求时发送过去的json,在ajax中的申明data时注意加个“json1=”,这样子在后台接收时通过request.getParameter(“json1”)就可以获得前端传过来的json了。
这里前端的html只是做了一个简单的按钮进行验证,其实可以把后台获取得到的json进行解析然后将对应的数据显示出来,但是在这里就不进行这一步操作了。
后台部分
数据库结构(需要操作多个数据库)
web.xml的配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the description of my