(1)SSM是什麼?
Spring,SpringMVC,Mybastis
(2)為什麼要專門訓練SSM
要開發一個專案,首先是搭建SSM環境,之後才能開發其他功能
(3)整合思路是什麼?
》》1.先搭建整合的環境
》》2.先把Spring的設定搭建完成
》》3.再使用Spring整合SpringMVC框架
》》4.最後使用Spring整合MyBatis框架
(4)SSM整合可以使用多種方式,咱們會選擇XML + 註解
的方式
(1)資料庫建立ssm
(2)建立maven工程
(3)properties給誰用?
(4)依賴框架
(5)log4j
create database ssm;
use ssm;
create table person(
id int primary key auto_increment,
`name` varchar(20),
money double
);
pom.xml
<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.2.9.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>
</properties>
<dependencies>
<!-- 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>test</scope>
</dependency>
<!-- 匯入Mysql資料庫連結jar包 -->
<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>
<!-- JSTL標籤類 -->
<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 -->
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis/spring包 -->
<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>
src\main\resources\log4j.properties
自已有需求,可以自行設定紀錄檔輸出級別
和紀錄檔存放位置
。
# Set root category priority to INFO and its only appender to CONSOLE.
# log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
# 可以把debug換成info,以免輸出很多debug資訊
log4j.rootCategory=debug, 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=d:\ssm.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
src\main\java\cn\cyl\domain\Person.java
package cn.cyl.domain;
public class Person {
private Integer id;
private String name;
private Double money;
public Person() {
}
public Person(String name, Double money) {
this.name = name;
this.money = money;
}
@Override
public String toString() {
return "Person{" +
"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;
}
}
src\main\java\cn\cyl\service\IPersonService.java
package cn.cyl.service;
import cn.cyl.domain.Person;
import java.util.List;
public interface IPersonService {
//查詢所有使用者
List<Person> findAll();
//新增一個使用者
void savePerson(Person person);
//新增多個使用者
void savePersons(List<Person> persons);
}
src\main\java\cn\cyl\dao\IPersonDao.java
package cn.cyl.dao;
import cn.cyl.domain.Person;
import java.util.List;
public interface IPersonDao {
//查詢所有
List<Person> findAll();
//儲存
void savePerson(Person person);
}
src\main\resources\applicationContext.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: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 @Repository @Component @AutoWried-->
<context:component-scan base-package="cn.cyl">
<!--制定掃包規則,不掃描 @Controller註解的JAVA類,其他的還是要掃描 -->
<!--@Controller 註解的 JAVA 類是由springmvc來掃描-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
src\main\java\cn\cyl\service\impl\PersonServiceImpl.java
/* @Service("personService")
IPersonService的實現類現在就一個,我們就不給它起id名了。*/
@Service
public class PersonServiceImpl implements IPersonService {
@Autowired
IPersonDao iPersonDao;
@Override
public List<Person> findAll() {
List<Person> list = iPersonDao.findAll();
return list;
}
@Override
public void savePerson(Person person) {
iPersonDao.save(person);
}
@Override
public void savePersons(List<Person> persons) {
for (int i = 0; i < persons.size(); i++) {
//除0異常
/*if (i==2){
System.out.println(i/0);
}*/
iPersonDao.savePerson(persons.get(i));
}
}
}
src\main\java\cn\cyl\dao\impl\PersonDaoImpl.java
/* 整合Mybatis後,dao層功能由Mybatis完成,此註解就可以去掉了,不然會多個實現類
然後後使用@Deprecated註解表示該類過時,不會再用了*/
@Repository
public class PersonDaoImpl implements IPersonDao {
@Override
public List<Person> findAll() {
System.out.println("查詢所有 findAll Dao");
//假資料庫
List<Person> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Person person = new Person("jack"+i,100.00);
person.setId(i+1);
list.add(person);
}
return list;
}
@Override
public void savePerson(Person person) {
System.out.println("儲存 save Dao");
}
}
src\test\java\cn\cyl\service\TestPersonServiceImpl.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestPersonServiceImpl {
//建立紀錄檔類物件
private static final Logger log = LoggerFactory.getLogger(TestPersonServiceImpl.class.getName());
@Autowired
IPersonService iPersonService;
@Test
public void test01(){//編寫兩個業務功能 1.查詢所有的person 2.儲存一個person
//呼叫 查詢方法
log.info(iPersonService+"");
List<Person> list = iPersonService.findAll();
//呼叫 儲存方法
log.info(list+"");
Person person = new Person("jack",100.00);
iPersonService.savePerson(person);
}
}
(1)web.xml中設定前端控制器DispatcherServlet
SpringMVC的核心就是DispatcherServlet,DispatcherServlet實質也是一個HttpServlet。DispatcherSevlet負責將請求分發,所有的請求都有經過它來統一分發。
(2)web.xml中設定編碼過濾器CharacterEncodingFilter
在 SpringMVC 中,框架直接給我們提供了一個用來解決請求和響應的亂碼問題的過濾器 CharacterEncodingFilter
。
(3)web.xml中設定編碼監聽器ContextLoaderListener
web.xml中的組態檔中ContextLoaderListener作為監聽器,會監聽web容器相關事件,在web容器啟動或者關閉時觸發執行響應程式
。
整合關鍵點就是:在web.xml中設定監聽器實現啟動服務建立容器
。
原理是:
1:Spring自動編寫了一個監聽器,該監聽器監聽ServletContext物件的建立
2:一旦ServletContext建立時,會自動讀取contextConfigLocation設定,獲取核心組態檔applicationContext.xml
3:解析核心組態檔,根據包掃描器建立物件
4:將建立的物件存入Spring容器
5:將建立的Spring容器存入ServletContext域物件
之後我們需要做的事情:
1:從ServletContext域物件獲取Spring容器
2:從Spring容器中獲取想要的物件
src\main\webapp\WEB-INF\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>
<!--設定spring組態檔的路徑及名稱-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--解決中文亂碼的過濾器-->
<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>
<!--上下文監聽器,伺服器部署完成後,該監聽器啟動,監聽ServletContext物件建立,
自動裝配ApplicationContext.xml的設定資訊,然後將spring容器放到該ServletContext中快取起來
設定Spring的監聽器,預設只載入WEB-INF目錄下的applicationContext.xml組態檔-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--設定前端控制器 controller-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--載入springmvc.xml
init-param 是DispatcherServlet的初始化引數,指定springmvc的路徑及檔名稱
當該Servlet 執行,springmvc的組態檔也會被載入進來-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!--設定servlet的啟動載入時機
load-on-startup 是servlet的載入時機, 1-5值,取值越小,載入時機越早-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
springmvc中設定檢視解析器,元件掃描,註解驅動,設定springmvc對資原始檔的放行。
src\main\resources\springmvc.xml
<?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">
<!-- 設定建立 spring 容器要掃描的包 -->
<context:component-scan base-package="cn.cyl">
<!-- 制定掃包規則 ,只掃描使用@Controller 註解的 JAVA 類 -->
<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>
<!--過濾靜態資源 .js .css png-->
<mvc:resources location="/css/" mapping="/css/**" />
<mvc:resources location="/images/" mapping="/images/**" />
<mvc:resources location="/js/" mapping="/js/**" />
<!--設定處理器對映器和處理器介面卡 -->
<!--開啟SpringMVC註解的支援 @RequestMapping @RequestBody @ResponseBody-->
<mvc:annotation-driven/>
</beans>
src\main\java\cn\cyl\controller\PersonController.java
@Controller
@RequestMapping("/person")
public class PersonController {
private static final Logger log = LoggerFactory.getLogger(PersonController.class);
@Autowired
IPersonService iPersonService;
@RequestMapping(path = "/list",method = RequestMethod.GET)
public String list(Model model){
List<Person> list = iPersonService.findAll();
log.info("所有資訊 list :"+list);
model.addAttribute("list",list);
return "list";
}
}
src\main\webapp\WEB-INF\pages\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 border="1px" width="100%">
<c:forEach items="${list}" var="person">
<tr>
<td>${person.id}</td>
<td>${person.name}</td>
<td>${person.money}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
src\main\resources\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>
<!--載入資料庫常陣列態檔-->
<properties resource="db.properties"/>
<!--該包下的類起別名-->
<typeAliases>
<package name="cn.cyl.domain"/>
</typeAliases>
<!--設定mybatis的開發環境,該目錄下可以有多個environment,
和spring整合後 environments設定將廢除-->
<environments default="mysql"><!--當前預設選擇的是mysql環境-->
<!--設定mysql的環境-->
<environment id="mysql">
<!--設定事務的型別:jdbc事務管理-->
<transactionManager type="JDBC"/>
<!--設定連線資料庫的資訊:用的是資料來源(連線池)-->
<dataSource type="POOLED">
<!--四大設定資訊-->
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--設定多個對映檔案,告知mybatis對映設定的位置-->
<mappers>
<package name="cn.cyl.dao"/>
</mappers>
</configuration>
資料庫常陣列態檔的內容
src\main\resources\db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=
注意:我們使用代理 dao的方式來操作持久層,所以之前寫的Dao的實現類 PersonDaoImpl 就是多餘的了。
<?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.cyl.dao.IPersonDao">
<select id="findAll" resultType="person">
select * from person
</select>
<insert id="savePerson" parameterType="person">
insert into person (name,money)values(#{name},#{money})
</insert>
</mapper>
public class TestMyBatis {
private SqlSession session;
@Before
public void init(){
//載入組態檔
InputStream in = TestMyBatis.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml");
// 建立SqlSessionFactory物件
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
// 建立SqlSession物件
session = factory.openSession();
}
@After
public void destory(){
session.commit();
session.close();
}
@Test
public void test01(){
IPersonDao dao = session.getMapper(IPersonDao.class);
dao.savePerson(new Person("tony",200.00));
}
@Test
public void test02(){
IPersonDao dao = session.getMapper(IPersonDao.class);
List<Person> list = dao.findAll();
System.out.println(list);
}
}
把 mybatis 組態檔(SqlMapConfig.xml)中內容設定到 spring 組態檔中,同時,把 mybatis 組態檔的內容清掉,也可以不清。
MyBatis-Spring 會幫助你將 MyBatis 程式碼無縫地整合到 Spring 中。它將允許 MyBatis 參與到 Spring 的事務管理之中,建立對映器 mapper 和 SqlSession 並注入到 bean 中。
以後就不需要呼叫 session.getMapper(IpersonDao.class)
session.commit()
session.close()
pom.xml
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
src\main\resources\applicationContext.xml
<!--載入資料庫常陣列態檔-->
<context:property-placeholder location="classpath:db.properties" />
<!--設定資料來源連線池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/crud"/>
<property name="user" value="root"/>
<property name="password" value=""/>
</bean>
<!-- 設定 MyBatis 的 Session 工廠 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 資料庫連線池 -->
<property name="dataSource" ref="dataSource"/>
<!--起別名-->
<property name="typeAliasesPackage" value="cn.cyl.domain"/>
</bean>
<!-- MapperScannerConfigurer 設定自動掃描所有 Mapper 介面和檔案,
然後查詢類路徑下的對映器並自動將它們建立成MapperFactoryBean,
MapperFactoryBean生成這些介面的代理類,並注入到應用程式中-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--掃描這個包下面所有的介面和對映檔案-->
<property name="basePackage" value="cn.cyl.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
src\main\resources\applicationContext.xml
<!--設定Spring框架宣告式事務管理-->
<!--設定事務管理器-->
<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:pointcut id="service" expression="execution(* cn.cyl.service.impl.*ServiceImpl.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="service"/>
</aop:config>
src\test\java\cn\cyl\service\TestPersonServiceImpl.java
@Test
public void test02(){
List<Person> list = new ArrayList<>();
list.add(new Person("jack",100.00));
list.add(new Person("rose",200.00));
list.add(new Person("tony",300.00));
iPersonService.savePersons(list);
}
@Override
public void savePersons(List<Person> persons) {
for (int i = 0; i < persons.size(); i++) {
//除0異常
if (i==2){
System.out.println(i/0);
}
iPersonDao.savePerson(persons.get(i));
}
}
新增資料失敗