内容接上一篇文章
文件目录如上图
上一篇内容完成了项目的创建,接下来在该结构的基础上完成增删改查功能
一.查询
1.创建实体UserInfo
在bean目录下建立UserInfo类,要记住不能添加构造方法
package com.huchengyue.bean;
public class UserInfo {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "UserInfo{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
2.在dao文件夹下建立IUserDao接口,定义数据库操作方法findAll
package com.huchengyue.dao;
import com.huchengyue.bean.UserInfo;
import java.util.List;
public interface IUserDao {
public List<UserInfo> findAll();
}
3.在service文件夹下建立IUserService接口,定义业务逻辑处理函数
package com.huchengyue.service;
import com.huchengyue.bean.UserInfo;
import java.util.List;
public interface IUserService {
public List<UserInfo> findAll();
}
4.在service下再创建impl包,在包中完成IUserService的接口的实现UserServiceImpl
package com.huchengyue.service.impl;
import com.huchengyue.bean.UserInfo;
import com.huchengyue.dao.IUserDao;
import com.huchengyue.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
//把类放到容器中
@Service
public class UserServiceImpl implements IUserService {
//从容器中取对象
@Autowired
IUserDao userDao;
@Override
public List<UserInfo> findAll() {
return userDao.findAll();
}
}
其中@Service注解可以把类注册到Spring容器中,@Autowired会自动从Spring容器中获得对象,不需要new
5.在controller文件夹下建立UserController类完成路由映射页面跳转
package com.huchengyue.controller;
import com.huchengyue.bean.UserInfo;
import com.huchengyue.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
private IUserService userService;
@RequestMapping("/findAll.do")
public ModelAndView findAll(){
List<UserInfo> userInfos = userService.findAll();
ModelAndView mv = new ModelAndView();
mv.addObject("ui",userInfos);
mv.setViewName("allUser");
return mv;
}
}
6.在resources下载建立mapper文件夹定义数据库具体操作
在mapper下建立UserMapper.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.huchengyue.dao.IUserDao" >
<select id="findAll" resultType="com.huchengyue.bean.UserInfo">
select * from userinfo
</select>
</mapper>
7.添加applicationContext.xml、db.properties、log4j.properties、spring-mvc.xml
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 1.配置数据库相关参数properties的属性:${url} -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 2.配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="2"/>
</bean>
<!-- 3.配置SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 扫描bean包 使用别名 -->
<property name="typeAliasesPackage" value="com.huchengyue.bean"></property>
<!--配置加载映射文件 UserMapper.xml-->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!-- 自动生成dao,mapper-->
<!-- 4.配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="com.huchengyue.dao"/>
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!--自动扫描-->
<context:component-scan base-package="com.huchengyue"/>
<!-- 配置事务-->
<!-- 5.配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 6.开启事务注解-->
<tx:annotation-driven></tx:annotation-driven>
</beans>
要记住把里边的包结构改成自己的
db.properties:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?useSSL=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123
把数据库连接配置成自己的
log4j.properties:
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 1.注解扫描位置-->
<context:component-scan base-package="com.huchengyue.controller" />
<!-- 2.配置映射处理和适配器-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
<!-- 3.视图的解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
同样改成自己的包名
这里添加的4个文件与上一篇文章说的不太一样,以这里为主,先看一下resources的目录结构
8.编写jsp
在webapp下的jsp中添加allUser.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>user列表</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
基于SSM框架的管理系统:简单实现增、删、改、查。
</h1>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>用户列表 —— 显示所有用户</small>
</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 column">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/user/toAddUser.do">新增</a>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-hover table-striped">
<thead>
<tr>
<th>id</th>
<th>用户名</th>
<th>密码</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach items="${ui}" var="userInfo">
<tr>
<td>${userInfo.id}</td>
<td>${userInfo.username}</td>
<td>${userInfo.password}</td>
<td>
<a href="${pageContext.request.contextPath}/user/toUpdate.do?id=${userInfo.id}">更改</a> |
<a href="${pageContext.request.contextPath}/user/delete.do?id=${userInfo.id}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
再在webapp下的index.jsp做修改,添加跳转的a标签
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<a href="${pageContext.request.contextPath}/user/findAll.do">查询所有</a>
<html>
<head>
<title>eTitl</title>
</head>
<body>
<h1>helloword</h1>
</body>
</html>
9.配置tomcat
点击ok,也可以为它改个名字,也可以不改。
10.添加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"
version="3.1">
<!-- 配置加载类路径的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>
<!-- 配置监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<!-- 解决中文乱码过滤器 -->
<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>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 前端控制器(加载classpath:spring-mvc.xml 服务器启动创建servlet) -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置初始化参数,创建完DispatcherServlet对象,加载springmvc.xml配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<!-- 服务器启动的时候,让DispatcherServlet对象创建 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
11.运行tomcat,自动弹出页面,也可以选择访问127.0.0.1:8080
二.增加
了解了查询,新增就容易多了,只需要对应添加相应的类与方法,以及配置对应的文件即可。
首先点击新增,跳转到新增页面,于是再jsp文件夹下添加增加的jsp页面:addUser.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>新增用户</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
基于SSM框架的管理系统:简单实现增、删、改、查。
</h1>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>新增用户</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/user/save.do"
method="post">
用户姓名:<input type="text" name="username"><br><br><br>
用户密码:<input type="text" name="password"><br><br><br>
<input type="submit" value="添加" >
</form>
</div>
然后在UserController中添加
@RequestMapping("/toAddUser.do")
public ModelAndView addUser(){
ModelAndView mv = new ModelAndView();
mv.setViewName("addUser");
return mv;
}
此时运行tomcat点击新增就可看到页面
这里我输入了新增数据,但新增具体还没有实现,我们需要添加新增的方法
在IUserDao中添加
public boolean addUser(UserInfo user);
在IUserService中添加
public boolean addUser(UserInfo user);
在UserServiceImpl中添加
@Override
public boolean addUser(UserInfo user) {
return userDao.addUser(user);
}
并且在UserMapper.xml中添加对应语句
<insert id="addUser">
insert into userinfo(username,password)
values(#{username},#{password})
</insert>
最后在UserController中添加
@RequestMapping("/save.do")
public String saveUser(UserInfo user){
userService.addUser(user);
return "redirect:/user/findAll.do";
}
完成点击添加后的业务处理与页面跳转
三.删除
为了方便起见,我先把之后会用到的关于数据库操作的方法都贴出来,一会只具体写业务逻辑
IUserDao:
package com.huchengyue.dao;
import com.huchengyue.bean.UserInfo;
import java.util.List;
public interface IUserDao {
public List<UserInfo> findAll();
public boolean addUser(UserInfo user);
public boolean deleteUser(int id);
public boolean updateUser(UserInfo user);
public List<UserInfo> findOne(int id);
}
IUserService:
package com.huchengyue.service;
import com.huchengyue.bean.UserInfo;
import java.util.List;
public interface IUserService {
public List<UserInfo> findAll();
public boolean addUser(UserInfo user);
public boolean deleteUser(int id);
public boolean updateUser(UserInfo user);
public List<UserInfo> findOne(int id);
}
UserServiceImpl
package com.huchengyue.service.impl;
import com.huchengyue.bean.UserInfo;
import com.huchengyue.dao.IUserDao;
import com.huchengyue.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
//把类放到容器中
@Service
public class UserServiceImpl implements IUserService {
//从容器中取对象
@Autowired
IUserDao userDao;
@Override
public List<UserInfo> findAll() {
return userDao.findAll();
}
@Override
public boolean addUser(UserInfo user) {
return userDao.addUser(user);
}
@Override
public boolean deleteUser(int id) {
return userDao.deleteUser(id);
}
@Override
public boolean updateUser(UserInfo user) {
return userDao.updateUser(user);
}
@Override
public List<UserInfo> findOne(int id) {
return userDao.findOne(id);
}
}
UserMapper.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.huchengyue.dao.IUserDao" >
<select id="findAll" resultType="com.huchengyue.bean.UserInfo">
select * from userinfo
</select>
<insert id="addUser">
insert into userinfo(username,password)
values(#{username},#{password})
</insert>
<delete id="deleteUser">
delete from userinfo where id=#{id}
</delete>
<select id="findOne" resultType="com.huchengyue.bean.UserInfo">
select * from userinfo where id=#{id}
</select>
<update id="updateUser">
update userinfo set username=#{username}, password=#{password} where id=#{id};
</update>
</mapper>
接下来说删除,删除只需要根据传来的id执行删除就可以,删除后刷新页面
@RequestMapping("/delete.do")
public String deleteUser(int id){
userService.deleteUser(id);
return "redirect:/user/findAll.do";
}
四.修改
点击修改后进入修改界面,这个过程是要根据选择的id查询到用户,并把userinfo对象传递到修改页面,然后在页面上修改后点击提交跳回到findAll页面
点击更改
@RequestMapping("/toUpdate.do")
public ModelAndView toUpdateUser(int id){
List<UserInfo> userInfos = userService.findOne(id);
UserInfo userInfo = userInfos.get(0);
ModelAndView mv = new ModelAndView();
mv.addObject("userInfo",userInfo);
mv.setViewName("updateUser");
return mv;
}
进入修改页面
然后点击提交
@RequestMapping("/update.do")
public String updateUser(UserInfo user){
userService.updateUser(user);
return "redirect:/user/findAll.do";
}