大家好,又见面了,我是你们的朋友全栈君。
本次ssm整合是对于初学者来说的第一次整合,里面还有很多地方可以进行优化,这点以后有空再分享。主要是体现整合的思路和过程。
1、准备数据
代码语言:javascript复制/*创建用户表*/
CREATE TABLE `user`(
id BIGINT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50),
password VARCHAR(50),
email VARCHAR(50),
phoneNum VARCHAR(20)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
/*初始化用户数据*/
insert into `user`(username,password,email,phoneNum)
values('xiaom','123456','xiaom@qq.com','020-8888888');
insert into `user`(username,password,email,phoneNum)
values('zhangs','123456','zhangs@qq.com','020-8888888');
[外链图片转存失败(img-lUUAIR4Q-1567593872014)(C:Users宏昌AppDataRoamingTyporatypora-user-images1567574368565.png)]
2、创建项目结构
[外链图片转存失败(img-4p2pH1Dm-1567593872015)(C:Users宏昌AppDataRoamingTyporatypora-user-images1567574585963.png)]
2.1 创建实体类
代码语言:javascript复制package com.itheima.pojo;
public class User {
private Integer id;//用户id
private String username;// 用户名称
private String password;// 用户密码
private String email;// 用户邮箱
private String phoneNum;// 用户联系电话
public Integer getId() {
return id;
}
public void setId(Integer 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;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public String toString() {
return "User{"
"id=" id
", username='" username '''
", password='" password '''
", email='" email '''
", phoneNum='" phoneNum '''
'}';
}
}
2.2 创建持久层接口
代码语言:javascript复制package com.itheima.dao;
import com.itheima.pojo.User;
import java.util.List;
public interface UserDao {
/** * 查找全部用户 */
List<Usre> findAllUser();
}
2.3 持久层实现类
代码语言:javascript复制package com.itheima.dao;
import com.itheima.pojo.User;
import java.util.List;
public class UserDaoImpl implements UserDao{
/** * 查找所有用户 */
@Override
public List<User> findAllUser() {
System.out.println("查找所有人");//测试用
return null;
}
}
2.4 业务层接口
代码语言:javascript复制package com.itheima.service;
import com.itheima.pojo.User;
import java.util.List;
public interface UserService {
/** * 查找所有用户 */
List<User> findAllUser();
}
2.5业务层实现类
代码语言:javascript复制package com.itheima.service;
import com.itheima.pojo.User;
import java.util.List;
public class UserServiceImpl implements UserService {
private UserDao userDao;
/** * 查找所有用户 */
@Override
public List<User> findAllUser() {
return userDao.findAllUser();
}
}
3、确保spring能够单独运行
3.1配置pom文件
代码语言:javascript复制<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.itheima</groupId>
<artifactId>spring_zhenghe</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<!--spring 版本-->
<spring.version>5.0.2.RELEASE</spring.version>
</properties>
<dependencies>
<!--spring ioc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
</project>
3.2为持久层实现类配置注解
代码语言:javascript复制package com.itheima.dao;
import com.itheima.pojo.User;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository("userDao")
public class UserDaoImpl implements UserDao{
/** * 查找所有用户 */
@Override
public List<User> findAllUser() {
System.out.println("查找所有人");
return null;
}
}
3.3为业务层实现类添加注解
代码语言:javascript复制package com.itheima.service;
import com.itheima.dao.UserDao;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
/** * 查找所有用户 */
@Override
public List<User> findAllUser() {
return userDao.findAllUser();
}
}
3.4编写bean.xml
代码语言:javascript复制<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--配置包扫描dao/service,说明: 第一步:导入context名称空间和约束 第二步:通过<context:component-scan/>标签配置,spring框架在 创建ioc容器的时候,会扫描指定的包和它的子包 -->
<context:component-scan base-package="com.itheima"></context:component-scan>
</beans>
3.5编写测试类
代码语言:javascript复制package com.itheima;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class TestSpring {
@Test
public void testspring(){
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:bean.xml");
UserService service = (UserService) ac.getBean("userService");
service.findAllUser();
}
}
测试结果正确
[外链图片转存失败(img-4B1xV6sH-1567593872016)(C:Users宏昌AppDataRoamingTyporatypora-user-images1567584034103.png)]
4、确保Springmvc能够运行
4.1配置pom
代码语言:javascript复制<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.itheima</groupId>
<artifactId>spring_zhenghe</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<!--spring 版本-->
<spring.version>5.0.2.RELEASE</spring.version>
<!-- jstl标签版本 -->
<jstl.version>1.2</jstl.version>
<!--servlet版本-->
<servlet.version>2.5</servlet.version>
<!--jsp版本-->
<jsp.version>2.0</jsp.version>
</properties>
<dependencies>
<!--spring ioc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!--junit4-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- spring webmvc依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- jstl标签依赖 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!--servlet依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<!--jsp依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<!--配置插件-->
<plugins>
<!--maven tomcat插件-->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<!-- tomcat 的端口号 -->
<port>8080</port>
<!-- 访问应用的路径 -->
<path>/ssm</path>
<!-- URL按UTF-8进行编码,解决中文参数乱码 -->
<uriEncoding>UTF-8</uriEncoding>
<!-- tomcat名称 -->
<server>tomcat7</server>
</configuration>
</plugin>
</plugins>
</build>
</project>
4.2编写配置文件springmvc.xml
代码语言:javascript复制<?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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--配置扫描controller-->
<context:component-scan base-package="com.itheima.ssm.controller"/>
<!--注解驱动方式配置处理器映射器和处理器适配器-->
<mvc:annotation-driven/>
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--配置视图的公共目录路径-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--配置视图的扩展名称-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
4.3 配置web.xml
代码语言:javascript复制<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>ssm</display-name>
<!-- 配置字符集编码过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!-- 指定使用的编码:UTF-8 -->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<!-- 配置所有请求都经过字符集编码过滤器处理 -->
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置前端控制器:DispatcherServlet-->
<servlet>
<servlet-name>ssm</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--加载springmvc主配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!--配置什么时候加载前端控制器,说明: 1.配置大于等于0的整数,表示在web容器启动的时候加载 2.配置小于0的整数,表示在第一次请求到达的时候加载 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ssm</servlet-name>
<!--配置拦截的url规则,说明: 1.*.do,表示以.do结尾的请求进入前端控制器 2./,表示所有请求都进入前端控制器 -->
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
4.4编写首页显示代码
代码语言:javascript复制<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--导入jstl标签库--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>用户列表jsp页面</title>
<style>
table {border:1px solid #000000}
table th{border:1px solid #000000}
table td{border:1px solid #000000}
</style>
<script>
// 添加用户
function add(id) {
window.location.href="${pageContext.request.contextPath}/add.do";
}
// 修改用户
function get(id) {
window.location.href="${pageContext.request.contextPath}/get.do?id=" id;
}
// 删除用户
function removeUser(id) {
if(confirm("确定要删除吗?")){
window.location.href="${pageContext.request.contextPath}/remove.do?id=" id;
}
}
</script>
</head>
<body>
用户列表:<button type="button" οnclick="add()">添加用户</button>
<table cellpadding="0" cellspacing="0" width="80%">
<tr>
<th>用户Id</th>
<th>用户名称</th>
<th>邮箱</th>
<th>联系电话</th>
<th>操作</th>
</tr>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.username}</td>
<td>${user.email}</td>
<td>${user.phoneNum}</td>
<td>
<button type="button" οnclick="get('${user.id}')">修改</button>
<button type="button" οnclick="removeUser('${user.id}')">删除</button>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
4.5 编写Controller测试类
代码语言:javascript复制package com.itheima.controller;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.List;
@Controller
public class UserController {
@RequestMapping("/list.do")
public String findAllUser(Model model){
List<User> users = new ArrayList<>();
//测试需要,把用户写死
User user = new User();
user.setId(1);
user.setUsername("张三");
user.setPassword("123");
user.setEmail("xiaom@qq.com");
user.setPhoneNum("020-8888888");
users.add(user);
model.addAttribute("users",users);
return "list";
}
}
测试结果正确:
[外链图片转存失败(img-Y2ZgzFNL-1567593872018)(C:Users宏昌AppDataRoamingTyporatypora-user-images1567585004999.png)]
5、整合Spring框架和SpringMvc框架
5.1web.xml配置监听器
代码语言:javascript复制 <!--指定spring配置文件位置-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext.xml</param-value>
</context-param>
<!--配置ContextLoaderListener监听器,说明: 1.ContextLoaderListener监听器,监听ServletContext对象的创建。一旦ServletContext对象创建, 它立即帮助我们创建spring容器,并且放入ServletContext域中。 2.该监听器,默认只能加载WEB-INF目录下,名称为applicationContext.xml的配置文件 3.通过context-param标签,配置指定spring的配置文件位置,改变默认行为。 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
6、确保Mybatis框架能够运行
6.1配置pom
代码语言:javascript复制<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.itheima</groupId>
<artifactId>spring_zhenghe</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<!--spring 版本-->
<spring.version>5.0.2.RELEASE</spring.version>
<!-- jstl标签版本 -->
<jstl.version>1.2</jstl.version>
<!--servlet版本-->
<servlet.version>2.5</servlet.version>
<!--jsp版本-->
<jsp.version>2.0</jsp.version>
<!-- slf4j日志版本 -->
<slf4j.version>1.7.7</slf4j.version>
<!-- mybatis版本 -->
<mybatis.version>3.4.5</mybatis.version>
<!--mysql驱动版本-->
<mysql.version>5.1.30</mysql.version>
</properties>
<dependencies>
<!--spring ioc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!--junit4-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- spring webmvc依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- jstl标签依赖 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!--servlet依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<!--jsp依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<!-- mybatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mysql驱动依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- slf4j依赖 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
</dependencies>
<build>
<!--配置插件-->
<plugins>
<!--maven tomcat插件-->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<!-- tomcat 的端口号 -->
<port>8080</port>
<!-- 访问应用的路径 -->
<path>/ssm</path>
<!-- URL按UTF-8进行编码,解决中文参数乱码 -->
<uriEncoding>UTF-8</uriEncoding>
<!-- tomcat名称 -->
<server>tomcat7</server>
</configuration>
</plugin>
</plugins>
</build>
</project>
6.2 编写Mabaties核心配置文件sqlMapConfig.xml
代码语言:javascript复制<?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.itheima.pojo"/>
</typeAliases>
<!-- 一个核心配置文件,可以配置多个运行环境,default默认使用哪个运行环境 -->
<environments default="default">
<!-- 其中的一个运行环境,通过id来进行标识-->
<environment id="default">
<!-- 事务管理器type的取值: 1. JDBC:由JDBC进行事务的管理 2. MANAGED:事务由容器来管理,后期学习Spring框架的时候,所有的事务由容器管理 -->
<transactionManager type="JDBC"/>
<!-- 数据源: 1. POOLED:使用mybatis创建的连接池 2. UNPOOLED:不使用连接池,每次自己创建连接 3. JNDI:由服务器提供连接池的资源,我们通过JNDI指定的名字去访问服务器中资源。 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring"/>
<property name="username" value="root"/>
<property name="password" value="zhc1024"/>
</dataSource>
</environment>
</environments>
<!--映射器-->
<mappers>
<!--指定外面的实体类映射文件,注:不是点号-->
<package name="com.itheima.dao"/>
</mappers>
</configuration>
6.3 编写log4j日志文件
代码语言:javascript复制# 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
6.4 编写配置持久层文件编写SQL语句
注:该文件要写在resource文件夹下,并且包名要和UserDao一致
代码语言:javascript复制<?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.itheima.dao.UserDao">
<!--1.查询全部用户列表-->
<select id="findAllUser" resultType="user">
select * from `user`
</select>
</mapper>
6.5 编写测试类
代码语言:javascript复制package com.itheima;
import com.itheima.dao.UserDao;
import com.itheima.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class TestMybatis {
@Test
public void testMybatis(){
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder();
SqlSessionFactory build = sfb.build(is);
sqlSession = build.openSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> users = mapper.findAllUser();
System.out.println(users);
} catch (IOException e) {
}finally {
if(sqlSession != null) sqlSession.close();
}
}
}
测试结果正确:
[外链图片转存失败(img-qohhhR6u-1567593872020)(C:Users宏昌AppDataRoamingTyporatypora-user-images1567586906811.png)]
7、整合spring框架和mybatis框架
7.1 配置pom
代码语言:javascript复制<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.itheima</groupId>
<artifactId>spring_zhenghe</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<!--spring 版本-->
<spring.version>5.0.2.RELEASE</spring.version>
<!-- jstl标签版本 -->
<jstl.version>1.2</jstl.version>
<!--servlet版本-->
<servlet.version>2.5</servlet.version>
<!--jsp版本-->
<jsp.version>2.0</jsp.version>
<!-- slf4j日志版本 -->
<slf4j.version>1.7.7</slf4j.version>
<!-- mybatis版本 -->
<mybatis.version>3.4.5</mybatis.version>
<!--mysql驱动版本-->
<mysql.version>5.1.30</mysql.version>
<!-- mybatis-spring整合包版本 -->
<mybatis.spring.version>1.3.1</mybatis.spring.version>
<!--druid版本-->
<druid.version>1.0.29</druid.version>
<!-- aspectj版本号 -->
<aspectj.version>1.6.12</aspectj.version>
</properties>
<dependencies>
<!--spring ioc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!--junit4-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- spring webmvc依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- jstl标签依赖 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!--servlet依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<!--jsp依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<!-- mybatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mysql驱动依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- slf4j依赖 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!--spring jdbc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--aspectj依赖-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.12</version>
</dependency>
<!-- mybatis-spring依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
</dependency>
<!--druid依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
</dependencies>
<build>
<!--配置插件-->
<plugins>
<!--maven tomcat插件-->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<!-- tomcat 的端口号 -->
<port>8080</port>
<!-- 访问应用的路径 -->
<path>/ssm</path>
<!-- URL按UTF-8进行编码,解决中文参数乱码 -->
<uriEncoding>UTF-8</uriEncoding>
<!-- tomcat名称 -->
<server>tomcat7</server>
</configuration>
</plugin>
</plugins>
</build>
</project>
7.2 编写applicationContext-dao.xml文件
编写db.properties配置文件
代码语言:javascript复制db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://127.0.0.1:3306/spring?characterEncoding=utf-8
db.username=root
db.password=zhc1024
代码语言:javascript复制<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--加载db.properties-->
<context:property-placeholder location="classpath:db.properties"/>
<!--配置数据源对象-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<!--连接数据库的四个基本要素-->
<property name="driverClassName" value="${db.driver}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</bean>
<!--配置SqlSessionFactory对象,说明: 1.让spring框架接管SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入数据源对象-->
<property name="dataSource" ref="dataSource"/>
<!--定义别名-->
<property name="typeAliasesPackage" value="com.itheima.pojo"></property>
</bean>
<!--配置自动扫描mapper映射文件-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--指定要扫描的包,说明: 1.如果有多个包要扫描。看是否在同一个父包 2.在同一个父包,配置父包即可 3.不在同一个父包,以半角逗号分割 -->
<property name="basePackage" value="com.itheima.dao"/>
</bean>
</beans>
7.3编写applicationContext-service.xml文件
代码语言:javascript复制<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--配置扫描service-->
<context:component-scan base-package="com.itheima.service"/>
</beans>
7.3编写applicationContext-trans.xml文件
代码语言:javascript复制<?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: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.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源对象-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置aop-->
<aop:config>
<!--配置切入点表达式-->
<aop:pointcut id="pt1" expression="execution(* com.itheima.service..*.*(..))"/>
<!--建立通知与切入点表达式关系-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>
<!--配置通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--配置事务属性-->
<tx:attributes>
<!--配置增、删、改事务规则-->
<tx:method name="insert*" propagation="REQUIRED" read-only="false"/>
<tx:method name="update*" propagation="REQUIRED" read-only="false"/>
<tx:method name="del*" propagation="REQUIRED" read-only="false"/>
<!--配置查询事务规则-->
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
</beans>
7.4编写applicationContext.xml
代码语言:javascript复制<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--导入其它子配置文件-->
<import resource="classpath:applicationContext-dao.xml"/>
<import resource="classpath:applicationContext-service.xml"/>
<import resource="classpath:applicationContext-trans.xml"/>
</beans>
7.8改造UserController
代码语言:javascript复制package com.itheima.controller;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.List;
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/list.do")
public String findAllUser(Model model){
/* List<User> users = new ArrayList<>(); //测试需要,把用户写死 User user = new User(); user.setId(1); user.setUsername("张三"); user.setPassword("123"); user.setEmail("xiaom@qq.com"); user.setPhoneNum("020-8888888"); users.add(user); model.addAttribute("users",users); return "list";*/
List<User> users = userService.findAllUser();
model.addAttribute("users",users);
return "list";
}
}
运行成功:
[外链图片转存失败(img-cIlX8tfm-1567593872023)(C:Users宏昌AppDataRoamingTyporatypora-user-images1567588222762.png)]
8.附上全部代码
项目结构:
[外链图片转存失败(img-NCk320Gv-1567593872026)(C:Users宏昌AppDataRoamingTyporatypora-user-images1567592095218.png)]
8.1 持久层
代码语言:javascript复制package com.itheima.dao;
import com.itheima.pojo.User;
import java.util.List;
public interface UserDao {
/** * 查找所有用户 */
List<User> findAllUser();
/** * 新增用户 */
void insertUser(User user);
/** * 修改状态回显 */
User findUserById(int id);
/** * 修改用户 */
void updateUser(User user);
/** * 删除用户 */
void deleteUser(int id);
}
8.2 实体类
代码语言:javascript复制package com.itheima.pojo;
public class User {
private Integer id;//用户id
private String username;// 用户名称
private String password;// 用户密码
private String email;// 用户邮箱
private String phoneNum;// 用户联系电话
public Integer getId() {
return id;
}
public void setId(Integer 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;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public String toString() {
return "User{"
"id=" id
", username='" username '''
", password='" password '''
", email='" email '''
", phoneNum='" phoneNum '''
'}';
}
}
8.3 业务层
代码语言:javascript复制package com.itheima.service;
import com.itheima.pojo.User;
import java.util.List;
public interface UserService {
/** 查找全部用户 */
List<User> findAllUser();
/** * 新增用户 */
void insertUser(User user);
/** * 修改状态回显 */
User findUserById(int id);
/** * 修改用户 */
void updateUser(User user);
/** * 删除用户 */
void deleteUser(int id);
}
8.4 业务层实现类
代码语言:javascript复制package com.itheima.service;
import com.itheima.dao.UserDao;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public List<User> findAllUser() {
return userDao.findAllUser();
}
@Override
public void insertUser(User user) {
userDao.insertUser(user);
}
@Override
public User findUserById(int id) {
return userDao.findUserById(id);
}
@Override
public void updateUser(User user) {
userDao.updateUser(user);
}
@Override
public void deleteUser(int id) {
userDao.deleteUser(id);
}
}
8.5 控制层
代码语言:javascript复制package com.itheima.controller;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
public class UserController {
@Autowired
private UserService userService;
/** * 显示用户 */
@RequestMapping("list")
public String showAllUser(Model model){
List<User> users = userService.findAllUser();
model.addAttribute("users",users);
return "list";
}
//===========================新增=======================================
/** * 跳转新增用户 */
@RequestMapping("add")
public String add(){
return "add";
}
/** * 新增 */
@RequestMapping("insert")
public String insert(User user){
userService.insertUser(user);
return "redirect:list";
}
//========================修改===================================
//状态回显
@RequestMapping("get")
public String getUser(Model model,Integer id){
User user = userService.findUserById(id);
model.addAttribute("user",user);
return "edit";
}
@RequestMapping("edit")
public String update(User user){
userService.updateUser(user);
return "redirect:list";
}
//====================删除=================================
@RequestMapping("remove")
public String delUser(Integer id){
userService.deleteUser(id);
return "redirect:list";
}
}
8.6 显示用户表
代码语言:javascript复制<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--导入jstl标签库--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>用户列表jsp页面</title>
<style>
table {border:1px solid #000000}
table th{border:1px solid #000000}
table td{border:1px solid #000000}
</style>
<script>
// 添加用户
function add(id) {
window.location.href="${pageContext.request.contextPath}/add.do";
}
// 修改用户
function get(id) {
window.location.href="${pageContext.request.contextPath}/get.do?id=" id;
}
// 删除用户
function removeUser(id) {
if(confirm("确定要删除吗?")){
window.location.href="${pageContext.request.contextPath}/remove.do?id=" id;
}
}
</script>
</head>
<body>
用户列表:<button type="button" οnclick="add()">添加用户</button>
<table cellpadding="0" cellspacing="0" width="80%">
<tr>
<th>用户Id</th>
<th>用户名称</th>
<th>邮箱</th>
<th>联系电话</th>
<th>操作</th>
</tr>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.username}</td>
<td>${user.email}</td>
<td>${user.phoneNum}</td>
<td>
<button type="button" οnclick="get('${user.id}')">修改</button>
<button type="button" οnclick="removeUser('${user.id}')">删除</button>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
8.7 编辑用户表
代码语言:javascript复制<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改用户信息</title>
<style>
table {border:1px solid #000000}
table th{border:1px solid #000000}
table td{border:1px solid #000000}
</style>
</head>
<body>
<form id="userForm"
action="${pageContext.request.contextPath }/edit.do" method="post">
修改用户信息:
<table cellpadding="0" cellspacing="0" width="80%">
<input type="hidden" name="id" value="${user.id}"/>
<tr>
<td>用户名称</td>
<td><input type="text" name="username" value="${user.username}" /></td>
</tr>
<tr>
<td>邮箱</td>
<td><input type="text" name="email" value="${user.email}" /></td>
</tr>
<tr>
<td>联系电话</td>
<td><input type="text" name="phoneNum" value="${user.phoneNum}" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="修改" />
</td>
</tr>
</table>
</form>
</body>
</html>
8.8 新增用户表
代码语言:javascript复制<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>添加用户信息</title>
<style>
table {border:1px solid #000000}
table th{border:1px solid #000000}
table td{border:1px solid #000000}
</style>
</head>
<body>
<form id="userForm"
action="${pageContext.request.contextPath }/insert.do" method="post">
添加用户信息:
<table cellpadding="0" cellspacing="0" width="80%">
<tr>
<td>用户名称</td>
<td><input type="text" name="username" value="" /></td>
</tr>
<tr>
<td>用户密码</td>
<td><input type="password" name="password" value="" /></td>
</tr>
<tr>
<td>邮箱</td>
<td><input type="text" name="email" value="" /></td>
</tr>
<tr>
<td>联系电话</td>
<td><input type="text" name="phoneNum" value="" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="添加" />
</td>
</tr>
</table>
</form>
</body>
</html>
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/143459.html原文链接:https://javaforall.cn