基于SSM框架的增删改查

写在前面: 我是「扬帆向海」,这个昵称来源于我的名字以及女朋友的名字。我热爱技术、热爱开源、热爱编程。技术是开源的、知识是共享的。

这博客是对自己学习的一点点总结及记录,如果您对 Java算法 感兴趣,可以关注我的动态,我们一起学习。

用知识改变命运,让我们的家人过上更好的生活

源码地址: https://github.com/zhangxycg/ssm_crud

如要查看源码,请点击我

视频地址: https://www.bilibili.com/video/av21045215

尚硅谷Java视频教程

一、使用的技术

    基础框架: ssm(SpringMVC + Spring + MyBatis)
    前端框架: Bootstrap
    数据库: MySQL
    项目的依赖管理: Maven
    分页: pagehelper
    逆向工程: MyBatis Generator

二、环境的搭建

  1. 创建一个maven工程

  2. 在pom文件中引入项目依赖的jar包
    • spring
    • springmvc
    • mybatis
    • 数据库连接池(c3p0)
    • mysql驱动包
    • 其他(jstl,servlet-api,junit)

  3. 引入bootstrap前端框架

  4. 编写ssm整合的关键配置文件
    web.xml,spring,springmvc,mybatis,使用mybatis的逆向工程生成对应的 pojo 以及 mapper

  5. 测试mapper

项目使用的表结构

部门表

