基于javaweb的web资源库项目——后台资源管理demo

2021/9/30 20:11:07

本文主要是介绍基于javaweb的web资源库项目——后台资源管理demo,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

前面完成了后台的用户管理,而资源管理的实现的原理和用户管理是差不多的,这里就直接给出资源管理的代码

文章目录

  • 表的设计
  • 表的创建
  • 创建实体类
  • 资源管理实现
    • 获取所有用户资源信息并分页
      • 后端实现
      • 后台资源管理页面
    • 标优优秀资源
      • 后端实现
      • 前端实现
    • 删除单个资源和批量删除资源

表的设计

资源管理需要两个表,一个是管理用户资源的表resource,另一个是管理资源类别的表category

显然,管理用户资源的表需要两个外键,其中一个外键resource_uid对应用户账号user_id,另一个对应资源类别category_id

这样当删除用户时,用户所拥有的资源也会被删除,同理,当删除资源类别时,属于这种资源类别的用户资源也会被删除

管理用户资源表resource如下

字段名称类型约束描述
resource_idint(10)NOT NULL AUTO_INCREMENT资源编号
resource_cidint(10)NOT NULL FOREIGN KEY (resource_cid) REFERENCES category (category_id) ON DELETE CASCADE ON UPDATE CASCADE外键对应资源类别编号category
resource_uidvarchar(20)NOT NULL FOREIGN KEY (resource_uid) REFERENCES user (user_id) ON DELETE CASCADE ON UPDATE CASCADE外键对应用户账号user_id
resource_namevarchar(20)NOT NULL资源名称
resource_imagevarchar(500)DEFAULT NULL图片路径
resource_urlvarchar(250)NOT NULL资源下载地址路径
resource_descvarchar(250)DEFAULT NULL资源描述
resource_levelvarchar(10)NOT NULL DEFAULT ‘初级’资源等级,默认为初级
resource_timedateNOT NULL资源上传时间
resource_goodint(10)NOT NULL DEFAULT ‘0’是否为优秀资源,默认为一般资源

资源类别表category如下

字段名称类型约束描述
category_idint(10)NOT NULL AUTO_INCREMENT资源类别编号
category_namevarchar(20)NOT NULL资源类别名称
category_descvarchar(250)DEFAULT NULL资源类别描述

表的创建

resource表的创建

在mysql命令行使用如下sql语句创建resource表

