1.新建maven-webapp工程,添加java、resources目录及test目录下的java、resources
2.引入依赖
<!--spring核心及相关依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.2.RELEASE</version> </dependency> <!--springmvc核心依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.2.RELEASE</version> </dependency> <!--servlet-api--> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <!--jstl--> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.3</version> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <!--druid--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.17</version> </dependency> <!--log4j--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.10.0</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.25</version> </dependency> <!--fastjson--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency>
3.Spring+Mybatis整合
3.1 新建表
3.2 新建实体类
package com.study.entity; import java.util.Date; /** * @ClassName User * @Description TODO * @Author Jiangnan Cui * @Date 2022/4/23 10:46 * @Version 1.0 */ public class User { private String id; private String name; private Integer age; private Date bir; @Override public String toString() { return "User{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", age=" + age + ", bir=" + bir + '}'; } public User() { } public User(String id, String name, Integer age, Date bir) { this.id = id; this.name = name; this.age = age; this.bir = bir; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Date getBir() { return bir; } public void setBir(Date bir) { this.bir = bir; } }
3.3 新建DAO接口
package com.study.dao; import com.study.entity.User; import java.util.List; /** * @ClassName UserDAO * @Description TODO * @Author Jiangnan Cui * @Date 2022/4/23 10:45 * @Version 1.0 */ public interface UserDAO { /** * @MethodName selectAllUsers * @Description 查询所有用户 * @return: java.util.List<com.study.entity.User> * @Author Jiangnan Cui * @Date 2022/4/23 10:50 */ List<User> selectAllUsers(); /** * @MethodName insertUser * @Description 添加用户 * @param: user * @Author Jiangnan Cui * @Date 2022/4/23 10:49 */ void insertUser(User user); }
3.4 新建Mapper配置文件
<?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.study.dao.UserDAO"> <!--selectAllUsers--> <select id="selectAllUsers" resultType="User"> select id,name,age,bir from t_user </select> <!--insertUser--> <insert id="insertUser" parameterType="User"> insert into t_user values(#{id},#{name},#{age},#{bir}) </insert> </mapper>
3.5 新建Service接口
package com.study.service; import com.study.entity.User; import java.util.List; /** * @ClassName UserService * @Description TODO * @Author Jiangnan Cui * @Date 2022/4/23 10:55 * @Version 1.0 */ public interface UserService { /** * @MethodName selectAllUsers * @Description 查询所有用户 * @return: java.util.List<com.study.entity.User> * @Author Jiangnan Cui * @Date 2022/4/23 10:50 */ List<User> selectAllUsers(); /** * @MethodName insertUser * @Description 添加用户 * @param: user * @Author Jiangnan Cui * @Date 2022/4/23 10:49 */ void insertUser(User user); }
3.6 新建ServiceImpl实现类
package com.study.service; import com.study.dao.UserDAO; import com.study.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.UUID; /** * @ClassName UserServiceImpl * @Description TODO * @Author Jiangnan Cui * @Date 2022/4/23 10:55 * @Version 1.0 */ @Service("userService") @Transactional public class UserServiceImpl implements UserService{ @Autowired private UserDAO userDAO; @Override @Transactional(propagation = Propagation.SUPPORTS) public List<User> selectAllUsers() { return userDAO.selectAllUsers(); } @Override public void insertUser(User user) { user.setId(UUID.randomUUID().toString()); userDAO.insertUser(user); } }
3.7 引入spring.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: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/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--开启注解扫描--> <context:component-scan base-package="com.study"/> <!--创建数据源对象--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=UTF-8&useSSL=false"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean> <!--创建SqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="mapperLocations" value="classpath:com/study/mapper/*.xml"/> <property name="typeAliasesPackage" value="com.study.entity"/> </bean> <!--创建DAO--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <property name="basePackage" value="com.study.dao"/> </bean> <!--创建事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--开启注解式事务生效--> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
3.8 引入log4j.properties
log4j.rootLogger=ERROR,stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.conversionPattern=[%p] %d{yyyy-MM-dd} %m%n • log4j.logger.com.study.dao=DEBUG log4j.logger.org.springframework=ERROR
3.9 测试Service方法是否可以成功调用
package com.study.test; import com.study.entity.User; import com.study.service.UserService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.List; /** * @ClassName TestUserService * @Description TODO * @Author Jiangnan Cui * @Date 2022/4/23 11:11 * @Version 1.0 */ public class TestUserService { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); UserService userService = (UserService) context.getBean("userService"); List<User> users = userService.selectAllUsers(); for (User user : users) { System.out.println("user = " + user); } } }
测试结果:
[DEBUG] 2022-04-23 ==> Preparing: select id,name,age,bir from t_user [DEBUG] 2022-04-23 ==> Parameters: [DEBUG] 2022-04-23 <== Total: 18 user = User{id='1', name='张三', age=10, bir=Fri Apr 01 00:00:00 CST 2022} user = User{id='2', name='李四', age=20, bir=Sat Apr 02 00:00:00 CST 2022} user = User{id='2d237778-835d-477b-9721-fe6f575064b9', name='波比', age=18, bir=Sun Feb 02 00:00:00 CST 2020} user = User{id='2f278828-6422-432d-ab1b-a727b33c23bc', name='小胖墩', age=3, bir=Mon Apr 11 21:43:57 CST 2022} user = User{id='3', name='王五', age=30, bir=Sun Apr 03 00:00:00 CST 2022} user = User{id='4', name='灰太狼', age=60, bir=Sun Apr 10 09:56:17 CST 2022} user = User{id='5', name='小超超', age=36, bir=Sun Apr 10 09:55:41 CST 2022} user = User{id='586a5f71-836c-4171-a038-4620fe0f9354', name='葫芦娃', age=5, bir=Tue Apr 12 09:45:17 CST 2022} user = User{id='6', name='小呆呆', age=60, bir=Sun Apr 10 09:55:43 CST 2022} user = User{id='7', name='小超超', age=36, bir=Sun Apr 10 09:55:44 CST 2022} user = User{id='7a1a00aa-1507-461a-95c0-50110d6f4333', name='唐三', age=20, bir=Fri Apr 15 00:00:00 CST 2022} user = User{id='8', name='胖嘟嘟', age=50, bir=Sun Apr 10 09:55:39 CST 2022} user = User{id='8a3e8ab8-5abc-44e1-9aec-31f3978d97f2', name='小胖墩', age=3, bir=Tue Apr 12 10:23:33 CST 2022} user = User{id='9', name='小崔', age=25, bir=Sun Apr 10 09:55:52 CST 2022} user = User{id='985cd035-dedc-4e84-973a-a5fdaa2b8475', name='喜洋洋', age=8, bir=Tue Oct 10 00:00:00 CST 2000} user = User{id='a6be9263-f05f-415f-855e-33843b22e71d', name='皮卡丘', age=10, bir=Thu Apr 14 00:00:00 CST 2022} user = User{id='cd280176-68b2-4ceb-b781-ba2f5e1fbeff', name='小胖墩', age=3, bir=Tue Apr 12 10:21:18 CST 2022} user = User{id='e3863fd3-173c-46f4-a753-c72f7c92ad56', name='小猫咪', age=3, bir=Mon Apr 11 21:36:31 CST 2022}
4.Spring+SpringMVC整合
4.1 配置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> <!--配置工厂监听器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--配置工厂配置文件--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </context-param> <!--配置springmvc核心servlet--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--配置post请求参数的中文乱码问题--> <filter> <filter-name>charset</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>charset</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
4.2 引入springmvc.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: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"> <!--开启注解扫描--> <context:component-scan base-package="com.study.controller"/> <!--配置处理映射器和处理适配器--> <mvc:annotation-driven/> <!--配置视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"/> <property name="suffix" value=".jsp"/> </bean> <!--解决静态资源拦截的配置--> <mvc:default-servlet-handler/> </beans>
4.3 新建Controller
package com.study.controller; import com.study.entity.User; import com.study.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import java.util.List; /** * @ClassName UserController * @Description TODO * @Author Jiangnan Cui * @Date 2022/4/23 12:12 * @Version 1.0 */ @Controller @RequestMapping("user") public class UserController { @Autowired private UserService userService; @RequestMapping("selectAllUsers") public String selectAllUsers(HttpServletRequest request){ //1.收集数据 //2.调用业务对象 List<User> users = userService.selectAllUsers(); request.setAttribute("users",users); return "selectAllUsers"; } @RequestMapping("insertUser") public String insertUser(User user){ //1.收集参数 //2.调用业务方法 try { userService.insertUser(user); return "redirect:/user/selectAllUsers"; } catch (Exception e) { e.printStackTrace(); return "redirect:/insertUser.jsp"; } } }
4.4 添加jsp文件
selectAllUsers.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>用来展示所有用户信息</title> <script src="${pageContext.request.contextPath}/js/jquery-3.5.1.min.js"></script> <script> $(function(){ alert(); }) </script> </head> <body> <h1>展示用户列表</h1> <c:forEach items="${requestScope.users}" var="user"> ${user.id} ==== ${user.name} ==== ${user.age} ==== ${user.bir} <br> </c:forEach> <a href="${pageContext.request.contextPath}/insertUser.jsp">添加用户信息</a> </body> </html>
insertUser.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>添加用户信息</title> </head> <body> <h1>添加用户信息</h1> <form action="${pageContext.request.contextPath}/user/insertUser" method="post"> 姓名:<input type="text" name="name"/> <br> 年龄:<input type="text" name="age"/> <br> 生日:<input type="text" name="bir"/> <br> <input type="submit" value="保存用户信息"> </form> </body> </html>
5. 部署tomcat服务器测试
测试结果:
6.总结
附项目目录结构: