1 | 创建MAVEN骨架(基于webapp) |
---|---|
2 | 创建基本文件目录(pojo , controller , service … ) |
3 | 配置Spring环境 |
4 | 配置SpringMVC环境 |
5 | 测试 Spring+SpringMVC整合 |
6 | 配置mybatis环境 |
7 | 测试Spring + mybatis 整合 |
8 | 测试Spring + SpringMVC + mybatis整合 |
1.1 这里要注意的地方就是在创建的时候要配置一组键值对,加快MAVEN的构建(导入本地仓库)
1.3 修改pom.xml配置文件(properties)
<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>8.0.12</mysql.version>
<mybatis.version>3.4.5</mybatis.version>
</properties>
1.4 导入要用到的jar包坐标
<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>
1.5 Resource文件无法扫描到的问题(在build标签中):
<!-- 扫描资源文件的,很重要!!! -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
2.1 在资源文件夹下创建applicationContext.xml 配置文件(Spring配置文件)
<?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"
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/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
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">
<!--
这里Spring不扫描控制层注解
-->
<context:component-scan base-package="cn.itcast">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
如果有不了解注解属性的小伙伴们 可以点击----》关于扫描注解的配置使用
2.2 创建pojo类(对应数据库的类型)
public class Account implements Serializable {
private Integer id;
private String name;
private Double money;
...(set() get() )
}
2.3 创建服务层接口(AccountService)
@Repository
public interface AccountService {
public List<Account> findAll();
public void saveAccount(Account account);
}
2.4 创建服务层接口实现类(AccountServiceImp)
@Service("accountService")
public class AccountServiceImp implements AccountService {
@Override
public List<Account> findAll() {
System.out.println("查询所有记录...");
return null;
}
@Override
public void saveAccount(Account account) {
System.out.println("插入成功...");
}
}
2.5 创建测试类(测试Spring环境是否搭建成功)
@Test
public void testSpringEve(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService accountService = (AccountService) context.getBean("accountService");
accountService.findAll();
}
输出:查询所有记录…
有输出结果,并且没有抛异常,说明Spring环境已经搭建完成
3.1 配置前端控制器(DispatcherServlet)(web.xml)中配置
<!-- 配置前端控制器 -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
3.2 创建SpringMVC配置文件
<!-- 配置只扫描Controller注解 -->
<context:component-scan base-package="cn.itcast.controller"
use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
3.3 创建视图解析器
<!-- 配置视图解析器 -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 文件位置 -->
<property name="prefix" value="/WEB-INF/pages/"/>
<!-- 后缀名 -->
<property name="suffix" value=".jsp"/>
</bean>
<!-- 配置mvc注解开启 -->
<mvc:annotation-driven/>
3.4 在WEB-INF下创建pages文件夹,在pages文件夹中创建success.jsp文件
3.5 加载配置SpringMVC配置文件(web.xml中)
<!-- 前端控制器 -->
<servlet>
<servlet-name>dispatcherServlet</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>
</servlet>
3.6 创建Controller层测试类(WebController)
@Controller
@RequestMapping("/account")
public class WebController {
@Autowired
@Qualifier("accountService")
private AccountServiceImp accountService;
/*
测试spring+springmvc环境搭建
*/
@RequestMapping("/testSpring")
public String testSpringMVC_Spring_Eve(Model model){
System.out.println("成功");
return "success";
}
数据库脚本如下:
CREATE DATABASE ssm;
USE ssm;
CREATE TABLE account(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20),
money DOUBLE );
4.1 在资源文件夹下(resources)创建druid.properties资源文件(mysql版本在8.0以上,所以url写法要多补充一些东西)
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql:///ssm?useSSL=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456
4.2 在applicationContext.xml中继续搭建mybatis相关环境
<!-- 搭建mybatis环境 -->
<!-- 加载本地配置文件 -->
<context:property-placeholder location="classpath:druid.properties"/>
<!-- 配置数据源 -->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 配置SqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"></property>
</bean>
<!-- 配置自动扫描包 -->
<bean id="scannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.itcast.dao"/>
</bean>
<!-- 配置事务管理器 -->
<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="find*" read-only="true"/>
<tx:method name="*"/>
<tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
</tx:attributes>
</tx:advice>
<!-- 配置AOP切面表达式 -->
<aop:config>
<aop:pointcut id="point" expression="execution(* cn.itcast.service.Imp.AccountServiceImp.*(..))"></aop:pointcut>
<aop:advisor advice-ref="txAdvice" pointcut-ref="point"></aop:advisor>
</aop:config>
4.3 在dao目录下创建对应的SsmDao.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="cn.itcast.dao.SsmDao">
<select id="findAll" resultType="cn.itcast.domain.Account">
select * from account
</select>
<insert id="saveAccount">
insert into account (name,money) values (#{name},#{money})
</insert>
</mapper>
4.4 修改实现类代码
@Autowired
private SsmDao ssmDao;
@Override
public List<Account> findAll() {
System.out.println("查询所有记录...");
return ssmDao.findAll();
}
@Override
public void saveAccount(Account account) {
System.out.println("插入成功...");
ssmDao.saveAccount(account);
}
4.5 编写测试类,测试SSM环境,并且将查到的值,展示到list.jsp界面上
@Controller
@RequestMapping("/account")
public class WebController {
@Autowired
@Qualifier("accountService")
private AccountServiceImp accountService;
/*
测试spring+springmvc+mybatis + 查询用户操作
*/
@RequestMapping("/testSpring")
public String testSpringMVC_Spring_Eve(Model model){
System.out.println("成功");
List<Account> alist = accountService.findAll();
model.addAttribute("alist",alist);
return "list";
}
/*
测试spring+springmvc+mybatis + 储存用户操作
*/
@RequestMapping("/testSave")
public String testSave(Account account ){
System.out.println("储存成功...");
accountService.saveAccount(account);
return "success";
}
}
4.6 编写list.jsp界面,查询到的信息展示到界面上
<%@ 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>
<table cellpadding="1">
<c:forEach items="${alist}" var="account" varStatus="s">
<tr bgcolor="#fafad2">
<td>姓名: ${account.name}</td>
<td>金额: ${account.money}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
4.7 搭建form表单并且提交展示:
<form action="/account/testSave" method="post">
<!-- 这里注意要和实体类属性名称对应 MVC会自动封装到实体类-->
用户名:<input type="text" name="name" />
金额:<input type="text" name="money" />
<input type="submit" value="提交" />
</form>
<web-app>
<display-name>Archetype Created Web Applicationdisplay-name>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
<filter>
<filter-name>characterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>characterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
web-app>
6.1查询结果如下: