总所周知,servlet一般是用在操作与后台数据有关的逻辑处理,而jsp的本质就是一个servlet,是不是可以用一个jsp专门处理简单的、不需要涉及到数据库的请求?
这个想法仅供学习,实际上现在开发的思想越来越趋向于前后端分离,模块解耦合,所以也造成了jsp慢慢被取代了,因为页面上镶嵌大量的代码对于后期的维护来说是致命的
这里有两个jsp文件,一个是展示效果的jsp,一个处理数据的jsp。还需要将这两个文件部署在Tomcat上,这个过程很简单就不再累赘了
展示效果的jsp
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" session="false"%>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title>表格</title>
</head>
<body>
<table id="myTable" cellpadding="0" cellspacing="1">
<thead>
<tr>
<th style="text-align: center; width: auto;">姓名</th>
<th style="text-align: center; width: 120px;">生日</th>
<th style="text-align: center; width: 300px;">操作</th>
</tr>
</thead>
<tbody id="tableData">
</tbody>
</table>
<script>
//ajax从获取数据
$(function () {
$.ajax({
type: "get",
//这个路径需要根据自己部署的情况来写JavaWeb是项目的名字
url: "http://localhost:8080/JavaWeb/data.jsp?flat=getFaiList",
data: {},
success: function (result) {
list = result;
var tableTtml = "";
for(var i in list){
tableTtml += "<tr>";
tableTtml += "<td>" + list[i].name + "</td>";
tableTtml += "<td>" + list[i].birthday + "</td>";
tableTtml += "<td>";
tableTtml += "<input type='button' value='上移' οnclick='moveUp(this)'>";
tableTtml += "<input type='button' value='下移' οnclick='moveDown(this)'>";
tableTtml += "<input type='button' value='删除' οnclick='remove(this)'>";
tableTtml += "<input type='button' value='修改' οnclick='edit(this)'>";
tableTtml += "<input type='button' value='保存' οnclick='keep(this)'>";
tableTtml += "</td>";
tableTtml += "</tr>";
}
$("#tableData").html(tableTtml);
}
})
});
</script>
</body>
</html>
第二个jsp
<%@page import="import java.util.*"%>
<%@page contentType="application/json;charset=UTF-8" language="java"%>
<%
String output = "";
String flat = request.getParameter("flat");
if (flat == null) {
return;
}
else if (flat.equals("getFaiList")) {
output = getFaiList();
}
//返回结果
out.print(output);
%>
<%!
public String getFaiList(){
List<Map<String, String>> list = new LinkedList<>();
Map<String, String> map1 = new HashMap<>();
map1.put("name","张三");
map1.put("birthday", "2010.1.1");
Map<String, String> map2 = new HashMap<>();
map2.put("name","张三");
map2.put("birthday", "2010.1.1");
Map<String, String> map3 = new HashMap<>();
map3.put("name","张三");
map3.put("birthday", "2010.1.1");
list.add(map1);
list.add(map2);
list.add(map3);
return list.toString();
}
%>