1. 程式人生 > >SSM框架根據id刪除一條資訊

SSM框架根據id刪除一條資訊

上一篇寫了批量刪除,現在寫只刪除一條資訊的程式碼!

我的程式碼是運用ajax實現完成的互動~

在控制器中的程式碼如下:

	
		/**
		 * 刪除一條資訊
		 * @param id
		 * @return
		 */
		@RequestMapping("deleteById")
		@ResponseBody
		public String deleteById(Integer id) {
			//判斷取值id是否為null,為null則表明刪除失敗!
			if(id==null) {
				return "error";
			}else {
				cImgService.deleteById(id);
				return "ok";
			}
			
		}

在Service中的程式碼如下:

//刪除一條
	void deleteById(Integer id);

在Service實現類中的程式碼如下:

        @Autowired
	private CoverImgDao cDao;

	public CoverImgDao getcDao() {
		return cDao;
	}

	public void setcDao(CoverImgDao cDao) {
		this.cDao = cDao;
        }
        public void deleteById(Integer id) {
		//刪除一條
		cDao.deleteById(id);
	}

在Dao層的程式碼如下:

//刪除一條
	void deleteById(Integer id);

在mapper檔案中的sql查詢語句程式碼如下:

<!-- 刪除一條資訊 -->
	<delete id="deleteById">
		delete from cover where cv_id = #{id}
	</delete>

在jsp頁面中的部分程式碼如下:

<a title="刪除" href="javascript:;" onclick="cImg_del(this,'${item.cv_id}')" class="ml-5" style="text-decoration:none">刪除</a>

這行程式碼是主要點選執行的刪除;位置:

<table class="table table-border table-sort table-bordered table-bg" id="tableId">
		<thead>
			<tr>
				<th scope="col" colspan="9">封面圖列表</th>
			</tr>
			<tr class="text-c">
				<th width="25"><input type="checkbox" id="all" value=""></th>
				<th width="40">ID</th>
				<th width="150">封面圖名稱</th>
				<th width="90">封面圖路徑</th>
				<th width="130">加入時間</th>
				<th width="130">管理員</th>
				<th width="100">操作</th>
			</tr>
		</thead>
		<tbody>
			<c:forEach items="${cList}" var="item">
				<tr class="text-c">
					<td><input type="checkbox" value="${item.cv_id}" name="id"></td>
					<td>${item.cv_id}</td>
					<td><img src="${item.cv_url}" style="width:200px;height: 50px;"/></td>
					<td>${item.cv_text}</td>
					<fmt:formatDate value="${item.cv_time}" var="day" pattern="yyyy-MM-dd"/>
					<td>${day}</td>
					<td>${item.ad_id}</td>
					<td class="td-manage"> <a title="編輯" href="javascript:;" onclick="cImg_edit('編輯封面圖','coverImg_add.jsp','1','800','500')" class="ml-5" style="text-decoration:none">編輯</a>
                                            <a title="刪除" href="javascript:;" onclick="cImg_del(this,'${item.cv_id}')" class="ml-5" style="text-decoration:none">刪除</a></td>
				</tr>
			</c:forEach>
		</tbody>
	</table>

在js中的程式碼如下:

解釋一下:c_id為jsp頁面中取到的該行id的值,該值為點選得到的值

/*封面圖-刪除*/
function cImg_del(obj,c_id){//id為取到的行id
	var r=confirm("是否確認刪除?");    
	if(r==true){
		//確定執行刪除
		var id = c_id;
		$.get("cover/deleteById?id="+id,function(data){
			 if(data=="ok"){
				alert("刪除成功!");
				//刪除成功後,重新整理頁面資訊
				location.reload();
			}else{
				alert("刪除失敗!!");
			} 
		});
		return true;
	}else{
		//反之取消刪除
		return false;
	}
}