目录结构,其中mybatis.xml并没有使用,已经整合到Spring容器中
一、配置坐标(pom.xml)
其中c3p0连接池并没有使用,用的druid连接池
<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.0.2.RELEASE</spring.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<mysql.version>5.1.40</mysql.version>
<mybatis.version>3.4.5</mybatis.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!-- spring -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</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>
<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>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>
<!-- log start -->
<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>
<!-- log end -->
<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.0</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
二、配置log4j配置文件(log4j.properties)
其中log4j.appender.LOGFILE.File需要保证有这个文件,自己配置
# 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=dC:\Users\dell\Desktop\homework\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
三、整合
1.配置web.xml文件(Spring、SpringMVC)配置
<!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>
<!--配置中文解码,值一定要是UTF-8-->
<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>
<!--监听Spring配置文件,让其修改生命周期-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--不写的话,默认监听WEB-INF下的applicationContext.xml文件所以修改目录地址-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--前端分发器-->
<servlet>
<servlet-name>dispatcherServlet</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>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
2.整合mybatis到Spring容器中管理(applicationContext.xml)
1.解除对SpringMVC中Controller的管理。
2.其中mybatis采用xml的方式执行sql语句所以在配置SqlSessionFactory工厂需要加上一个mapperLocations属性来找映射文件所在目录。如是注解方式则无需加。
<?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">
<!--spring配置-->
<!--开启注解的扫描,希望处理service和dao,controller不需要Spring框架去处理-->
<context:component-scan base-package="edu.xiao">
<!--配置哪些注解不扫描-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--Spring整合mybatis-->
<!--1.配置连接池-->
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSources">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/eesy"/>
<property name="username" value="root"/>
<property name="password" value="y426759813."/>
</bean>
<!--2.配置SqlSessionFactory工厂-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
<property name="dataSource" ref="dataSources"/>
<!-- xml方式,自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!--3. 配置AccountDao接口所在包及注解方式-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="mapperScannerConfigurer">
<property name="basePackage" value="edu.xiao.dao"/>
</bean>
<!--Spring配置声明式事务管理,这样增删改就会提交,更新数据库-->
<!--1.配置事务管理器-->
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="dataSourceTransactionManager">
<property name="dataSource" ref="dataSources"/>
</bean>
<!--2.配置事务通知-->
<tx:advice transaction-manager="dataSourceTransactionManager" id="transactionInterceptor">
<tx:attributes>
<tx:method name="find*" read-only="true"/>
<tx:method name="*" isolation="DEFAULT"/>
</tx:attributes>
</tx:advice>
<!--配置AOP增强-->
<aop:config>
<aop:advisor advice-ref="transactionInterceptor" pointcut="execution( * edu.xiao.service.impl.*tServiceImpl.*(..))"/>
</aop:config>
</beans>
3.配置SpringMVC的配置文件(springmvc.xml)
只扫描Controller注解
<?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">
<!--springMVC配置-->
<!--开启注解扫描,只扫描Controller注解-->
<context:component-scan base-package="edu.xiao">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!--配置的视图解析器对象-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<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>
四、编写测试代码
准备数据库表和pojo类
pojo实体类Account
package edu.xiao.pojo;
import java.io.Serializable;
public class Account implements Serializable {
private Integer id;
private String name;
private Double money;
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
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;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
}
1.编写Spring框架的表现层(AccountController)
package edu.xiao.controller;
import edu.xiao.pojo.Account;
import edu.xiao.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private IAccountService service;
@RequestMapping("/testSpring")
public ModelAndView testSpring() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("success"); /*跳转到成功页面*/
System.out.println("表现层:testSuccess"); /*打印,方法执行成功*/
List<Account> listAccount = service.findListAccount(); /*与业务层交互,查询所有*/
modelAndView.addObject("list",listAccount);/*把数据传入request域*/
for (Account account : listAccount) {
System.out.println(account);/*打印用户信息*/
}
return modelAndView;
}
@RequestMapping("/saveAccount")
public void saveAccount(HttpServletRequest req, HttpServletResponse res,Account account) throws Exception {
service.saveAccount(account); /*调用业务层的保存,然后在查询所有,跳转到前端success页面*/
res.sendRedirect(req.getContextPath()+"/account/testSpring");
return;
}
}
2.编写持久层(IAccountDao)
因为整合了mybatis所以不需要写实现类
package edu.xiao.dao;
import edu.xiao.pojo.Account;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository("accountDao")
public interface IAccountDao {
List<Account> findListAccount();
void saveAccount(Account account);
}
3.编写业务层
i.业务接口类(IAccountService)
package edu.xiao.service;
import edu.xiao.pojo.Account;
import java.util.List;
public interface IAccountService {
List<Account> findListAccount();
void saveAccount(Account account);
}
o.业务接口实现类(AccountServiceImpl)
package edu.xiao.service.impl;
import edu.xiao.dao.IAccountDao;
import edu.xiao.pojo.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import edu.xiao.service.IAccountService;
import java.util.List;
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
public List<Account> findListAccount() {
System.out.println("业务层:查询所有。。。");
return accountDao.findListAccount();
}
@Override
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
}
4.编写一个页面测试
i.编写一个用户信息保存的表单页(index.jsp)
其中input的name值一定要和pojo的属性值一致,让SpringMVC自动封装
<%--
Created by IntelliJ IDEA.
User: dell
Date: 2020/4/8
Time: 21:43
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>
<form action="account/saveAccount" method="post">
姓名:<input type="text" name="name"><br>
金额:<input type="text" name="money"><br>
<input type="submit">
</form>
</body>
</html>
o.编写一个效果页面(success.jsp)
<%--
Created by IntelliJ IDEA.
User: dell
Date: 2020/4/8
Time: 21:42
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>
<h3>配置成功!</h3><br>
<c:forEach items="${list}" var="account">
${
account.name} : ${
account.money} <br/>
</c:forEach>
</body>
</html>