USE web_resource;
DROP TABLE IF EXISTS `resource`;
CREATE TABLE `resource` (
  `resource_id` int(10) NOT NULL AUTO_INCREMENT,
  `resource_cid` int(10) NOT NULL,
  `resource_uid` varchar(20) NOT NULL,
  `resource_name` varchar(20) NOT NULL,
  `resource_image` varchar(500) DEFAULT NULL,
  `resource_url` varchar(250) NOT NULL,
  `resource_desc` varchar(250) DEFAULT NULL,
  `resource_level` varchar(10) NOT NULL DEFAULT '初级',
  `resource_time` date NOT NULL,
  `resource_good` int(10) NOT NULL DEFAULT '0',
  PRIMARY KEY (`resource_id`),
  KEY `resource_cid` (`resource_cid`),
  KEY `resource_uid` (`resource_uid`),
  CONSTRAINT `resource_ibfk_1` FOREIGN KEY (`resource_cid`) REFERENCES `category` (`category_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `resource_ibfk_2` FOREIGN KEY (`resource_uid`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;

category表的创建

在mysql命令行使用如下sql语句创建category表

USE web_resource;
DROP TABLE IF EXISTS `category`;
CREATE TABLE `category` (
  `category_id` int(10) NOT NULL AUTO_INCREMENT,
  `category_name` varchar(20) NOT NULL,
  `category_desc` varchar(250) DEFAULT NULL,
  PRIMARY KEY (`category_id`,`category_name`),
  KEY `category_id` (`category_id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

创建实体类

在entity包下,创建用户资源实体resource,如下

package com.zhuo.entity;

public class Resource {
    private int resourceId;
    private int resourceCid;
    private String resourceUid;
    private String resourceName;
    private String resourceImage;
    private String resourceUrl;
    private String resourceDesc;
    private String resourceLevel;
    private String resourceTime;
    private int resourceGood;
	public Resource() {
		super();
	}
	public Resource(int resourceId, int resourceCid, String resourceUid, String resourceName, String resourceImage,
			String resourceUrl, String resourceDesc, String resourceLevel, String resourceTime, int resourceGood) {
		super();
		this.resourceId = resourceId;
		this.resourceCid = resourceCid;
		this.resourceUid = resourceUid;
		this.resourceName = resourceName;
		this.resourceImage = resourceImage;
		this.resourceUrl = resourceUrl;
		this.resourceDesc = resourceDesc;
		this.resourceLevel = resourceLevel;
		this.resourceTime = resourceTime;
		this.resourceGood = resourceGood;
	}
	public int getResourceId() {
		return resourceId;
	}
	public void setResourceId(int resourceId) {
		this.resourceId = resourceId;
	}
	public int getResourceCid() {
		return resourceCid;
	}
	public void setResourceCid(int resourceCid) {
		this.resourceCid = resourceCid;
	}
	public String getResourceUid() {
		return resourceUid;
	}
	public void setResourceUid(String resourceUid) {
		this.resourceUid = resourceUid;
	}
	public String getResourceName() {
		return resourceName;
	}
	public void setResourceName(String resourceName) {
		this.resourceName = resourceName;
	}
	public String getResourceImage() {
		return resourceImage;
	}
	public void setResourceImage(String resourceImage) {
		this.resourceImage = resourceImage;
	}
	public String getResourceUrl() {
		return resourceUrl;
	}
	public void setResourceUrl(String resourceUrl) {
		this.resourceUrl = resourceUrl;
	}
	public String getResourceDesc() {
		return resourceDesc;
	}
	public void setResourceDesc(String resourceDesc) {
		this.resourceDesc = resourceDesc;
	}
	public String getResourceLevel() {
		return resourceLevel;
	}
	public void setResourceLevel(String resourceLevel) {
		this.resourceLevel = resourceLevel;
	}
	public String getResourceTime() {
		return resourceTime;
	}
	public void setResourceTime(String resourceTime) {
		this.resourceTime = resourceTime;
	}
	public int getResourceGood() {
		return resourceGood;
	}
	public void setResourceGood(int resourceGood) {
		this.resourceGood = resourceGood;
	}
	@Override
	public String toString() {
		return "Resource [resourceId=" + resourceId + ", resourceCid=" + resourceCid + ", resourceUid=" + resourceUid
				+ ", resourceName=" + resourceName + ", resourceImage=" + resourceImage + ", resourceUrl=" + resourceUrl
				+ ", resourceDesc=" + resourceDesc + ", resourceLevel=" + resourceLevel + ", resourceTime="
				+ resourceTime + ", resourceGood=" + resourceGood + "]";
	}
}

在entity包下,创建资源类别实体category,如下

package com.zhuo.entity;

public class Category {
    private int categoryId;
    private String categoryName;
    private String categoryDesc;
	public Category() {
		super();
	}
	public Category(int categoryId, String categoryName, String categoryDesc) {
		super();
		this.categoryId = categoryId;
		this.categoryName = categoryName;
		this.categoryDesc = categoryDesc;
	}
	public int getCategoryId() {
		return categoryId;
	}
	public void setCategoryId(int categoryId) {
		this.categoryId = categoryId;
	}
	public String getCategoryName() {
		return categoryName;
	}
	public void setCategoryName(String categoryName) {
		this.categoryName = categoryName;
	}
	public String getCategoryDesc() {
		return categoryDesc;
	}
	public void setCategoryDesc(String categoryDesc) {
		this.categoryDesc = categoryDesc;
	}
	@Override
	public String toString() {
		return "Category [categoryId=" + categoryId + ", categoryName=" + categoryName + ", categoryDesc="
				+ categoryDesc + "]";
	}
}

资源管理实现

获取所有用户资源信息并分页

后端实现

在controller层中创建resource包,并在resource包下创建DoResourceSelect.java,代码如下

package com.zhuo.controller.resource;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zhuo.entity.Category;
import com.zhuo.entity.Resource;
import com.zhuo.entity.User;
import com.zhuo.service.impl.ResourceServiceImpl;

@WebServlet("/manage/admin_do_resource_select")
public class DoResourceSelect extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 当前页
		int currentPage = 1;
		// 每页显示条数
		int count = 5;
		// array[0]=资源总数,array[1]=总页数,后面会被覆盖
		int array[] = { 0, 0 };
		// 获取用户指定的页面
		String cp = request.getParameter("currentPage");
		System.out.println("cp = " + cp);
		// 接收用户搜索的关键字
		String keyword = request.getParameter("keywords");
		/* 用户如果有指定当前页,则把字符串转化为int型 */
		if (cp != null) {
			currentPage = Integer.parseInt(cp);
		}
		// 创建资源service层接口的实现类
		ResourceServiceImpl resourceServiceImpl = new ResourceServiceImpl();
		/*
		 * 调用业务逻辑方法获取资源记录总数并算出总页数 即(array[0]=资源总数,array[1]=总页数(资源总数/每页显示条数)
		 */
		try {
			array = resourceServiceImpl.getResourcePageTotal(count, keyword);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		// 调用业务逻辑方法获取所有资源信息
		ArrayList<Resource> listResource = null;
		try {
			listResource = resourceServiceImpl.getAllResourceInfo(currentPage, count, keyword);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		// 调用业务逻辑方法获取所有含有资源的用户信息
		ArrayList<User> listUser = null;
		try {
			listUser = resourceServiceImpl.getAllHasResourceUser(listResource);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		/* 遍历所有资源,遍历过程中利用资源id
		 * 调用业务逻辑方法获取资源类别信息,并添加到list集合中 */
		ArrayList<Category> listCategory = new ArrayList<Category>();
		for (int i = 0; i < listResource.size(); i++) {
			Category category = new Category();
			try {
				category = resourceServiceImpl.getAllResourceCategoryInfo(listResource.get(i).getResourceCid());
			} catch (SQLException e) {
				e.printStackTrace();
			}
			listCategory.add(category);
		}
		// 放到请求对象域里
		request.setAttribute("resourceList", listResource);
		request.setAttribute("userList", listUser);
		request.setAttribute("categoryList", listCategory);
		request.setAttribute("totalStudent", array[0]);
		request.setAttribute("totalPage", array[1]);
		request.setAttribute("currentPage", currentPage);
		request.getRequestDispatcher("/views/after/manage/admin_resource.jsp").forward(request, response);
	}
}

在service层中创建ResourceService接口,并在接口中添加如下业务逻辑抽象方法,如下

	// 获取所有资源记录总数及页数
	public int[] getResourcePageTotal(int count, String keyword) throws SQLException;
	
	// 获取所有资源信息
	public ArrayList<Resource> getAllResourceInfo(int currentPage, int count, String keyword) throws SQLException;
	
	// 获取所有含有资源的用户信息
	public ArrayList<User> getAllHasResourceUser(ArrayList<Resource> listResource) throws SQLException;
	
	// 获取所有资源的类别信息
	public Category getAllResourceCategoryInfo(int categoryId) throws SQLException;

在service层中创建接口的实现类ResourceServiceImpl.java,并在实现类中重写接口方法,如下

	// 创建资源dao层接口的实现类
	ResourceDao resourceDao = new ResourceDaoImpl();
	@Override
	public int[] getResourcePageTotal(int count, String keyword) throws SQLException {
		// 检索所有资源总数并算出总页数
		int[] array = resourceDao.selectResourceTotal(count, keyword);
		return array;
	}
	
	@Override
	public ArrayList<Resource> getAllResourceInfo(int currentPage, int count, String keyword) throws SQLException {
		// 检索所有资源信息
		ArrayList<Resource> listResource = resourceDao.selectAllResource(currentPage, count, keyword);
		return listResource;
		
	}
	
	@Override
	public ArrayList<User> getAllHasResourceUser(ArrayList<Resource> listResource) throws SQLException {
		// 检索含有资源的所有用户信息
		ArrayList<User> listUser = resourceDao.selectAllHasResourceUser(listResource);
		return listUser;
	}
	
	@Override
	public Category getAllResourceCategoryInfo(int catagotyId) throws SQLException{
		// 检索所有资源的资源类别
		Category category = resourceDao.selectAllResourceCategoryInfo(catagotyId);
		return category;
	}

在dao层中创建接口ResourceDao.java,并在接口中添加如下抽象方法,执行底层操作,如下

// 检索所有资源总数并算出总页数
	public int[] selectResourceTotal(int count, String keyword) throws SQLException;
	
	// 检索所有资源信息
	public ArrayList<Resource> selectAllResource(int currentPage, int count, String keyword) throws SQLException;

	// 检索含有资源的所有用户信息
	public ArrayList<User> selectAllHasResourceUser(ArrayList<Resource> listResource) throws SQLException;
	
	// 检索所有资源的资源类别
	public Category selectAllResourceCategoryInfo(int categoryId) throws SQLException;

在dao层中创建接口的实现类ResourceDaoImpl.java,并在实现类中重写接口方法,如下

	// 存放查询数据库返回的结果集
	ResultSet resultSet;

	@Override
	public int[] selectResourceTotal(int count, String keyword) throws SQLException {
		String sql = "";
		// 0 资源记录数 1 页数
		int array[] = { 0, 1 };
		if (keyword != null) {
			// sql检索语句
			sql = "select count(*) from resource where  resource_name like ?";
			// 调用jdbc工具类执行sql语句
			resultSet = JDBCUtil.executeQuery(sql, "%" + keyword + "%");
		} else {
			// sql检索语句
			sql = "select count(*) from resource";
			// 调用jdbc工具类执行sql语句
			resultSet = JDBCUtil.executeQuery(sql);
		}
		while (resultSet.next()) {
			array[0] = resultSet.getInt(1);
			if (array[0] % count == 0) {
				array[1] = array[0] / count;
			} else {
				array[1] = array[0] / count + 1;
			}
		}
		return array;
	}

	@Override
	public ArrayList<Resource> selectAllResource(int currentPage, int count, String keyword) throws SQLException {
		// 存放所有资源信息的list集合
		ArrayList<Resource> listResource = new ArrayList<Resource>();
		String sql = "";
		if (keyword != null) {
			// sql检索语句
			sql = "select * from resource where  resource_name like ? order by resource_time desc limit ?, ?";
			// 调用jdbc工具类执行sql语句
			resultSet = JDBCUtil.executeQuery(sql, "%" + keyword + "%", (currentPage - 1) * count, count);
		} else {
			// sql检索语句
			sql = "select * from resource  order by resource_time desc limit ?, ?";
			// 调用jdbc工具类执行sql语句
			resultSet = JDBCUtil.executeQuery(sql, (currentPage - 1) * count, count);
		}
		while (resultSet.next()) {
			Resource resource = new Resource(Integer.parseInt(resultSet.getString("resource_id")),
					Integer.parseInt(resultSet.getString("resource_cid")), resultSet.getString("resource_uid"),
					resultSet.getString("resource_name"), resultSet.getString("resource_image"),
					resultSet.getString("resource_url"), resultSet.getString("resource_desc"),
					resultSet.getString("resource_level"), resultSet.getString("resource_time"),
					Integer.parseInt(resultSet.getString("resource_good")));
			listResource.add(resource);
		}
		return listResource;
	}

	@Override
	public ArrayList<User> selectAllHasResourceUser(ArrayList<Resource> listResource) throws SQLException {
		// 存放所有含有资源的用户信息的list集合
		ArrayList<User> listUser = new ArrayList<User>();
		String sql = "";
		for (int i = 0; i < listResource.size(); i++) {
			// sql检索语句
			sql = "select * from user where user_id=?";
			// 调用jdbc工具类执行sql语句
			resultSet = JDBCUtil.executeQuery(sql, listResource.get(i).getResourceUid());
			while (resultSet.next()) {
				User user = new User(resultSet.getString("user_id"), resultSet.getString("user_password"),
						resultSet.getString("user_name"), resultSet.getString("user_sex"),
						resultSet.getString("user_birthday"), resultSet.getString("user_class"),
						resultSet.getString("user_level"));
				listUser.add(user);
			}
		}
		return listUser;
	}

	@Override
	public Category selectAllResourceCategoryInfo(int categoryId) throws SQLException {
		// 创建资源类别实体
		Category category = new Category();
		// sql检索语句
		String sql = "select * from category where category_id=?";
		// 调用jdbc工具类执行sql语句
		resultSet = JDBCUtil.executeQuery(sql, categoryId);
		while (resultSet.next()) {
			category = new Category(Integer.parseInt(resultSet.getString("category_id")),
					resultSet.getString("category_name"), resultSet.getString("category_desc"));
		}
		return category;
	}

后台资源管理页面

在manage文件夹中创建admin_resource.jsp,代码如下

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ include file="admin_menu.jsp"%>
<div class="main-wrap">
	<div class="crumb-wrap">
		<div class="crumb-list">
			<i class="icon-font"></i><a
				href="${pageContext.request.contextPath}/views/after/manage/admin_index.jsp">首页</a><span
				class="crumb-step">&gt;</span><span class="crumb-name">资源管理</span>
		</div>
	</div>
	<div class="search-wrap">
		<div class="search-content">
			<form action="admin_do_resource_select" method="get">
				<table class="search-tab">
					<tr>
						<th width="70">关键字:</th>
						<td><input class="common-text" placeholder="输入资源名称"
							name="keywords" id="" type="text"></td>
						<td><input class="btn btn-primary btn2" name="sub" value="查询"
							type="submit"></td>
					</tr>
				</table>
			</form>
		</div>
	</div>
	<div id="register" class="result-wrap">
		<form action="admin_do_resource_delete" id="delectForm" method="post">
			<div class="result-title">
				<div class="result-list">
					<a id="batchDel"
						href="javascript:deleteMore('你确定删除这些资源吗?', 'delectForm')"> <i
						class="icon-font"></i>批量删除
					</a>
				</div>
			</div>

			<div class="result-content" id="dg">
				<table class="result-tab" width="100%">
					<tr>
						<th class="tc" width="5%"><input class="allChoose" name=""
							onclick="selAll(this)" type="checkbox"></th>
						<th>资源编号</th>
						<th>资源名称</th>
						<th>资源类别</th>
						<th>资源等级</th>
						<th>作者</th>
						<th>作者类别</th>
						<th>上传时间</th>
						<th>是否优秀</th>
						<th>操作</th>
					</tr>

					<c:forEach var="u" items="${resourceList}" varStatus="loop">
						<tr>
							<td class="tc"><input name="id[]" value="${u.resourceId}"
								type="checkbox"></td>
							<td>${u.resourceId }</td>
							<td>${u.resourceName  }</td>
							<td>${requestScope.categoryList.get(loop.count-1).categoryName  }</td>
							<td>${u.resourceLevel  }</td>
							<td>${requestScope.userList.get(loop.count-1).userName  }</td>
							<td>${requestScope.userList.get(loop.count-1).userLevel  }</td>
							<td>${u.resourceTime  }</td>
							<c:choose>
								<c:when test="${u.resourceGood==1  }">
									<td>优秀</td>
								</c:when>
								<c:otherwise>
									<td>一般</td>
								</c:otherwise>
							</c:choose>
							<td><c:choose>
									<c:when test="${u.resourceGood==0  }">
										<a class="link-update"
											href="javascript:setGood(${u.resourceId}, '${u.resourceName}', '${pageContext.request.contextPath}/manage/admin_do_resource_update?id=${u.resourceId}&currentPage=${currentPage }')">设为优秀</a>
										<a class="link-del"
											href="javascript:Delete('你确定要删除资源【${u.resourceName} 】吗?', '${pageContext.request.contextPath}/manage/admin_do_resource_delete?id=${u.resourceId}&currentPage=${currentPage }')">删除</a>
									</c:when>
									<c:otherwise>
										<span>&#8195;&#8195;&#8195;&#8195;</span>
										<a class="link-del"
											href="javascript:Delete('你确定要删除资源【${u.resourceName} 】吗?', '${pageContext.request.contextPath}/manage/admin_do_resource_delete?id=${u.resourceId}&currentPage=${currentPage }')">删除</a>
									</c:otherwise>
								</c:choose></td>
						</tr>
					</c:forEach>
				</table>
				<div class="list-page">
					共 ${totalStudent} 条记录, 当前 ${currentPage} / ${totalPage} 页 <a
						href="admin_do_resource_select?currentPage=1">首页</a> <a
						href="admin_do_resource_select?currentPage=${currentPage - 1 < 1 ? 1 : currentPage-1}">上一页</a>
					<a
						href="admin_do_resource_select?currentPage=${currentPage + 1 > totalPage ? totalPage : currentPage + 1}">下一页</a>
					<a href="admin_do_resource_select?currentPage=${totalPage}">尾页</a>
				</div>
			</div>
		</form>
	</div>
</div>
<script src="${pageContext.request.contextPath}/views/js/function.js"></script>
</body>
</html>

在数据库中的resource表中添加一些资源信息,如下

在这里插入图片描述

启动项目测试
在这里插入图片描述

标优优秀资源

后端实现

在controller层的resource包下创建DoResourceUpdate.java,代码如下

package com.zhuo.controller.resource;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zhuo.entity.User;
import com.zhuo.service.UserService;
import com.zhuo.service.impl.ResourceServiceImpl;
import com.zhuo.service.impl.UserServiceImpl;

@WebServlet("/manage/admin_do_resource_update")
public class DoResourceUpdate extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/* 设置字符编码,解决中文乱码问题 */
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		/* 接收客户端信息 */
		String resourceId = request.getParameter("id");
		// 创建资源service层接口的实现类
		ResourceServiceImpl userServiceImpl = new ResourceServiceImpl();
		/* 调用业务逻辑方法修改标优资源 */
		int count = 0;
		try {
			count = userServiceImpl.modifyResourceInfo(resourceId);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if (count > 0) {
			response.sendRedirect("admin_do_resource_select?currentPage=" + request.getParameter("currentPage"));
		} else {
			PrintWriter out = response.getWriter();
			out.write("<script>");
			out.write("alert('用户修改失败')");
			out.write("location.href='admin_to_resource_update?id=" + resourceId + "'");
			out.write("</script>");
		}
	}
}

在service层的ResourceService接口中添加一个修改标优编号业务逻辑的抽象方法,如下

	// 修改标优标识
	public int modifyResourceInfo(String resourceId) throws SQLException;

在service层的实现类ResourceServiceImpl中重写接口的方法modifyResourceInfo,如下

	@Override
	public int modifyResourceInfo(String resourceId) throws SQLException {
		// 更新标优字段
		int i = resourceDao.updateResource(resourceId);
		return i;
	}

在dao层的ResourceDao接口中添加更新标优字段的抽象方法,如下

	// 更新标优字段
	public int updateResource(String resourceId) throws SQLException;

在dao层的实现类型ResourceDaoImpl中重写接口方法updateResource,如下

	@Override
	public int updateResource(String resourceId) throws SQLException {
		// sql更新语句
		String sql = "update resource set resource_good=? where resource_id = ?";
		// 调用jdbc工具类执行sql语句
		int i = JDBCUtil.executeUpdate(sql, 1, resourceId);
		return i;
	}

前端实现

在js文件侠下的function.js添加如下的js代码,如下

// 标优点击事件处理函数
function setGood(resourceId, resourceName, url) {
	message = "您确认要标优【" + resourceName + "】资源吗?"
	if (confirm(message)) {
		location.href = url;
	}
}

启动项目测试

在这里插入图片描述

删除单个资源和批量删除资源

在controller层的resource包下创建DoResourceDelete.java

package com.zhuo.controller.resource;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zhuo.service.UserService;
import com.zhuo.service.impl.ResourceServiceImpl;
import com.zhuo.service.impl.UserServiceImpl;

@WebServlet("/manage/admin_do_resource_delete")
public class DoResourceDelete extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/* 设置字符编码,解决中文乱码问题 */
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		/* 接收客户端信息 */
		String id = request.getParameter("id");
		// 创建资源service层接口的实现类
		ResourceServiceImpl resourceServiceImpl = new ResourceServiceImpl();
		/* 调用业务逻辑方法删除资源 */
		int count = 0;
		try {
			count = resourceServiceImpl.removeResourceInfo(id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		/* 成功或失败重定向到哪里 */
		if (count > 0) {
			response.sendRedirect("admin_do_resource_select?currentPage=" + request.getParameter("currentPage"));
		} else {
			PrintWriter out = response.getWriter();
			out.write("<script>");
			out.write("alert('删除失败')");
			out.write("location.href='admin_do_resource_select?currentPage=" + request.getParameter("currentPage"));
			out.write("</script>");
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/* 设置字符编码,解决中文乱码问题 */
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		/* 接收客户端信息 */
		String ids[] = request.getParameterValues("id[]");
		// 创建用户service层接口的实现类
		ResourceServiceImpl resourceServiceImpl = new ResourceServiceImpl();
		int count = 0;
		/* 遍历学生id过程中,调用业务逻辑方法删除学生 */
		for (int i = 0; i < ids.length; i++) {
			try {
				count = resourceServiceImpl.removeResourceInfo(ids[i]);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		/* 成功或失败重定向到哪里 */
		if (count > 0) {
			response.sendRedirect("admin_do_resource_select");
		} else {
			PrintWriter out = response.getWriter();
			out.write("<script>");
			out.write("alert('批量删除失败')");
			out.write(
					"location.href='admin_do_resource_select?currentPage=" + request.getParameter("currentPage") + "'");
			out.write("</script>");
		}
	}
}

在service层的ResourceService接口中添加删除资源的业务逻辑抽象方法,如下

	// 删除资源信息
	public int removeResourceInfo(String resourceId) throws SQLException;

在service层的实现类ResourceServiceImpl中重写接口方法removeResourceInfo,如下

	@Override
	public int removeResourceInfo(String resourceId) throws SQLException {
		// 删除资源信息
		int i = resourceDao.deleteResource(resourceId);
		return i;
	}

在dao层的ResourceDao接口中添加删除资源的抽象方法,如下

	// 删除资源信息
	public int deleteResource(String resourceId) throws SQLException;

在dao层的实现类ResourceDaoImpl中重写接口方法deleteResource,如下

	@Override
	public int deleteResource(String resourceId) throws SQLException {
		// sql删除语句
		String sql = "delete from resource where resource_id=?";
		int i = JDBCUtil.executeUpdate(sql, resourceId);
		return i;
	}

启动项目测试

在这里插入图片描述

资源类别管理实现就不说明了,原理是一样的,下一篇更新论坛管理。



这篇关于基于javaweb的web资源库项目——后台资源管理demo的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程