准备工作
环境准备
IDEA
MySQL 5.7.31
Tomcat 8.5.64
Maven 3.6.3
这是我的环境,版本别差太大就没问题。
数据库准备
CREATE DATABASE `ssmtest`; USE `ssmtest`; DROP TABLE IF EXISTS `user`; CREATE TABLE `user`( `userid` INT(10) NOT NULL AUTO_INCREMENT COMMENT '用户ID', `username` VARCHAR(100) NOT NULL COMMENT '用户名', `password` VARCHAR(100) NOT NULL COMMENT '用户密码', `value` INT(10) NOT NULL DEFAULT 1 COMMENT '状态,1正常', KEY `userid`(`userid`) ) ENGINE=INNODB DEFAULT CHARSET=utf8; INSERT INTO `user`(`userid`,`username`,`password`,`value`)VALUES (1,'keafmd','666',1), (2,'keafod','888',1);
开始干活
新建个Maven项目ssmtest,加上Web支持
创建完成的效果:
添加依赖
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <!--统一的版本管理--> <spring.version>5.2.7.RELEASE</spring.version> <slf4j.version>1.7.6</slf4j.version> <log4j.version>1.2.12</log4j.version> <mysql.version>5.1.49</mysql.version> <mybatis.version>3.4.5</mybatis.version> </properties> <dependencies> <!-- spring --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.5</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <!--Junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>compile</scope> </dependency> <!--数据库驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- 数据库连接池 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.1</version> <type>jar</type> <scope>compile</scope> </dependency> <!--Servlet - JSP --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--Mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.2</version> </dependency> <!-- log --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> </dependencies>
完整的pom.xml
<?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.keafmd</groupId> <artifactId>ssmtest</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>ssmtest Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <!--统一的版本管理--> <spring.version>5.2.7.RELEASE</spring.version> <slf4j.version>1.7.6</slf4j.version> <log4j.version>1.2.12</log4j.version> <mysql.version>5.1.49</mysql.version> <mybatis.version>3.4.5</mybatis.version> </properties> <dependencies> <!-- spring --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.5</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <!--Junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>compile</scope> </dependency> <!--数据库驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- 数据库连接池 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.1</version> <type>jar</type> <scope>compile</scope> </dependency> <!--Servlet - JSP --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--Mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.2</version> </dependency> <!-- log --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> </dependencies> <build> <finalName>ssmtest</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>
创建entity、dao、service、controller包
实体类编写
添加lombook
User:
package com.keafmd.entity; import lombok.Data; import java.io.Serializable; /** * Keafmd * * @ClassName: User * @Description: 用户实体类 * @author: 牛哄哄的柯南 * @Date: 2021-04-19 9:11 * @Blog: https://keafmd.blog.csdn.net/ */ @Data public class User implements Serializable { private Integer userId; private String userName; private String password; }
持久层接口编写
IUserDao :
package com.keafmd.dao; import com.keafmd.entity.User; import java.util.List; /** * Keafmd * * @ClassName: IUserDao * @Description: 用户dao接口 * @author: 牛哄哄的柯南 * @Date: 2021-04-19 9:20 * @Blog: https://keafmd.blog.csdn.net/ */ public interface IUserDao { //查询所有 public List<User> findAll(); //保存用户 public void saveUser(User user); }
业务层接口编写
IUserService:
package com.keafmd.service; import com.keafmd.entity.User; import java.util.List; /** * Keafmd * * @ClassName: IUserService * @Description: user业务层接口 * @author: 牛哄哄的柯南 * @Date: 2021-04-19 9:23 * @Blog: https://keafmd.blog.csdn.net/ */ public interface IUserService { //查询所有 public List<User> findAll(); //保存用户 public void saveUser(User user); }
业务层实现类编写
UserServiceImpl :
package com.keafmd.service.impl; import com.keafmd.entity.User; import com.keafmd.service.IUserService; import java.util.List; /** * Keafmd * * @ClassName: UserService * @Description: user业务层实现类 * @author: 牛哄哄的柯南 * @Date: 2021-04-19 9:25 * @Blog: https://keafmd.blog.csdn.net/ */ public class UserServiceImpl implements IUserService { @Override public List<User> findAll() { System.out.println("user业务层实现类--findAll"); return null; } @Override public void saveUser(User user) { System.out.println("user业务层实现类--saveUser"); } }
表现层编写
UserController :
package com.keafmd.controller; /** * Keafmd * * @ClassName: UserController * @Description: user控制层 * @author: 牛哄哄的柯南 * @Date: 2021-04-19 9:28 * @Blog: https://keafmd.blog.csdn.net/ */ public class UserController { }
整合步骤
保证 Spring 框架在 web 工程中独立运行
第一步:编写 spring 配置文件并导入约束
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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 开启注解扫描,要扫描的是service和dao层的注解,要忽略web层注解,因为web层让SpringMVC框架去管理 --> <context:component-scan base-package="com.keafmd"> <!-- 配置要忽略的注解 --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> </beans>
第二步:使用注解配置业务层
在 UserServiceImpl 方法上加上 @Service("userService").
package com.keafmd.service.impl; import com.keafmd.entity.User; import com.keafmd.service.IUserService; import org.springframework.stereotype.Service; import java.util.List; /** * Keafmd * * @ClassName: UserService * @Description: user业务层实现类 * @author: 牛哄哄的柯南 * @Date: 2021-04-19 9:25 * @Blog: https://keafmd.blog.csdn.net/ */ @Service("userService") public class UserServiceImpl implements IUserService { @Override public List<User> findAll() { System.out.println("user业务层实现类--findAll"); return null; } @Override public void saveUser(User user) { System.out.println("user业务层实现类--saveUser"); } }
第三步:导入log4j.properties配置文件
# Set root category priority to INFO and its only appender to CONSOLE. #log4j.rootCategory=INFO, CONSOLE debug info warn error fatal log4j.rootCategory=info, CONSOLE, LOGFILE # Set the enterprise logger category to FATAL and its only appender to CONSOLE. log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE # CONSOLE is set to be a ConsoleAppender using a PatternLayout. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n # LOGFILE is set to be a File appender using a PatternLayout. log4j.appender.LOGFILE=org.apache.log4j.FileAppender log4j.appender.LOGFILE.File=d:\axis.log log4j.appender.LOGFILE.Append=true log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
第四步:测试 spring 能否独立运行
测试代码:
package com.keafmd; import com.keafmd.service.IUserService; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Keafmd * * @ClassName: TestSpring * @Description: 测试 spring 能否独立运行 * @author: 牛哄哄的柯南 * @Date: 2021-04-19 9:38 * @Blog: https://keafmd.blog.csdn.net/ */ public class TestSpring { @Test public void test1(){ //加载配置文件 ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); //获取对象 IUserService userService = (IUserService)ac.getBean("userService"); //调用方法 userService.findAll(); } }
测试效果:
保证 SpringMVC 在 web 工程中独立运行
第一步:编写 SpringMVC 的配置文件
springmvc.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 开启注解扫描,扫描controller的注解,别的不扫描 --> <context:component-scan base-package="com.keafmd"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 配置视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- JSP文件所在的目录 --> <property name="prefix" value="/WEB-INF/pages/"/> <!-- 文件的后缀名 --> <property name="suffix" value=".jsp"/> </bean> <!-- 过滤静态资源,设置静态资源不过滤 --> <mvc:resources location="/css/" mapping="/css/**"/> <mvc:resources location="/images/" mapping="/images/**"/> <mvc:resources location="/js/" mapping="/js/**"/> <!-- 开启对SpringMVC注解的支持 --> <mvc:annotation-driven/> </beans>
第二步:在 web.xml 中配置核心控制器(DispatcherServlet)
web.xml:
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <!-- 配置前端控制器:服务器启动必须加载,需要加载springmvc.xml配置文件 --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置初始化参数,加载springmvc.xml配置文件 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- 启动服务器,创建该servlet --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</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> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
第三步:编写 Controller 和 jsp 页面
UserController :
package com.keafmd.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * Keafmd * * @ClassName: UserController * @Description: user控制层 * @author: 牛哄哄的柯南 * @Date: 2021-04-19 9:28 * @Blog: https://keafmd.blog.csdn.net/ */ @Controller @RequestMapping("/user") public class UserController { @RequestMapping("/findAll") public String findAll(){ System.out.println("表现层--查询所有用户"); return "user_list"; } }
index.jsp:
<%-- Created by IntelliJ IDEA. User: lenovo Date: 2021/4/19 Time: 9:52 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <a href="user/findAll">查询所有用户</a> </body> </html>
user_list.jsp:
<%-- Created by IntelliJ IDEA. User: lenovo Date: 2021/4/19 Time: 9:55 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>查询所有用户</h1> </body> </html>
第四步:部署tomcat服务器
-Dfile.encoding=utf-8
第五步:启动服务器,进行测试
点击后的效果:
Spring 整合 SpringMVC 的框架
第一步:配置监听器实现启动服务创建容器
<!-- 配置 spring 提供的监听器,用于启动服务时加载容器 。 该监听器只能加载 WEB-INF 目录中名称为 applicationContext.xml 的配置文件 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 手动指定 spring 配置文件位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
完整的web.xml:
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <!-- 配置前端控制器:服务器启动必须加载,需要加载springmvc.xml配置文件 --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置初始化参数,加载springmvc.xml配置文件 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- 启动服务器,创建该servlet --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 配置 spring 提供的监听器,用于启动服务时加载容器 。 该监听器只能加载 WEB-INF 目录中名称为 applicationContext.xml 的配置文件 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 手动指定 spring 配置文件位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!--解决中文乱码的过滤器--> <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> </web-app>
第二步:在controller中注入service对象,调用service对象的方法进行测试
UserController :
package com.keafmd.controller; import com.keafmd.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * Keafmd * * @ClassName: UserController * @Description: user控制层 * @author: 牛哄哄的柯南 * @Date: 2021-04-19 9:28 * @Blog: https://keafmd.blog.csdn.net/ */ @Controller @RequestMapping("/user") public class UserController { @Autowired private IUserService userService; @RequestMapping("/findAll") public String findAll(){ System.out.println("表现层--查询所有用户"); //调用service的方法 userService.findAll(); return "user_list"; } }
重启Tomcat点击查询所有用户,控制台输出效果如下:
保证 MyBatis 框架在 web 工程中独立运行
第一步:在web项目中编写SqlMapConfig.xml的配置文件,编写核心配置文件
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> <!-- 配置连接数据库的信息 --> <properties resource="jdbcConfig.properties"></properties> <!-- 配置mybatis的环境 --> <environments default="mysql"> <environment id="mysql"> <!-- 配置事务管理 --> <transactionManager type="JDBC"></transactionManager> <dataSource type="pooled"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <!-- 指定映射文件位置 --> <mappers> <!--<mapper class="com.keafmd.dao.IAccountDao"/> <mapper class="com.keafmd.dao.IUserDao"/>--> <package name="com.keafmd.dao"/> </mappers> </configuration>
jdbcConfig.properties:
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssmtest jdbc.username=root jdbc.password=18044229
第二步:在IUserDao接口的方法上添加注解,编写SQL语句
IUserDao :
package com.keafmd.dao; import com.keafmd.entity.User; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import java.util.List; /** * Keafmd * * @ClassName: IUserDao * @Description: 用户dao接口 * @author: 牛哄哄的柯南 * @Date: 2021-04-19 9:20 * @Blog: https://keafmd.blog.csdn.net/ */ public interface IUserDao { //查询所有 @Select("select * from user") public List<User> findAll(); //保存用户 @Insert("insert into user(username,password) values(#{userName},#{password})") public void saveUser(User user); }
第三步:编写测试的方法
TestMybatis :
package com.keafmd; import com.keafmd.dao.IUserDao; import com.keafmd.entity.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.After; import org.junit.Before; import org.junit.Test; import java.io.InputStream; import java.util.List; /** * Keafmd * * @ClassName: TestMybatis * @Description: * @author: 牛哄哄的柯南 * @Date: 2021-04-19 10:20 * @Blog: https://keafmd.blog.csdn.net/ */ public class TestMybatis { private InputStream in; private SqlSessionFactory factory; private SqlSession session; private IUserDao userDao; @Before public void init() throws Exception{ //加载配置文件 in = Resources.getResourceAsStream("SqlMapConfig.xml"); //创建SqlSessionFactory对象 factory = new SqlSessionFactoryBuilder().build(in); //创建SqlSession对象 session = factory.openSession(); //获取到代理对象 userDao = session.getMapper(IUserDao.class); } @After public void destory() throws Exception{ session.commit(); session.close(); in.close(); } /** * 查询所有 */ @Test public void run1(){ List<User> users = userDao.findAll(); for (User user : users) { System.out.println(user); } } /** * 测试保存 */ @Test public void saveUser(){ User user = new User(); user.setUserName("毛利小五郎"); user.setPassword("999"); userDao.saveUser(user); } }
测试效果:
Spring 整合 MyBatis 框架
把 mybatis 配置文件(SqlMapConfig.xml)中内容配置到 spring 配置文件中同时,把 mybatis 配置文件的内容清掉。
第一步:把SqlMapConfig.xml配置文件中的内容配置到applicationContext.xml配置文件中
把以下内容添加到applicationContext.xml配置文件中:
<!--Spring整合Mybatisl框架--> <!-- 配置C3P0的连接池对象 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql:///ssmtest"/> <property name="user" value="root"/> <property name="password" value="18044229"/> </bean> <!-- 配置SqlSession的工厂 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 配置扫描dao的包 --> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.keafmd.dao"/> </bean> <!--SqlMapConfig.xml和jdbcConfig.properties可以删除了-->
再添加上配置Spring框架声明式事务管理:
<!--配置Spring框架声明式事务管理--> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置事务的通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> <tx:method name="*" isolation="DEFAULT"/> </tx:attributes> </tx:advice> <!-- 配置AOP增强 --> <aop:config> <!--<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.keafmd.service.impl.*.*(..))"/>--> <!-- 配置切入点表达式 --> <aop:pointcut expression="execution(* com.keafmd.service.impl.*.*(..))" id="pt1"/> <!-- 建立通知和切入点表达式的关系 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/> </aop:config>
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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 开启注解扫描,要扫描的是service和dao层的注解,要忽略web层注解,因为web层让SpringMVC框架去管理 --> <context:component-scan base-package="com.keafmd"> <!-- 配置要忽略的注解 --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--Spring整合Mybatisl框架--> <!-- 配置C3P0的连接池对象 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql:///ssmtest?characterEncoding=utf8"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean> <!-- 配置SqlSession的工厂 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 配置扫描dao的包 --> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.keafmd.dao"/> </bean> <!--SqlMapConfig.xml和jdbcConfig.properties可以删除了--> <!--配置Spring框架声明式事务管理--> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置事务的通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> <tx:method name="*" isolation="DEFAULT"/> </tx:attributes> </tx:advice> <!-- 配置AOP增强 --> <aop:config> <!--<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.keafmd.service.impl.*.*(..))"/>--> <!-- 配置切入点表达式 --> <aop:pointcut expression="execution(* com.keafmd.service.impl.*.*(..))" id="pt1"/> <!-- 建立通知和切入点表达式的关系 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/> </aop:config> </beans>
第三步:在IUserDao接口中添加@Repository注解
package com.keafmd.dao; import com.keafmd.entity.User; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository; import java.util.List; /** * Keafmd * * @ClassName: IUserDao * @Description: 用户dao接口 * @author: 牛哄哄的柯南 * @Date: 2021-04-19 9:20 * @Blog: https://keafmd.blog.csdn.net/ */ @Repository public interface IUserDao { //查询所有 @Select("select * from user") public List<User> findAll(); //保存用户 @Insert("insert into user(username,password) values(#{userName},#{password})") public void saveUser(User user); }
第四步:在UserServiceImpl中注入dao对象
package com.keafmd.service.impl; import com.keafmd.dao.IUserDao; import com.keafmd.entity.User; import com.keafmd.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Keafmd * * @ClassName: UserService * @Description: user业务层实现类 * @author: 牛哄哄的柯南 * @Date: 2021-04-19 9:25 * @Blog: https://keafmd.blog.csdn.net/ */ @Service("userService") public class UserServiceImpl implements IUserService { @Autowired IUserDao userDao; @Override public List<User> findAll() { System.out.println("user业务层实现类--findAll"); return userDao.findAll(); } @Override public void saveUser(User user) { System.out.println("user业务层实现类--saveUser"); userDao.saveUser(user); } }
第五步:修改 UserController 代码
package com.keafmd.controller; import com.keafmd.entity.User; import com.keafmd.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * Keafmd * * @ClassName: UserController * @Description: user控制层 * @author: 牛哄哄的柯南 * @Date: 2021-04-19 9:28 * @Blog: https://keafmd.blog.csdn.net/ */ @Controller @RequestMapping("/user") public class UserController { @Autowired private IUserService userService; @RequestMapping("/findAll") public String findAll(Model model){ System.out.println("表现层--查询所有用户"); //调用service的方法 List<User> userList = userService.findAll(); model.addAttribute("userList",userList); return "user_list"; } @RequestMapping("/save") public void save(User user , HttpServletRequest request, HttpServletResponse response) throws IOException { userService.saveUser(user); response.sendRedirect(request.getContextPath()+"/user/findAll"); return; } }
第五步:修改 user_list.jsp 代码,实现显示账户信息
<%-- Created by IntelliJ IDEA. User: lenovo Date: 2021/4/19 Time: 9:55 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> </head> <body> <h1>查询所有用户</h1> <%-- ${userList}--%> <c:forEach items="${userList}" var="user"> ${user.userName} ${user.password} </c:forEach> </body> </html>
第六步:测试查询
效果:
第七步:测试保存
修改index.jsp代码,添加测试保存的代码:
<%-- Created by IntelliJ IDEA. User: lenovo Date: 2021/4/19 Time: 9:52 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <a href="user/findAll">查询所有用户</a> <h1>测试保存</h1> <form action="user/save" method="post"> 账户名:<input type="text" name="userName" /><br/> 密码:<input type="text" name="password" /><br/> <input type="submit" value="保存"> </form> </body> </html>
修改 UserController 代码,添加save方法:
package com.keafmd.controller; import com.keafmd.entity.User; import com.keafmd.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * Keafmd * * @ClassName: UserController * @Description: user控制层 * @author: 牛哄哄的柯南 * @Date: 2021-04-19 9:28 * @Blog: https://keafmd.blog.csdn.net/ */ @Controller @RequestMapping("/user") public class UserController { @Autowired private IUserService userService; @RequestMapping("/findAll") public String findAll(Model model){ System.out.println("表现层--查询所有用户"); //调用service的方法 List<User> userList = userService.findAll(); model.addAttribute("userList",userList); return "user_list"; } @RequestMapping("/save") public void save(User user , HttpServletRequest request, HttpServletResponse response) throws IOException { userService.saveUser(user); response.sendRedirect(request.getContextPath()+"/user/findAll"); return; } }
测试效果:
增删改查(前后端分离)
查找
实际开发中,多为前后端分离,所以我们需要修改我们的表现层代码,同时需要添加上jackson的依赖。
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.11.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.11.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.11.0</version> </dependency>
UserController:
package com.keafmd.controller; import com.keafmd.common.CommonResult; import com.keafmd.entity.User; import com.keafmd.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * Keafmd * * @ClassName: UserController * @Description: user控制层 * @author: 牛哄哄的柯南 * @Date: 2021-04-19 9:28 * @Blog: https://keafmd.blog.csdn.net/ */ @Controller @RequestMapping("/user") public class UserController { @Autowired private IUserService userService; // http://127.0.0.1:8080/ssmtest/user/findAll @RequestMapping("/findAll") @ResponseBody public List<User> findAll(){ System.out.println("表现层--查询所有用户"); //调用service的方法 List<User> userList = userService.findAll(); // model.addAttribute("userList",userList); // return "user_list"; return userList; } @RequestMapping("/save") public void save(User user , HttpServletRequest request, HttpServletResponse response) throws IOException { userService.saveUser(user); response.sendRedirect(request.getContextPath()+"/user/findAll"); return; } }
访问: http://127.0.0.1:8080/ssmtest/user/findAll
前端vue项目
这里我们需要有相关的环境,这里不细说了。
创建个空的vue项目
找个文件夹进入命令行,输入:vue create ssmtest
关闭代码格式化校验工具
在项目的根目录(与package.json同级)中,添加名称为vue.config.js的文件,就能自动被vue-cli加载。
module.exports = { lintOnSave:false, //关闭代码格式化校验工具 devServer:{ port: 80 //修改启动端口 } }
安装相关的工具
1、安装vue-router
npm install vue-router
2、安装 element-ui插件
npm i element-ui -S
3、安装axios
npm install axios
目录结构
编写main.js
在这里引入各种组件,写上router。
import Vue from 'vue' import App from './App.vue' import router from '@/router' import ElementUI from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css'; Vue.use(ElementUI); Vue.config.productionTip = false new Vue({ render: h => h(App), router }).$mount('#app')
编写App.vue
在div中写入<router-view></router-view>,用路由控制界面。
<template> <div id="app"> <router-view></router-view> </div> </template> <script> // import First from './components/First.vue' export default { name: 'App', components: { // First } } </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
编写router文件夹下的index.js
在这里使用router配置各种路径
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) // import A from '@/components/A' // import B from '@/components/B' export default new Router({ mode: 'history', routes: [{ path: '/', name: 'Index', component: () => import('@/views'), children: [{ path: '/user', name: 'User', component: () => import('@/views/user') } ] } // , // { // path: '/user', // name: 'User', // component: () => import('@/views/user') // } // { // path: '/aaa', // name: 'A', // component: A // }, // { // path: '/bbb', // name: 'B', // component: B // } ] })
编写公共部分的menu.vue
注意:在 el-menu 标签里注入router。
<template> <el-menu router > <el-submenu index="1"> <template slot="title"> <span>管理</span> </template> <el-menu-item-group> <el-menu-item index="/user"> <i class="el-icon-location"></i>用户管理</el-menu-item> <!-- <el-menu-item index="/menu"> <i class="el-icon-location"></i>菜单管理</el-menu-item> --> </el-menu-item-group> </el-submenu> <!-- <el-submenu index="2"> <template slot="title"> <span>ElementUI组件</span> </template> <el-menu-item-group> <el-menu-item index="/table"> <i class="el-icon-location"></i>表格组件</el-menu-item> </el-menu-item-group> </el-submenu> --> </el-menu> </template> <script> export default { name: 'Menu' } </script> <style> </style>
编写views下的index.vue
<template> <el-container class="wrap"> <el-header class="header"> <el-row> <el-col :span="20">信息系统</el-col> <el-col :span="4"> <el-dropdown> <span class="el-dropdown-link"> keafmd<i class="el-icon-arrow-down el-icon--right"></i> </span> <el-dropdown-menu slot="dropdown"> <el-dropdown-item command="Personal">个人设置</el-dropdown-item> <el-dropdown-item command="Logout">退出</el-dropdown-item> </el-dropdown-menu> </el-dropdown> </el-col> </el-row> </el-header> <el-container> <el-aside width="200px" class="aside"> <Menu></Menu> </el-aside> <el-main> <!-- <User></User> --> <router-view></router-view> </el-main> </el-container> </el-container> </template> <script> // import User from './user/index.vue' import Menu from '@/components/menu' export default { name: 'Index', components: { Menu // User }, data() { return {} }, methods: { }, created() {} } </script> <style scoped> .wrap { height: 100vh; } .header { border-bottom: 1px solid aqua; } .aside { border-right: 1px solid aqua; } </style>
编写views下的user下的index.vue
<template> <div> <el-table :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))" style="width: 100%"> <el-table-column label="userName" prop="userName"> </el-table-column> <el-table-column label="Password" prop="password"> </el-table-column> <el-table-column align="right"> <template slot="header" slot-scope="scope"> <el-input v-model="search" size="mini" placeholder="输入关键字搜索" /> </template> <template slot-scope="scope"> <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">Edit</el-button> <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">Delete </el-button> </template> </el-table-column> </el-table> </div> </template> <script> import axios from 'axios'; axios.defaults.baseURL = 'http://127.0.0.1:8080/ssmtest'; export default { name: 'User', components: { }, data() { return { tableData: [], search: '' } }, methods: { getData() { axios.get('/user/findAll') .then((res) => { this.tableData = res.data }) .catch(function(error) { console.log(error); }); }, handleEdit(index, row) { console.log(index, row); }, handleDelete(index, row) { console.log(index, row); } }, created() { this.getData(); } } </script> <style> </style>
效果展示
查询效果: