1. 程式人生 > >struts2實現CRUD(增 刪 改 查)

struts2實現CRUD(增 刪 改 查)

CRUD是Create(建立)、Read(讀取)、Update(更新)和Delete(刪除)

首先,肯定是要與資料互動的,所以我們先寫一個bean類

程式碼如下:

public class Food {
		private Integer id;
		private String name;
		private Double price;
		public Integer getId() {
			return id;
		}
		public void setId(Integer id) {
			this.id = id;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public Double getPrice() {
			return price;
		}
		public void setPrice(Double price) {
			this.price = price;
		}
		public Food(Integer id, String name, Double price) {
			super();
			this.id = id;
			this.name = name;
			this.price = price;
		}
		public Food() {
			super();
			// TODO Auto-generated constructor stub
		}
		@Override
		public String toString() {
			return "Food [id=" + id + ", name=" + name + ", price=" + price + "]";
		}
		
}

在bean類中建立的欄位,與資料庫中的欄位相對應,

下面是Dao程式碼:

Dao介面:

public interface FoodDaoI {
	//列表展示
		List<Food> showFoodList();
	//刪除操作
		void delFoodById(Integer id);
	//新增操作
		void addFood(Food food);
	//更新前回顯
		Food findById(Integer id);
	//更新
		void updateFood(Food food);
}

Dao實現類:

public class FoodDaoImpl implements FoodDaoI{

	private QueryRunner qr=new QueryRunner(JDBCUtils3.getDataSource());
	
	public List<Food> showFoodList() {
		String sql="select * from ee";
		List<Food> list=null;
		try {
			list=qr.query(sql, new BeanListHandler<Food>(Food.class));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	public void delFoodById(Integer id) {
		String sql="delete from ee where id=?";
		try {
			qr.update(sql, id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void addFood(Food food) {
		String sql="insert into ee set id=?,name=?,price=?";
		try {
			qr.update(sql, food.getId(),food.getName(),food.getPrice());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public Food findById(Integer id) {
		String sql="select * from ee where id=?";
		Food food=null;
		try {
			food=qr.query(sql, new BeanHandler<Food>(Food.class),id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return food;
	}

	public void updateFood(Food food) {
		String sql="update ee set name=?, price=? where id=?";
		try {
			qr.update(sql, food.getName(),food.getPrice(),food.getId());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

然後是action類,程式碼如下:

public class FoodAction extends ActionSupport implements ModelDriven<Food>{

	private FoodDaoI foodDao=new FoodDaoImpl();
	
	private static final long serialVersionUID = 5418396635382987020L;
	
	private List<Food> list;
	private Food food=new Food();
	
	
	//列表展示
	public String list() {
		list = foodDao.showFoodList();
		return "list";
	}
	//刪除操作
	public String delete() {
		foodDao.delFoodById(food.getId());
		return "delete";
		
	}
	//新增操作
	public String add() {
		foodDao.addFood(food);
		return "add";
	}
	//更新前回顯
	public String toupdate() {
		food=foodDao.findById(food.getId());
		ServletActionContext.getRequest().setAttribute("food", food);
		return "toupdate";
		
	}
	//更新操作
	public String update() {
		foodDao.updateFood(food);
		return "update";
		
	}
	
	//*****************************************
	
	public FoodDaoI getFoodDao() {
		return foodDao;
	}
	public void setFoodDao(FoodDaoI foodDao) {
		this.foodDao = foodDao;
	}
	public List<Food> getList() {
		return list;
	}
	public void setList(List<Food> list) {
		this.list = list;
	}
	public Food getFood() {
		return food;
	}
	public void setFood(Food food) {
		this.food = food;
	}
	public Food getModel() {
		// TODO Auto-generated method stub
		return food;
	}

}

需要注意的是,本例子在action中實現了ModelDriven<>類,所以需要設定action類中,相應的getter/setter方法

接下來是struts.xml檔案的配置:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

    	<package name="Struts2_CRUD_DEMO" extends="struts-default" namespace="/">
    			<action name="action_*" class="com.baidu.action.FoodAction"  method="{1}" >
    					<result name="list" >/list.jsp</result>
    					
    					<result name="delete" type="redirect">action_list</result>
    					
    					<result name="add" type="redirect">action_list</result>
    					
    					<result name="toupdate">/update.jsp</result>
    					
    					<result name="update" type="redirect">action_list</result>
    			</action>
    	</package>

</struts>

在strutsxml檔案中需要注意的是方法之間重定向的時候需要設定<result>標籤中的type屬性

下面是jsp:

列表展示jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
	<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
	<script type="text/javascript">
			function del(id) {
				location.href="action_delete?id="+id;
			}
			function toUpdate(id) {
				location.href="action_toupdate?id="+id;
			}
	</script>


</head>
<body>
		

	<h2>Food List</h2>
	<table border="1" style="align-content: center;">
			<tr>
				<td>id</td>
				<td>name</td>
				<td>price</td>
			</tr>
		<c:forEach items="${list }" var="food">
			<tr>
				<td>${food.id }</td>
				<td>${food.name }</td>
				<td>${food.price }</td>
				<td>
					<button onclick="del(${food.id })">刪除</button>
				</td>
				<td>
					<button onclick="toUpdate(${food.id })">修改</button>
				</td>
			</tr>
		</c:forEach>
	</table>
	<a href="add.jsp">新增</a>
	
</body>
</html>

更新介面jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
	
	
</head>
<body>
	<form action="action_update"  method="post">
		<input type="hidden" name="id" value="${food.id }">
		姓名:<input type="text" value="${food.name }" name="name"><br>
		價格:<input type="text" value="${food.price }" name="price"><br>
		<input type="submit" value="提交">
	</form>
</body>
</html>

新增介面jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
	<script type="text/javascript">
				
	</script>

</head>
<body>
	<form action="action_add" method="post">
		<input type="hidden" name="food.id">
		姓名:<input type="text" value="" name="name"><br>
		價格:<input type="text" value="" name="price"><br>
		
		<input type="submit" value="提交">
	</form>
	
</body>
</html>

寫這個簡單例子,主要是為了幫助剛剛接觸Struts2這個框架的初學者,能更好的去理解Struts2框架,並學會如何使用,如果有同學想要本例子中相關jar包,可以給博主要哦