Resource download: https://download.csdn.net/download/weixin_44893902/35123371
Exercise point design: add, delete, modify
1, Language and environment
- Implementation language: JAVA language.
- Environment requirements: MyEclipse/Eclipse + Tomcat + MySql.
- Use technology: Jsp+Servlet+JavaBean or spring MVC + Spring + mybatis.
2, Realize function
In order to facilitate the school to manage books, a set of book information management system with BS structure is developed. The main functions are as follows:
- The home page displays all book information by default, and is arranged in descending order according to the addition time.
(1) Sort in descending order of addition time.
(2) The add book button is displayed at the bottom.
- Click the "add book" link to jump to the book addition interface.
(1) Add time: the current time is selected by default.
3. After the user enters the complete information and submits it, it is required to automatically jump to the list interface. At this time, the list interface displays the newly added book information (in descending order according to the addition time, which should be in the first item).
4. Click the delete hyperlink in the "list" interface to delete, and then the list will be refreshed automatically.
5. The user clicks the modify hyperlink in the "list" interface, jumps to the modify page, and echoes the book information to be modified on this page
,
3, Database design
- Create a database (person_db).
- Create a tb_person with the following structure.
Field name | explain | Field type | length | remarks |
---|---|---|---|---|
id | number | int | Primary key, self increment, increment is 1 | |
BookName | Book name | varchar | 50 | Cannot be empty |
author | author | varchar | 10 | Cannot be empty |
pages | the number of pages | Int | Cannot be empty | |
createTime | Creation time | datetime | Cannot be empty |
4, Recommended implementation steps
- The implementation steps of JSP version are as follows:
(1) Build database and tables according to the above database requirements, and add test data (no less than 5, and the test data does not need to be consistent with the above figure).
(2) Create a Web project, create various packages, and import the jar files required by the project.
(3) Create a Book entity class.
(4) Create a Servlet to obtain different requests from users, and forward these requests to the corresponding business methods of the business processing layer.
(5) Create a business processing layer, in which business methods are defined and system requirements are implemented. DAO methods need to be executed in these business methods.
(6) Create BaseDAO tool class and use JDBC to complete the function method code of querying, deleting and adding data table data.
(7) Write a JSP page to display the query results of the data.
2. The implementation steps of SSM version are as follows:
(1) Create database, create data table and add test data (no less than 5, and the test data does not need to be consistent with the above figure).
(2) Create a Web project, create various packages, and import the jar files required by the project.
(3) Add relevant SSM framework support.
(4) Various configuration files required by the configuration project (mybatis configuration file, spring configuration file, spring MVC configuration file).
(5) Create an entity class.
(6) Mapper interface required to create MyBatis operation database and its Xml mapping database operation statement file.
(7) Create corresponding interfaces and implementation classes of business logic, implement corresponding businesses, and add references and injections to DAO/Mapper in the classes.
(8) Create the Controller class, add reference and injection to the business logic class in the Controller, and configure the spring MVC configuration file.
(9) Create relevant operation pages and beautify the pages with CSS.
(10) Realize various operation functions of the page, and the operation should be humanized.
(11) After debugging and running successfully, export relevant database files and submit them.
5, Implementation code
1. MySQL database
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', '<A dream of Red Mansions', 'Cao Xueqin', '542', '2021-07-20 10:44:26'); INSERT INTO `tb_person` VALUES ('2', '<Outlaws of the marsh', 'Shi Naian', '652', '2021-07-20 10:44:57'); INSERT INTO `tb_person` VALUES ('3', '<Mirror Flower', 'Li Ruzhen', '441', '2021-07-20 10:45:59'); INSERT INTO `tb_person` VALUES ('5', '<Journey to the West', 'Wu Chengen', '5000', '2021-07-20 12:42:43'); INSERT INTO `tb_person` VALUES ('7', '<Romance of the Three Kingdoms', 'Luo Guanzhong', '10000', '2021-07-20 12:42:07');
2. Project Java code
directory structure
person_db
JAR package:
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"; } //Add page Jump @RequestMapping("getpage") public String getpage() { return "/addPage"; } //add to @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"; } //Query by id @RequestMapping("getbyid") public String getbyid(Model model,int id) { TbPerson tbPerson=service.getByid(id); model.addAttribute("tbPerson", tbPerson); return "/addPage"; } //modify @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 { //Query all List<TbPerson> selsctAll(); //delete int delete(int id); //Query by id TbPerson getByid(int id); //modify int update(TbPerson tbPerson); //add to 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", Do not generate Example */ public void generateMyBatis() { //Warning messages during MBG execution List<String> warnings = new ArrayList<String>(); //When the generated code is repeated, the original code is overwritten boolean overwrite = true ; String generatorFile = "/generatorConfig.xml"; //String generatorFile = "/generator/generatorConfigExample.xml"; //Read MBG configuration file InputStream is = Generator.class.getResourceAsStream(generatorFile); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config; try { config = cp.parseConfiguration(is); DefaultShellCallback callback = new DefaultShellCallback(overwrite); //Create MBG MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); //Execute generated code 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> <!-- alias --> <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"/> <!-- Data source configuration --> <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> <!-- to configure SqlSessionFactory --> <bean class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- set up MyBatis Core profile --> <property name="configLocation" value="classpath:MyBatis/SqlMapConfig.xml"></property> <!-- set up data sources --> <property name="dataSource" ref="dataSource"></property> </bean> <!-- to configure Mapper scanning --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- set up Mapper Scan package --> <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 "> <!-- to configure Service Layer scanning --> <context:component-scan base-package="com.service"></context:component-scan> <!-- Configure transaction management --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- Enable annotation mode management AOP affair --> <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 "> <!-- to configure Controller Layer scan package --> <context:component-scan base-package="com.controller"></context:component-scan> <!-- Configure annotation driven --> <mvc:annotation-driven></mvc:annotation-driven> <!-- Configure view parser --> <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"> <!-- Configuration Generator --> <generatorConfiguration> <context id="MySQLContext" targetRuntime="MyBatis3Simple" defaultModelType="flat"> <!-- Configure leading and trailing delimiters --> <property name="beginningDelimiter" value="`"/> <property name="endingDelimiter" value="`"/> <!-- Configure comment information --> <commentGenerator> <!-- Do not generate comments --> <property name="suppressAllComments" value="true"/> <property name="suppressDate" value="true"/> <property name="addRemarkComments" value="true"/> </commentGenerator> <!-- Database connection configuration --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/person_db" userId="root" password="123456"> </jdbcConnection> <!-- targetPackage: Generate the package name stored in the entity class, targetProject: Specify the target project path, either relative or absolute --> <javaModelGenerator targetPackage="com.entity" targetProject="src"> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- to configure SQL Mapper Mapper.xml File properties --> <sqlMapGenerator targetPackage="com.dao" targetProject="src"/> <!-- type="XMLMAPPER": All the methods are in use XML Interface call dependency XML file --> <javaClientGenerator targetPackage="com.dao" type="XMLMAPPER" targetProject="src"/> <!-- Generate mappings for all tables --> <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>Add books</h1> <form action="addPerson.do"> </c:if> <c:if test="${tbPerson.id!=null }"> <h1>Revise books</h1> <form action="update.do"> </c:if> <input type="hidden" name="id" value="${tbPerson.id }" /> <p> <label>Book Name:</label> <input type="text" name="bookname" value="${tbPerson.bookname }" /> </p> <p> <label>Author:</label> <input type="text" name="author" value="${tbPerson.author }" /> </p> <p> <label>the number of pages:</label> <input type="number" name="pages" value="${tbPerson.pages }" /> </p> <p> <button type="submit">Submit</button> <input type="button" onclick="window.history.back();" value="cancel"> </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>Library information management system</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>Library information management system</h1> <br /> </div> <table> <tr> <th>Serial number</th> <th>Book name</th> <th>author</th> <th>the number of pages</th> <th>Add time</th> <th>operation</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 })">delete</a> <a href="getbyid.do?id=${person.id }">modify</a></td> </tr> </c:forEach> <tr style="text-align: left;"> <td colspan="6"><a href="getpage.do">add to</a></td> </tr> </table> <script type="text/javascript"> function del(id){ if(confirm("Are you sure you want to delete?")){ return window.location.href="deleteByid.do?id="+id; }else { return false; } } </script> </body> </html>