JavaEE——Spring学习笔记01【Ioc开发的模式】
JavaEE——Spring学习笔记02【Spring和Mybatis的整合】
JavaEE——Spring学习笔记04【Spring的事务管理】
目录
1. 使用maven创建一个web工程项目:04-spring-web
5.3 使用mybatis的逆向工程生成pojo和mapper
八、Maven创建Web工程使用Spring
1. 使用maven创建一个web工程项目:04-spring-web
2. 修改web.xml文件的版本为4.0
3. 构建项目的包结构
4.搭建tomcat服务器,启动服务器
5.实现在前端页面中添加学生的信息
5.1 修改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.suke</groupId>
<artifactId>04-spring-web</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>04-spring-web 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>
</properties>
<dependencies>
<!--添加Junit的单元测试包-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!--添加Mysql驱动程序包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<!--添加数据库连接池的druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.6</version>
</dependency>
<!--spring的jdbc模板包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!--添加mybatis的依赖包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<!--添加Spring的核心包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<!--添加Spring的test依赖包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<!--添加mybatis和spring的整合包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- @Resource注解依赖的jar包-->
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
<!--添加log4j日志的jar包-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.6</version>
<scope>test</scope>
</dependency>
<!--添加一个AspectJ的依赖包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<!--添加Cglib的包-->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.1_3</version>
</dependency>
<!--配置spring的事务管理-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<!--添加Servlet的包-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--添加JSP的包-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<!--添加spring-web依赖的包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
</dependencies>
<!--找映射文件:spring与mybatis整合肯定要使用到mybatis的映射文件-->
<build>
<resources>
<resource>
<directory>src/main/java</directory><!--映射文件所有在目录-->
<!--包含目录下的.properties文件,.xml文件都会进行扫描-->
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
5.2 创建数据库表——student表
5.3 使用mybatis的逆向工程生成pojo和mapper
src/main/java/com.suke/pojo/Student
package com.suke.pojo;
public class Student {
private Integer id;
private String name;
private String email;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email == null ? null : email.trim();
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", age=" + age +
'}';
}
}
src/main/java/com.suke/mapper/StudentMapper
package com.suke.mapper;
import com.suke.pojo.Student;
import java.util.List;
/*
* dao层: 学生的功能接口
* */
public interface StudentMapper {
//1、添加学生信息的功能
public int insertStudent(Student student);
//2、查询学生信息列表
public List<Student> selectStudents();
}
src/main/java/com.suke/mapper/StudentMapper.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.suke.mapper.StudentMapper">
<!--注册学生信息的sql语句-->
<insert id="insertStudent" parameterType="student">
insert into student(name, email, age)
values (#{name}, #{email}, #{age});
</insert>
<!--查询学生列表信息SQL语句-->
<select id="selectStudents" resultType="student">
select *
from student;
</select>
</mapper>
5.4 创建添加学生列表的jsp页面index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>注册学生信息</title>
</head>
<body>
<h2>注册学生信息</h2>
<%--form表单--%>
<form action="reg" method="post">
<table>
<tr>
<td>姓名:</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>邮箱:</td>
<td><input type="text" name="email"/></td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="text" name="age"/></td>
</tr>
<%--注册的按钮--%>
<tr>
<td></td>
<td><input type="submit" value="注册学生"/></td>
</tr>
</table>
</form>
</body>
</html>
5.5 添加学生信息成功给出提示的页面result.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>提示页面</title>
</head>
<body>
<h2>注册学生信息结果显示</h2>
<h3>注册学生信息成功!</h3>
</body>
</html>
5.6 mybatis动态代理的接口StudentMapper
/*
* dao层: 学生的功能接口
* */
public interface StudentMapper {
//1、添加学生信息的功能
public int insertStudent(Student student);
//2、查询学生信息列表
public List<Student> selectStudents();
}
5.7 mybatis动态代理的接口对应的映射文件StudentMapper
<?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.suke.mapper.StudentMapper">
<!--注册学生信息的sql语句-->
<insert id="insertStudent" parameterType="student">
insert into student(name, email, age)
values (#{name}, #{email}, #{age});
</insert>
<!--查询学生列表信息SQL语句-->
<select id="selectStudents" resultType="student">
select *
from student;
</select>
</mapper>
5.8 编写Servlet程序StudentServlet
public class StudentServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1、设置请求的编码
req.setCharacterEncoding("utf-8");
//2、获取表单中数据
String strName = req.getParameter("name");
String strEmail = req.getParameter("email");
String strAge = req.getParameter("age");
//3、创建Spring的容器对象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/total.xml");
//4、创建学生对象
Student student = new Student();
student.setName(strName);
student.setEmail(strEmail);
student.setAge(Integer.parseInt(strAge));
//5、获取业务层对象
StudentService studentService = (StudentService) applicationContext.getBean("studentService");
int result = studentService.addStudent(student);
//6、跳转到成功的页面
req.getRequestDispatcher("/result.jsp").forward(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}
5.9 spring和mybatis的整合
1)applicationContext-dao.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--加载jdbc的属性文件-->
<context:property-placeholder location="classpath:jdbc/db.properties"/>
<!--配置mysql数据库参数:使用的是Druid技术-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close" lazy-init="false">
<!--获取mysql的参数-->
<property name="driverClassName" value="${jdbc_driver}"/>
<property name="url" value="${jdbc_url}"/>
<property name="username" value="${jdbc_user}"/>
<property name="password" value="${jdbc_password}"/>
<!--获取连接池中参数-->
<property name="initialSize" value="${initialSize}"/>
<property name="minIdle" value="${mindle}"/>
<property name="maxActive" value="${maxActive}"/>
<property name="maxWait" value="${maxWatit}"/>
</bean>
<!--管理mybatis的工厂类对象-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--加载数据源-->
<property name="dataSource" ref="dataSource"/>
<!--加载mybatis的主配置文件-->
<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"/>
<!--配置别名包扫描器-->
<property name="typeAliasesPackage" value="com.suke.pojo"/>
</bean>
<!--Spring配置mybatis的动态代理的过程-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--配置映射文件的包扫描器-->
<property name="basePackage" value="com.suke.mapper"/>
</bean>
</beans>
2)applicationContext-service.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--添加Service层的注解的包扫描器-->
<context:component-scan base-package="com.suke.service"/>
</beans>
3)applicationContext-trans.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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--1、配置平台事务的管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--配置数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务的隔离级别和传播行为-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" isolation="DEFAULT"/>
</tx:attributes>
</tx:advice>
<!--事务管理器和切入点配置-->
<aop:config>
<aop:pointcut id="txService" expression="execution(* com.suke.service.*.*(..))"/>
<!--事务使用内置的切面-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txService"/>
</aop:config>
</beans>
4)dao.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--<import resource="classpath:spring/applicationContext-dao.xml"/>
<import resource="classpath:spring/applicationContext-service.xml"/>-->
<import resource="classpath:spring/applicationContext-*.xml"/>
</beans>
5)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>
<!--保持空数据即可:交给Spring容器管理-->
</configuration>
6)db.properties
jdbc_driver=com.mysql.cj.jdbc.Driver jdbc_url=jdbc:mysql://localhost:3306/myjdbc?characterEncoding=utf8&useSSL=false&serverTimezone=UTC jdbc_user=root jdbc_password=root initialSize=10 mindle=10 maxActive=30 maxWatit=6000
7)log4j.properties
log4j.rootLogger=DEBUG,console,file log4j.appender.console = org.apache.log4j.ConsoleAppender log4j.appender.console.Target = System.out log4j.appender.console.Threshold=DEBUG log4j.appender.console.layout = org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=[%c]-%m%n log4j.appender.file = org.apache.log4j.RollingFileAppender log4j.appender.file.File=./log/whatsblog.log log4j.appender.file.MaxFileSize=10mb log4j.appender.file.Threshold=DEBUG log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n log4j.logger.org.mybatis=DEBUG log4j.logger.java.sql=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.ResultSet=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
5.10 编写web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置Servlet-->
<servlet>
<servlet-name>StudentServlet</servlet-name>
<servlet-class>com.suke.controller.StudentServlet</servlet-class>
</servlet>
<!--配置访问Servlet的映射路径-->
<servlet-mapping>
<servlet-name>StudentServlet</servlet-name>
<url-pattern>/reg</url-pattern>
</servlet-mapping>
</web-app>
5.11 更新StudentServlet
public class StudentServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1、设置请求的编码
req.setCharacterEncoding("utf-8");
//2、获取表单中数据
String strName = req.getParameter("name");
String strEmail = req.getParameter("email");
String strAge = req.getParameter("age");
//3、创建Spring的容器对象
//ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/total.xml");
WebApplicationContext applicationContext = null;
//全局对象
ServletContext sc = getServletContext();
applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
//4、创建学生对象
Student student = new Student();
student.setName(strName);
student.setEmail(strEmail);
student.setAge(Integer.parseInt(strAge));
//5、获取业务层对象
StudentService studentService = (StudentService) applicationContext.getBean("studentService");
int result = studentService.addStudent(student);
//6、跳转到成功的页面
req.getRequestDispatcher("/result.jsp").forward(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}
5.12 更新web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--初始化Spring的容器文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext-*.xml</param-value>
</context-param>
<!--使用监听器监听Spring的容器文件-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置Servlet-->
<servlet>
<servlet-name>StudentServlet</servlet-name>
<servlet-class>com.suke.controller.StudentServlet</servlet-class>
</servlet>
<!--配置访问Servlet的映射路径-->
<servlet-mapping>
<servlet-name>StudentServlet</servlet-name>
<url-pattern>/reg</url-pattern>
</servlet-mapping>
</web-app>