资源下载:https://download.csdn.net/download/weixin_44893902/35123371
练习点设计:添加、删除、修改
Jsp
+Servle
t+JavaBean
或SpringMVC
+ Spring
+ Mybatis
。为了方便学校对图书进行管理,开发一套BS结构的图书信息管理系统,主要功能如下:
3. 用户输入完整信息提交以后,要求自动跳转至列表界面,此时列表界面显示新增的书籍信息(按添加时间降序排列,应该在第一条)。
4. 用户点击“列表”界面中的删除超链接,执行删除操作,然后列表进行自动刷新。
5. 用户点击“列表”界面中的修改超链接,跳转到修改页面,并在该页面回显需要修改的书籍信息.
、
person_db
)。tb_person
),结构如下。字段名 | 说明 | 字段类型 | 长度 | 备注 |
---|---|---|---|---|
id | 编号 | int | 主键,自增,增量为1 | |
BookName | 书籍名称 | varchar | 50 | 不能为空 |
author | 作者 | varchar | 10 | 不能为空 |
pages | 页数 | Int | 不能为空 | |
createTime | 创建时间 | datetime | 不能为空 |
/*
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');
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";
}
}
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
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>
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;
}
}
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);
}
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;
}
}
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();
}
}
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>
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>
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
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>
<javaModelGenerator targetPackage="com.entity" targetProject="src">
<property name="trimStrings" value="true"/>
javaModelGenerator>
<sqlMapGenerator targetPackage="com.dao" targetProject="src"/>
<javaClientGenerator targetPackage="com.dao" type="XMLMAPPER"
targetProject="src"/>
<table tableName="%">table>
context>
generatorConfiguration>
web.xml
<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_dbdisplay-name>
<welcome-file-list>
<welcome-file>index.htmlwelcome-file>
<welcome-file>index.htmwelcome-file>
<welcome-file>index.jspwelcome-file>
<welcome-file>default.htmlwelcome-file>
<welcome-file>default.htmwelcome-file>
<welcome-file>default.jspwelcome-file>
welcome-file-list>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring/applicationContext-*.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring/spring-mvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>*.dourl-pattern>
servlet-mapping>
<filter>
<filter-name>CharacterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>forceEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
web-app>
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 heretitle>
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 heretitle>
<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>