在看这篇文章前,新手可以参考http://www.runoob.com/jsp/eclipse-jsp.html熟悉下开发环境Eclipse jsp/servlet一节写的很清楚了
1.任务描述:
web页面需要一张表格,可以新增,和删除某一项,大概效果如下
点击新增,会新建一条数据插入后台数据,并在表中显示。
点击删除,会删除后台数据中的对应数据,并移除表中对应数据。
是不是很简单的任务,哈
2.需求分析
首页界面上用一个table,向后台请求数据,然后动态填充到表中,一条条往表中插入。插入和删除直接操作后台数据,然后刷新界面即可。
后台数据保存可以用多种方式,这里简单用文件存储,为了方便解析,结构可以采用xml或者json。这里选择json
3.实现过程
项目创建:
在eclipse中新建动态web项目
总体结构如下:
前端部分:
1)先做一个表头和新增按钮
<body>
<table width="100%" height="300px" border="1px" id="tad">
<tr>
<th>设备号</th>
<th>设备名称</th>
<th>操作</th>
</tr>
</table>
<button onClick="addItem()">新增锁</button>
</body>
2)页面第一次加载时用js查询已有数据并动态插入表中,查询的结果定位json数组:[{id:1,name:”xxx”},{id:2,name:”xxx”}]
//前端程序片段,通过ajax获取json数据
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var result = xmlhttp.responseText;
//js自带对json的解析
var datas = JSON.parse(result);
var table = document.getElementById("tad");
//遍历数组并逐条插入
for ( var i in datas) {
oneRow = table.insertRow();//插入一行
cell1 = oneRow.insertCell();//单单插入一行是不管用的,需要插入单元格
cell2 = oneRow.insertCell();
cell3 = oneRow.insertCell();
cell1.innerHTML = datas[i].id;
cell2.innerHTML = datas[i].name;
cell3.innerHTML = "<button onclick='deleteItem(this)'>删除</button>";
}
}
}
xmlhttp.open("GET", "HelloServlet", true);
xmlhttp.send();
3)删除事件。这里简单实现通过条目位置删除对应数据,最早的时候犯了个低级错误,参数直接传入了下标位置,然后删除,结果出现了一些问题,可以思考下会出什么问题。修正后传入节点本身,查询位置,然后删除:
function deleteItem(node){
//通过parentNode获取父节点
var index=node.parentNode.parentNode.rowIndex;
//ajax的post请求过程
var xmlhttp = new XMLHttpRequest();
var param = "index="+index;
//回调方法
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//删除成功后刷新当前页面
window.location.reload();
}
}
xmlhttp.open("POST", "DelServlet", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(param);
}
4)插入事件
function addItem(){
var xmlhttp = new XMLHttpRequest();
var param = "id=666&name=锁1";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//刷新当前页面
window.location.reload();
}
}
xmlhttp.open("POST", "AddServlet", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(param);
}
这样前端基本完成,别忘了写个漂亮的表格样式css。之所以直接刷新页面是因为,加载页面会执行1)和2)这样数据的变化可以直接显示出来,当然也可以手动操作dom去插入或删除节点,效果一样。
后台部分:这部分是java代码,需要相关基础
1)首先准备好数据存取的工具类,因为我们是存在文件里面,所以封装一个文件操作类FileUtil:
/***
* 存:将数据写入文件,覆盖原来的内容
*
* @param filePath
* 文件的路径
* @param content
* 保存的内容;
* @return
*/
public static boolean saveFile(String filePath, String content) {
boolean successful = true;
FileOutputStream fout = null;
try {
fout = new FileOutputStream(new File(filePath), false);
fout.write(content.getBytes());
} catch (FileNotFoundException e1) {
successful = false;
} catch (IOException e) {
successful = false;
} finally {
if (fout != null) {
try {
fout.close();
} catch (IOException e) {
}
}
}
return successful;
}
/***
* 取:读出当前数据
*/
public static String loadFile(String filePath, String charset) {
FileInputStream fin = null;
StringBuffer sb = new StringBuffer();
try {
fin = new FileInputStream(new File(filePath));
byte[] buffer = new byte[1024];
int start = -1;
while ((start = fin.read(buffer)) != -1) {
sb.append(new String(buffer, 0, start, charset));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fin != null) {
try {
fin.close();
} catch (IOException e) {
}
}
}
return sb.toString();
}
一个存,一个取,基本上这两个方法足够了
2)准备一个实体类LockBean,作为处理单元
/**
* 锁的实体类
*/
public class LockBean {
public int id;
public String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
3)准备数据处理的逻辑FileHelper,无非是增删改查
/**
* 本地文件操作类
* @author cd
*
*/
public class FileHelper {
private FileHelper(){};
private final String JSON_FOLDER = "/Users/cd/file/";
private final String LOCK_JSON_NAME= "lock.json";
private static final String CHARSET= "utf-8";
private static FileHelper fileHelper;
public static FileHelper getInstance(){
if(fileHelper==null){
fileHelper = new FileHelper();
}
return fileHelper;
}
//增
public void addLock(LockBean lock){
File file = new File(JSON_FOLDER,LOCK_JSON_NAME);
ArrayList<LockBean> lockList = new ArrayList();
if(!file.exists()){
System.out.println("file not exist");
}else{
//查询,并解析为arraylist
String json = FileUtil.loadFile(JSON_FOLDER+LOCK_JSON_NAME,CHARSET);
JSONArray jsonArray = JSONArray.fromObject(json);
System.out.println("get jsonArray:"+jsonArray.toString());
lockList = (ArrayList<LockBean>) JSONArray.toList(jsonArray);
}
//向arraylist中添加数据
lockList.add(lock);
//将arraylist转回成json并保存
JSONArray jsonArray = JSONArray.fromObject(lockList);
String json = jsonArray.toString();
System.out.println("save json:"+json);
FileUtil.saveFile(JSON_FOLDER+LOCK_JSON_NAME, json);
}
//删
public void deleteLock(LockBean lock){
}
public void deleteLock(int index){
//查询
String json = FileUtil.loadFile(JSON_FOLDER+LOCK_JSON_NAME,CHARSET);
JSONArray jsonArray = JSONArray.fromObject(json);
System.out.println("get jsonArray:"+jsonArray.toString());
ArrayList<LockBean> lockList = (ArrayList<LockBean>) JSONArray.toList(jsonArray);
//删除
lockList.remove(index);
//保存
JSONArray jArray = JSONArray.fromObject(lockList);
String json1 = jArray.toString();
FileUtil.saveFile(JSON_FOLDER+LOCK_JSON_NAME, json1);
}
//改
public void updateLock(LockBean lock){
}
//查
public ArrayList<LockBean> getLockList(){
ArrayList<LockBean> lockList = new ArrayList();
//查询
String json = FileUtil.loadFile(JSON_FOLDER + LOCK_JSON_NAME,CHARSET);
JSONArray jsonArray = JSONArray.fromObject(json);
System.out.println("get jsonArray:"+jsonArray.toString());
lockList = (ArrayList<LockBean>) JSONArray.toList(jsonArray);
return lockList;
}
public String getLockListString(){
//查询
String json = FileUtil.loadFile(JSON_FOLDER + LOCK_JSON_NAME,CHARSET);
JSONArray jsonArray = JSONArray.fromObject(json);
return jsonArray.toString();
}
}
这里仅仅用增删足够了。由于java没有带对json的解析,这些json解析的方法都是第三方库文件的,要将其导入项目。web项目的第三方文件都要导入到WEB-INF中的lib,否则不会生效。
4)然后是servlet,作为业务逻辑层
HelloServlet.java实现获取当前已有的数据,封装成json结构并返回给前端。由于我们存入文件中的数据已经是json了,这里省了一步。
/**
* Servlet implementation class HelloServlet
*/
@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public HelloServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// 使用 GBK 设置中文正常显示
response.setCharacterEncoding("UTF-8");
String str = FileHelper.getInstance().getLockListString();
response.getWriter().write(str);
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
AddServlet实现添加操作,后面只贴核心代码了
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//防止中文乱码,这样最保险
response.setContentType("text/html;chartset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
// request.getParameter()获取jsp页面提交的数据
String id = request.getParameter("id");
String name =request.getParameter("name");
LockBean lock = new LockBean();
lock.setId(Integer.valueOf(id));
lock.setName(name);
FileHelper.getInstance().addLock(lock);
}
DelServlet实现删除操作
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//防止中文乱码,这样最保险
response.setContentType("text/html;chartset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
// request.getParameter()获取jsp页面提交的数据
String index = request.getParameter("index");
FileHelper.getInstance().deleteLock(Integer.valueOf(index)-1);
}
如此一个简单的动态web应用就完成了。打完收工。