本文共 2777 字,大约阅读时间需要 9 分钟。
到这一步,已经算是完成很多一部分内容了,后端代码也就差不多写完了。在这里需要注意的是,数据要和前端需求相结合,所以在开发过程中往往是将增删改查分成四个部分来写,分别结合前端来边修改边写后端,但是在这里由于篇幅有限,我将前端和后端都写好了,这是后端的action内容,供大家参考:
package action;import employee.emp;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionSupport;import com.sun.net.httpserver.HttpServer;import util.jdbcDAO;import jdk.nashorn.internal.ir.RuntimeNode;import org.apache.struts2.ServletActionContext;import java.util.ArrayList;public class empaction extends ActionSupport { private static final long serialVersionUID = 1L; public emp getEmployee() { return employee; } public void setEmployee(emp employee) { this.employee = employee; } private emp employee = new emp(); public ArrayListgetEmployees() { return employees; } public void setEmployees(ArrayList employees) { this.employees = employees; } private ArrayList employees = new ArrayList (); public int getId() { return Id; } public void setId(int id) { Id = id; } private int Id; public int getNewID() { return newID; } public void setNewID(int newID) { this.newID = newID; } private int newID; public String listAll() { employees = jdbcDAO.queryAll(); ActionContext.getContext().put("employees", employees); System.out.println(employees.size()); return "success"; } //这是跳转到确认页的Action public String toAdd() { employees = jdbcDAO.queryAll(); //以下是为了添加人的时候确认新增人id int size = employees.size(); emp emp = employees.get(size-1); newID = emp.getId()+1; System.out.println("id="+newID); ActionContext.getContext().put("newID", newID); return "success"; } public String addEmp() { System.out.println(employee); jdbcDAO.insert(employee); return "success"; } public String editEmp() { System.out.println("更新操作"); System.out.println(employee); jdbcDAO.update(employee); return "success"; } public String selectEmp() { System.out.println(Id); employee = jdbcDAO.select(Id); System.out.println(employee);// ActionContext.getContext().setSession(employee); ActionContext.getContext().put("emp",employee); return "success"; } public String deleteEmp() { jdbcDAO.delete(Id); return "success"; }}
这里有好多东西需要注意:
首先是从后端传值到前端用的是:
ActionContext.getContext().put("emp",employee);
容器中的值只对当前页面有用,也就是你在调用listAll的时候,将整个数据放进了employee中传到前端,当你在前端点击页面跳转的时候上一页面的employee就会失效了,在页面跳转的时候
必须重新获取,所以所有的action里面除了必要的增删改查还添加了一个toAdd,目的就是用来进行页面跳转的同时计算新增字段的id,而不能直接在上一页面的employee中来获取
在前端获取后端值的方式也有很多,在后端获取前端值的方式也有很多,这些我在最末尾,将用一篇文章来总结。
转载地址:http://tawlf.baihongyu.com/