一、语言和环境
实现语言:JAVA语言。
环境要求:MyEclipse/Eclipse + Tomcat + MySql。
使用技术:Jsp+Servlet+JavaBean或SpringMVC + Spring + Mybatis。
二、实现功能
为了方便学校对图书进行管理,开发一套BS结构的图书信息管理系统,主要功能如下:
首页默认显示所有图书信息,并且按添加时间降序排列。
(1)按添加时间降序排列。
(2)底部显示添加书籍按钮。
- 点击“添加书籍”链接,跳转至书籍添加界面。
(1)添加时间默认新增时取当前时间即可。
3. 用户输入完整信息提交以后,要求自动跳转至列表界面,此时列表界面显示新增的书籍信息(按添加时间降序排列,应该在第一条)。
4. 用户点击“列表”界面中的删除超链接,执行删除操作,然后列表进行自动刷新。
5. 用户点击“列表”界面中的修改超链接,跳转到修改页面,并在该页面回显需要修改的书籍信息.
三、数据库设计
- 创建数据库(
person_db
)。 - 创建数据表(
tb_person
),结构如下。
四、推荐实现步骤
JSP版本的实现步骤如下:
(1)按以上数据库要求建库、建表,并添加测试数据(不少于5条,测试数据不需要和上图一致)。
(2)创建Web工程并创建各个包,导入工程所需的jar文件。
(3)创建Book实体类。
(4)创建Servlet获取用户不同的请求,并将这些请求转发至业务处理层相应的业务方法。
(5)创建业务处理层,在其中定义业务方法,实现系统需求,在这些业务方法中需要执行DAO方法。
(6)创建BaseDAO工具类,使用JDBC完成数据表数据的查询、删除、添加的功能方法代码。
(7)编写JSP页面展示数据的查询结果。
2.SSM版本的实现步骤如下:
(1)创建数据库,创建数据表,添加测试数据(不少于5条,测试数据不需要和上图一致)。
(2)创建Web工程并创建各个包,导入工程所需的jar文件。
(3)添加相关SSM框架支持。
(4)配置项目所需要的各种配置文件(mybatis配置文件、spring配置文件、springMVC配置文件)。
(5)创建实体类。
(6)创建MyBatis操作数据库所需的Mapper接口及其Xml映射数据库操作语句文件。
(7)创建业务逻辑相应的接口及其实现类,实现相应的业务,并在类中加入对DAO/Mapper的引用和注入。
(8)创建Controller控制器类,在Controller中添加对业务逻辑类的引用和注入,并配置springMVC配置文件。
(9)创建相关的操作页面,并使用CSS对页面进行美化。
(10)实现页面的各项操作功能,操作要人性化。
(11)调试运行成功后导出相关的数据库文件并提交。
五、实现代码
1、MySQL数据库
person_db.sql
/* Date: 2021-07-20 12:46:17 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `tb_person` -- ---------------------------- DROP TABLE IF EXISTS `tb_person`; CREATE TABLE `tb_person` ( `id` int(11) NOT NULL AUTO_INCREMENT, `BookName` varchar(50) NOT NULL, `author` varchar(10) NOT NULL, `pages` int(11) NOT NULL, `createTime` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of tb_person -- ---------------------------- INSERT INTO `tb_person` VALUES ('1', '《红楼梦》', '曹雪芹', '542', '2021-07-20 10:44:26'); INSERT INTO `tb_person` VALUES ('2', '《水浒传》', '施耐庵', '652', '2021-07-20 10:44:57'); INSERT INTO `tb_person` VALUES ('3', '《镜花缘》', '李汝珍', '441', '2021-07-20 10:45:59'); INSERT INTO `tb_person` VALUES ('5', '《西游记》', '吴承恩', '5000', '2021-07-20 12:42:43'); INSERT INTO `tb_person` VALUES ('7', '《三国演义》', '罗贯中', '10000', '2021-07-20 12:42:07');
2、项目Java代码
目录结构
person_db
JAR包:
src
com.controller
PersonController.java
package com.controller; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.entity.TbPerson; import com.service.PersonService; import com.sun.org.apache.bcel.internal.generic.NEW; @Controller public class PersonController { @Resource private PersonService service; @RequestMapping("selectAll") public String selectAll(Model model) { List<TbPerson> list=service.selsctAll(); model.addAttribute("personList", list); return "/person"; } @RequestMapping("deleteByid") public String deleteByid(int id) { int rows=service.delete(id); return "redirect:/selectAll.do"; } //添加页面跳转 @RequestMapping("getpage") public String getpage() { return "/addPage"; } //添加 @RequestMapping("addPerson") public String addPerson(TbPerson tbPerson) { SimpleDateFormat simple=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); tbPerson.setCreatetime(simple.format(new Date())); int rows=service.addPerson(tbPerson); return "redirect:/selectAll.do"; } //根据id查询 @RequestMapping("getbyid") public String getbyid(Model model,int id) { TbPerson tbPerson=service.getByid(id); model.addAttribute("tbPerson", tbPerson); return "/addPage"; } //修改 @RequestMapping("update") public String update(TbPerson tbPerson) { SimpleDateFormat simple=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); tbPerson.setCreatetime(simple.format(new Date())); int rows=service.update(tbPerson); return "redirect:/selectAll.do"; } }
com.dao
TbPersonMapper.java
package com.dao; import com.entity.TbPerson; import java.util.List; public interface TbPersonMapper { int deleteByPrimaryKey(Integer id); int insert(TbPerson record); TbPerson selectByPrimaryKey(Integer id); List<TbPerson> selectAll(); int updateByPrimaryKey(TbPerson record); }
TbPersonMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.dao.TbPersonMapper" > <resultMap id="BaseResultMap" type="com.entity.TbPerson" > <id column="id" property="id" jdbcType="INTEGER" /> <result column="BookName" property="bookname" jdbcType="VARCHAR" /> <result column="author" property="author" jdbcType="VARCHAR" /> <result column="pages" property="pages" jdbcType="INTEGER" /> <result column="createTime" property="createtime" jdbcType="TIMESTAMP" /> </resultMap> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from tb_person where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.entity.TbPerson" > insert into tb_person (id, BookName, author, pages, createTime) values (#{id,jdbcType=INTEGER}, #{bookname,jdbcType=VARCHAR}, #{author,jdbcType=VARCHAR}, #{pages,jdbcType=INTEGER}, #{createtime,jdbcType=TIMESTAMP}) </insert> <update id="updateByPrimaryKey" parameterType="com.entity.TbPerson" > update tb_person set BookName = #{bookname,jdbcType=VARCHAR}, author = #{author,jdbcType=VARCHAR}, pages = #{pages,jdbcType=INTEGER}, createTime = #{createtime,jdbcType=TIMESTAMP} where id = #{id,jdbcType=INTEGER} </update> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select id, BookName, author, pages, createTime from tb_person where id = #{id,jdbcType=INTEGER} </select> <select id="selectAll" resultMap="BaseResultMap" > select id, BookName, author, pages, createTime from tb_person ORDER BY createTime DESC </select> </mapper>
com.entity
TbPerson.java
package com.entity; import java.util.Date; public class TbPerson { private Integer id; private String bookname; private String author; private Integer pages; private String createtime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getBookname() { return bookname; } public void setBookname(String bookname) { this.bookname = bookname == null ? null : bookname.trim(); } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author == null ? null : author.trim(); } public Integer getPages() { return pages; } public void setPages(Integer pages) { this.pages = pages; } public String getCreatetime() { return createtime; } public void setCreatetime(String createtime) { this.createtime = createtime; } }
com.service
PersonService.java
package com.service; import java.util.List; import com.entity.TbPerson; public interface PersonService { //查询所有 List<TbPerson> selsctAll(); //删除 int delete(int id); //根据id查询 TbPerson getByid(int id); //修改 int update(TbPerson tbPerson); //添加 int addPerson(TbPerson tbPerson); }
com.service.impl
PersonServiceImpl.java
package com.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.dao.TbPersonMapper; import com.entity.TbPerson; import com.service.PersonService; @Service public class PersonServiceImpl implements PersonService { @Resource private TbPersonMapper mapper; @Override public List<TbPerson> selsctAll() { // TODO Auto-generated method stub List<TbPerson> list=mapper.selectAll(); return list; } @Override public int delete(int id) { // TODO Auto-generated method stub int rows=mapper.deleteByPrimaryKey(id); return rows; } @Override public TbPerson getByid(int id) { // TODO Auto-generated method stub TbPerson tbPerson=mapper.selectByPrimaryKey(id); return tbPerson; } @Override public int update(TbPerson tbPerson) { // TODO Auto-generated method stub int rows=mapper.updateByPrimaryKey(tbPerson); return rows; } @Override public int addPerson(TbPerson tbPerson) { // TODO Auto-generated method stub int rows=mapper.insert(tbPerson); return rows; } }
genter
Generator.java
package genter; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.exception.InvalidConfigurationException; import org.mybatis.generator.exception.XMLParserException; import org.mybatis.generator.internal.DefaultShellCallback; public class Generator { /* * targetRuntime="MyBatis3Simple", 不生成Example */ public void generateMyBatis() { //MBG执行过程中的警告信息 List<String> warnings = new ArrayList<String>(); //当生成的代码重复时,覆盖原代码 boolean overwrite = true ; String generatorFile = "/generatorConfig.xml"; //String generatorFile = "/generator/generatorConfigExample.xml"; //读取MBG配置文件 InputStream is = Generator.class.getResourceAsStream(generatorFile); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config; try { config = cp.parseConfiguration(is); DefaultShellCallback callback = new DefaultShellCallback(overwrite); //创建MBG MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); //执行生成代码 myBatisGenerator.generate(null); } catch (IOException e) { e.printStackTrace(); } catch (XMLParserException e) { e.printStackTrace(); } catch (InvalidConfigurationException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } for (String warning : warnings) { System.out.println(warning); } } public static void main(String[] args) { Generator generator = new Generator(); generator.generateMyBatis(); } }
MyBatis
SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 别名 --> <typeAliases> <package name="com.entity"/> </typeAliases> </configuration>
spring
applicationContext-dao.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd "> <context:property-placeholder location="classpath:dataSource.properties"/> <!-- 数据源配置 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${db.driverClass}"></property> <property name="Url" value="${db.jdbcUrl}"></property> <property name="username" value="${db.user}"></property> <property name="password" value="${db.password}"></property> </bean> <!-- 配置SqlSessionFactory --> <bean class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 设置MyBatis核心配置文件 --> <property name="configLocation" value="classpath:MyBatis/SqlMapConfig.xml"></property> <!-- 设置数据源 --> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置Mapper扫描 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 设置Mapper扫描包 --> <property name="basePackage" value="com.dao"></property> </bean> </beans>
applicationContext-service.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd "> <!-- 配置Service层扫描 --> <context:component-scan base-package="com.service"></context:component-scan> <!-- 配置事务管理层 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 开启注解方式管理AOP事务 --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd "> <!-- 配置Controller层扫描包 --> <context:component-scan base-package="com.controller"></context:component-scan> <!-- 配置注解驱动 --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name="prefix" value="/WEB-INF/jsp"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
dataSource.properties
db.driverClass=com.mysql.jdbc.Driver db.jdbcUrl=jdbc:mysql://127.0.0.1:3306/person_db?useUnicode=true&characterEncoding=UTF-8&useSSL=false db.user=root db.password=123456
generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <!-- 配置生成器 --> <generatorConfiguration> <context id="MySQLContext" targetRuntime="MyBatis3Simple" defaultModelType="flat"> <!-- 配置前置分隔符和后置分隔符 --> <property name="beginningDelimiter" value="`"/> <property name="endingDelimiter" value="`"/> <!-- 配置注释信息 --> <commentGenerator> <!-- 不生成注释 --> <property name="suppressAllComments" value="true"/> <property name="suppressDate" value="true"/> <property name="addRemarkComments" value="true"/> </commentGenerator> <!-- 数据库连接配置 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/person_db" userId="root" password="123456"> </jdbcConnection> <!-- targetPackage:生成实体类存放的包名, targetProject:指定目标项目路径,可以使用相对路径或绝对路径 --> <javaModelGenerator targetPackage="com.entity" targetProject="src"> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- 配置SQL映射器Mapper.xml文件的属性 --> <sqlMapGenerator targetPackage="com.dao" targetProject="src"/> <!-- type="XMLMAPPER":所有的方法都在XML中,接口调用依赖XML文件 --> <javaClientGenerator targetPackage="com.dao" type="XMLMAPPER" targetProject="src"/> <!-- 生成所有表的映射 --> <table tableName="%"></table> </context> </generatorConfiguration>
WebContent
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>person_db</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> </web-app>
JSP
index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Insert title here</title> </head> <body> <script> window.location.href = "selectAll.do"; </script> </body> </html>
addPage.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Insert title here</title> <style type="text/css"> .boddy { border: 1px solid black; width: 30%; margin: 0 auto; padding: 20px; } </style> </head> <body> <div class="boddy"> <c:if test="${tbPerson.id==null }"> <h1>添加书籍</h1> <form action="addPerson.do"> </c:if> <c:if test="${tbPerson.id!=null }"> <h1>修改书籍</h1> <form action="update.do"> </c:if> <input type="hidden" name="id" value="${tbPerson.id }" /> <p> <label>书籍名称:</label> <input type="text" name="bookname" value="${tbPerson.bookname }" /> </p> <p> <label>作者:</label> <input type="text" name="author" value="${tbPerson.author }" /> </p> <p> <label>页数:</label> <input type="number" name="pages" value="${tbPerson.pages }" /> </p> <p> <button type="submit">提交</button> <input type="button" onclick="window.history.back();" value="取消"> </p> </form> </div> </body> </html>
person.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>图书信息管理系统</title> </head> <style> * { margin: 0; padding: 0; } table, td, th { border-collapse: collapse; border-spacing: 0; } table { text-align: center; width: 80%; margin: 0 auto; } td, th { padding: 5px 10px; border: 1px solid black; } th { background: #284bf8; font-size: 1.3rem; font-weight: 450; color: white; cursor: pointer; } .form { width: 80%; padding: 10px; margin: 0 auto; } h1 { text-align: center; } tr:hover { background: #a1a4b5; } </style> <body> <div class="form"> <h1>图书信息管理系统</h1> <br /> </div> <table> <tr> <th>序号</th> <th>书籍名称</th> <th>作者</th> <th>页数</th> <th>添加时间</th> <th>操作</th> </tr> <c:forEach items="${personList }" var="person" varStatus="item"> <tr> <td>${item.index+1 }</td> <td>${person.bookname }</td> <td>${person.author }</td> <td>${person.pages }</td> <td>${person.createtime }</td> <td><a style="color: red" onclick="del(${person.id })">删除</a> <a href="getbyid.do?id=${person.id }">修改</a></td> </tr> </c:forEach> <tr style="text-align: left;"> <td colspan="6"><a href="getpage.do">添加</a></td> </tr> </table> <script type="text/javascript"> function del(id){ if(confirm("确认要删除吗?")){ return window.location.href="deleteByid.do?id="+id; }else { return false; } } </script> </body> </html>