CREATE TABLE `tbl_dept` (
  `dept_id` int(11) NOT NULL AUTO_INCREMENT,
  `dept_name` varchar(255) NOT NULL,
  PRIMARY KEY (`dept_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

员工表

CREATE TABLE `tbl_emp` (
  `emp_id` int(11) NOT NULL AUTO_INCREMENT,
  `emp_name` varchar(255) NOT NULL,
  `gender` char(1) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `d_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`emp_id`),
  KEY `fk_emp_dept` (`d_id`),
  CONSTRAINT `fk_emp_dept` FOREIGN KEY (`d_id`) REFERENCES `tbl_dept` (`dept_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2020 DEFAULT CHARSET=utf8;

三、页面效果图

在这里插入图片描述

四、项目结构图

在这里插入图片描述

五、功能及其实现逻辑

1. 查询功能
  1. 在浏览器访问 index.jsp 页面
  2. index.jsp 页面发出查询员工列表的请求
  3. 后台 EmployeeController 接收前台发过来的请求,查出员工数据
  4. 来到 list.jsp 页面进行展示查询出的数据
  5. pageHelper 分页插件完成分页查询功能
2. 新增功能

在这里插入图片描述

  1. 在 index.jsp 页面点击 “ 新增 ” 按钮
  2. 弹出员工新增的对话框
  3. 然后去数据库查询部门列表,显示在对话框中
  4. 用户输入数据,并进行校验
  5. jquery前端校验,ajax用户名重复校验,重要数据(后端校验使用了JSR303);
  6. 数据填写正确,点击保存按钮
3. 修改功能

在这里插入图片描述

  1. 在页面点击 “编辑” 按钮
  2. 弹出用户修改的模态框
  3. 修改数据(用户名无法修改)
  4. 修改完成,点击 “更新 ” 按钮,完成用户修改
4. 删除功能

在这里插入图片描述

  1. 单个删除
    点击删除按钮,弹出提示信息,点击确定。将会删除数据
  2. 批量删除
    勾选员工姓名前的选择框,可以实现批量删除

六、 踩坑

第一次踩坑连接不上数据库 ,报错信息如下

java.sql.SQLException: The server time zone value '?й???????' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73)
	at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76)
	at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:835)
	at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:455)
	at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240)
	at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:199)
	at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:175)
	at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:220)
	at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:206)
	at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:203)
	at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1138)
	at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1125)
	at com.mchange.v2.resourcepool.BasicResourcePool.access$700(BasicResourcePool.java:44)
	at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1870)
	at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:696)
Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value '?й???????' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
	at sun.reflect.GeneratedConstructorAccessor45.newInstance(Unknown Source)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
	at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
	at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:85)
	at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:132)
	at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2243)
	at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2267)
	at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1319)
	at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:966)
	at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:825)
	... 12 more


在这里插入图片描述
报错原因是

在使用mysql的jdbc驱动最新版(6.0+)版本时,数据库和系统时区差异引起的问题。

解决办法:

第一种是 降低驱动的版本

第二种是:在jdbc连接的url后面加上 ?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&characterEncoding=UTF8

在这里插入图片描述

第二次踩坑字新增与修改完成以后,员工数据不按 id 进行升序排列

解决办法:

修改 EmployeeMapper.xml 中的查询语句,使员工数据按 员工 id 进行升序排列
在这里插入图片描述

<select id="selectByExampleWithDept" resultMap="WithDeptResultMap">
        select
        <if test="distinct">
            distinct
        </if>
        <include refid="WithDept_Column_List" />
        FROM tbl_emp e
        left join tbl_dept d on e.`d_id`=d.`dept_id`
        <if test="_parameter != null">
            <include refid="Example_Where_Clause" />
        </if>
        <!-- 员工数据根据id进行升序排列 -->
        order by e.`emp_id`  asc
    </select>
SSM框架是指Spring+SpringMVC+MyBatis三大框架的整合,下面提供一个基于SSM框架增删改查页面示例: 首先,我们需要在SpringMVC的配置文件中添加视图解析器和处理器映射器: ```xml <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 处理器映射器 --> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" /> <!-- 处理器适配器 --> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" /> ``` 然后,我们需要编写一个Controller类来处理页面请求,并且调用Service层来实现增删改查的操作: ```java @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping(value = "/list", method = RequestMethod.GET) public ModelAndView userList() { ModelAndView modelAndView = new ModelAndView("userList"); List<User> userList = userService.findAllUsers(); modelAndView.addObject("userList", userList); return modelAndView; } @RequestMapping(value = "/add", method = RequestMethod.GET) public ModelAndView addUserPage() { ModelAndView modelAndView = new ModelAndView("addUser"); return modelAndView; } @RequestMapping(value = "/add", method = RequestMethod.POST) public ModelAndView addUser(User user) { ModelAndView modelAndView = new ModelAndView("redirect:/user/list"); userService.addUser(user); return modelAndView; } @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) public ModelAndView deleteUser(@PathVariable("id") int id) { ModelAndView modelAndView = new ModelAndView("redirect:/user/list"); userService.deleteUser(id); return modelAndView; } @RequestMapping(value = "/update/{id}", method = RequestMethod.GET) public ModelAndView updateUserPage(@PathVariable("id") int id) { ModelAndView modelAndView = new ModelAndView("updateUser"); User user = userService.findUserById(id); modelAndView.addObject("user", user); return modelAndView; } @RequestMapping(value = "/update", method = RequestMethod.POST) public ModelAndView updateUser(User user) { ModelAndView modelAndView = new ModelAndView("redirect:/user/list"); userService.updateUser(user); return modelAndView; } } ``` 在以上Controller类的代码中,我们提供了五个请求方法: 1. `userList()`:用于展示所有用户信息的页面; 2. `addUserPage()`:用于展示添加用户信息的页面; 3. `addUser(User user)`:用于接收添加用户信息的表单数据; 4. `deleteUser(int id)`:用于删除指定用户信息; 5. `updateUserPage(int id)`:用于展示修改指定用户信息的页面; 6. `updateUser(User user)`:用于接收修改用户信息的表单数据。 最后,我们需要编写相应的JSP页面来展示数据和表单。比如我们可以编写一个userList.jsp页面来展示所有用户信息: ```html <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>User List</title> </head> <body> <h1>User List</h1> <table> <thead> <tr> <th>ID</th> <th>Name</th> <th>Age</th> <th>Gender</th> <th>Phone</th> <th>Email</th> <th>Action</th> </tr> </thead> <tbody> <c:forEach items="${userList}" var="user"> <tr> <td>${user.id}</td> <td>${user.name}</td> <td>${user.age}</td> <td>${user.gender}</td> <td>${user.phone}</td> <td>${user.email}</td> <td> <a href="<c:url value='/user/update/${user.id}'/>">Edit</a> <a href="<c:url value='/user/delete/${user.id}'/>">Delete</a> </td> </tr> </c:forEach> </tbody> </table> <a href="<c:url value='/user/add'/>">Add User</a> </body> </html> ``` 在以上JSP页面的代码中,我们使用了JSTL标签库来遍历所有用户信息,并且提供了“Add User”、“Edit”和“Delete”三个超链接来触发相关请求方法。 其他的JSP页面也类似,只需要根据表单数据的不同来进行相应的处理即可。
评论 23
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值