SpringMVC第三天
##SpringMVC大纲
第1章:搭建整合环境
####1.1 搭建整合环境
整合说明:SSM整合可以使用多种方式,咱们会选择XML + 注解的方式
整合的思路
- 先搭建整合的环境
- 先把Spring的配置搭建完成
- 再使用Spring整合SpringMVC框架
- 最后使用Spring整合MyBatis框架
创建数据库和表结构
语句
create database ssm;
use ssm;
create table account(
id int primary key auto_increment,
name varchar(20),
money double
);
创建ssm,并在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.gavin</groupId>
<artifactId>springmvcspringmybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<!--war包-->
<packaging>war</packaging>
<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.6</mysql.version>
<mybatis.version>3.4.5</mybatis.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- 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>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>18081</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
部署ssm的项目,只要把ssm项目加入到tomcat服务器中即可
####1.2 编写实体类
package com.gavin.domain;
public class Account {
private Integer id;
private String name;
private Double money;
//get...set...toString
}
####1.3 编写dao接口
package com.gavin.dao;
import com.gavin.domain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface AccountDao {
/***
* 保存账号
* @param account
*/
int saveAccount(Account account);
/***
* 查询所有
* @return
*/
List<Account> findAll();
}
####1.4 编写service接口和实现类
package com.gavin.service;
import com.gavin.domain.Account;
import java.util.List;
public interface AccountService {
/***
* 保存账号
* @param account
*/
void saveAccount(Account account);
/***
* 查询所有
* @return
*/
List<Account> findAll();
}
package com.gavin.service.impl;
import com.gavin.dao.AccountDao;
import com.gavin.domain.Account;
import com.gavin.service.AccountService;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
@Override
public void saveAccount(Account account) {
System.out.println(acount);
}
@Override
public List<Account> findAll() {
System.out.println("正在执行findAll");
return null;
}
}
第2章:Spring框架代码的编写
####2.1 搭建和测试Spring的开发环境
#####2.1.1 在ssm的resources下创建spring.xml的配置文件,编写具体的配置信息。
<?xml version="1.0" encoding="UTF-8"?>
<!-- 开启注解扫描,要扫描的是service和dao层的注解,要忽略web层注解,因为web层让SpringMVC框架去管理 -->
<context:component-scan base-package="com.gavin">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
#####2.1.2 在ssm项目中编写测试方法,进行测试
public class SpringMyBatisSpringMVCTest {
private AccountService accountService;
@Before
public void init(){
ApplicationContext act = new ClassPathXmlApplicationContext("spring.xml");
accountService = act.getBean(AccountService.class);
}
@Test
public void testFindAll(){
List<Account> accounts = accountService.findAll();
}
}
第3章:Spring整合SpringMVC框架
3.1 搭建和测试SpringMVC的开发环境
#####3.1.1 在web.xml中配置DispatcherServlet前端控制器
dispatcherServlet
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:springmvc.xml
1
dispatcherServlet
/
#####3.1.2 在web.xml中配置DispatcherServlet过滤器解决中文乱码
characterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
characterEncodingFilter
/*
#####3.1.3 创建springmvc.xml的配置文件,编写配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!-- 扫描controller的注解,别的不扫描 -->
<context:component-scan base-package="com.gavin" use-default-filters="false">
<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>
#####3.1.4 测试SpringMVC的框架搭建是否成功
######3.1.4.1 编写index.jsp和list.jsp编写,超链接
查询所有
######3.1.4.1 创建AccountController类,编写方法,进行测试
package com.gavin.controller;
import com.gavin.domain.Account;
import com.gavin.service.AccountService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
@RequestMapping(value = “/account”)
public class AccountController {
private AccountService accountService;
/***
* 查询所有
* @return
*/
@RequestMapping(value = "/findAll")
public String findAll(){
return "list";
}
/***
* 保存账号
* @param account
* @return
*/
@RequestMapping(value = "/add")
public String add(Account account){
return "redirect:account/findAll";
}
}
3.2 Spring整合SpringMVC的框架
目的:在controller中能成功的调用service对象中的方法。
在项目启动的时候,就去加载spring.xml的配置文件,在web.xml中配置ContextLoaderListener监听器。
<!-- 配置Spring的监听器 -->
<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>
在controller中注入service对象,调用service对象的方法进行测试
package com.gavin.controller;
import com.gavin.domain.Account;
import com.gavin.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
@RequestMapping(value = "/account")
public class AccountController {
@Autowired
private AccountService accountService;
/***
* 查询所有
* @return
*/
@RequestMapping(value = "/findAll")
public String findAll(){
//调用AccountService实现查询
List<Account> accounts = accountService.findAll();
return "list";
}
/***
* 保存账号
* @param account
* @return
*/
@RequestMapping(value = "/add")
public String add(Account account){
//增加数据
accountService.saveAccount(account);
return "redirect:account/findAll";
}
}
第4章:Spring整合MyBatis框架
4.1 搭建和测试MyBatis的环境
4.1.1 在web项目中编写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>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/spring5"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!-- 使用的是注解 -->
<mappers>
<!-- <mapper class="cn.itcast.dao.AccountDao"/> -->
<!-- 该包下所有的dao接口都可以使用 -->
<package name="com.gavin.dao"/>
</mappers>
</configuration>
4.1.2 在AccountDao接口的方法上添加注解,编写SQL语句
package com.gavin.dao;
import com.gavin.domain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface AccountDao {
/***
* 保存账号
* @param account
*/
@Insert("insert into account(name,money)values(#{name},#{money})")
int saveAccount(Account account);
/***
* 查询所有
* @return
*/
@Select("select * from account")
List<Account> findAll();
}
4.1.3 编写测试的方法
public class MyBatisTest {
@Test
public void testMyBatis() throws IOException {
//获取SqlMapConfig.xml字节输入流
InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");
//获取SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = builder.build(is);
//创建sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession(true);
AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
//查询所有
List<Account> accounts = accountDao.findAll();
for (Account account : accounts) {
System.out.println(account);
}
//关闭资源
sqlSession.close();
}
}
4.2 Spring整合MyBatis框架
4.2.1 目的:把SqlMapConfig.xml配置文件中的内容配置到spring.xml配置文件中
<!-- 配置的连接池对象 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/spring5"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</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.gavin.dao"/>
</bean>
4.2.2 在service中注入dao对象,进行测试
代码如下
AccountDao代码:
package com.gavin.dao;
import com.gavin.domain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface AccountDao {
/***
* 保存账号
* @param account
*/
@Insert("insert into account(name,money)values(#{name},#{money})")
int saveAccount(Account account);
/***
* 查询所有
* @return
*/
@Select("select * from account")
List<Account> findAll();
}
AccountServiceImpl代码:
package com.gavin.service.impl;
import com.gavin.dao.AccountDao;
import com.gavin.domain.Account;
import com.gavin.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public void saveAccount(Account account) {
int acount = accountDao.saveAccount(account);
}
@Override
public List<Account> findAll() {
return accountDao.findAll();
}
}
AccountController代码:
package com.gavin.controller;
import com.gavin.domain.Account;
import com.gavin.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
@RequestMapping(value = "/account")
public class AccountController {
@Autowired
private AccountService accountService;
/***
* 查询所有
* @return
*/
@RequestMapping(value = "/findAll")
public String findAll(){
//调用AccountService实现查询
List<Account> accounts = accountService.findAll();
return "list";
}
/***
* 保存账号
* @param account
* @return
*/
@RequestMapping(value = "/add")
public String add(Account account){
//增加数据
accountService.saveAccount(account);
return "redirect:/account/findAll";
}
}
4.2.3 配置Spring的声明式事务管理
在spring.xml中配置声明式事务:
<!-- 配置事务管理器 -->
<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="*" isolation="DEFAULT"/>
</tx:attributes>
</tx:advice>
<!-- 配置AOP增强事务 -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(public * com.gavin.service.impl.*.*(..))"/>
</aop:config>
4.2.4 测试保存帐户的方法
<form action="/account/add" method="post">
姓名:<input type="text" name="name"/><br/>
金额:<input type="text" name="money"/><br/>
<input type="submit" value="保存"/><br/>
</form>