一、配置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.qianfeng</groupId>
<artifactId>SsmDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<!--統(tǒng)一管理spring所有的版本-->
<properties>
<spring-version>4.3.6.RELEASE</spring-version>
</properties>
<dependencies>
<!--springmvc的依賴-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<!--rest風(fēng)格使用-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.10</version>
</dependency>
<!--mariadb-->
<dependency>
<groupId>mariadb</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>1.8.0</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!--mybatis spring的插件手销,將mybatis交給spring來管理-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!--spring的單元測試-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-version}</version>
</dependency>
<!--spring jdbc,包含事務(wù)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- spring aop的面向切面的配置-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>com.springsource.org.aspectj.weaver</artifactId>
<version>1.6.8.RELEASE</version>
</dependency>
<!--druid數(shù)據(jù)源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.28</version>
</dependency>
<!--日志信息-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--單元測試-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- define the project compile level -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- 添加tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
<port>8080</port>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
</plugins>
</build>
</project>
二碧信、在WEB-INF下新建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_3_1.xsd"
version="3.1">
<!--配置Springmvc-->
<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:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--中文過濾器-->
<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>
</web-app>
三街夭、在resource目錄下配置spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
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/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">
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<!--<property name="suffix" value=".jsp"></property>-->
</bean>
<!--配置缺省的servlet處理器砰碴,靜態(tài)資源可以直接被訪問-->
<mvc:default-servlet-handler></mvc:default-servlet-handler>
<!--上下文的組件掃描-->
<!--設(shè)置包掃描,分別掃描controller和service包-->
<!--<context:component-scan base-package="com.qianfeng" />-->
<!--掃描所有包也行-->
<context:component-scan base-package="com.qianfeng.controller"></context:component-scan>
<context:component-scan base-package="com.qianfeng.service" />
<!--配置注解驅(qū)動-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--設(shè)置ssm的整合注解配置-->
<context:annotation-config />
<!--引入spring和mybatis的整合文件-->
<import resource="classpath:spring-mybatis.xml" />
</beans>
四板丽、在resource目錄下配置spring-mybatis.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: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/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 配置druid數(shù)據(jù)源 -->
<!--driver的name應(yīng)為driverClassName-->
<bean id="ds" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="org.mariadb.jdbc.Driver"/>
<property name="url" value="jdbc:mariadb://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="yutong19970820"/>
</bean>
<!--我們知道在Mybatis的所有操作都是基于一個(gè)SqlSession的呈枉,而SqlSession是由SqlSessionFactory來產(chǎn)生
的,SqlSessionFactory又是由SqlSessionFactoryBuilder來生成的埃碱。但是Mybatis-Spring是基于
SqlSessionFactoryBean的猖辫。在使用Mybatis-Spring的時(shí)候,我們也需要SqlSession乃正,而且這個(gè)SqlSession是
內(nèi)嵌在程序中的住册,一般不需要我們直接訪問。SqlSession也是由SqlSessionFactory來產(chǎn)生的瓮具,但是Mybatis
Spring給我們封裝了一個(gè)SqlSessionFactoryBean荧飞,在這個(gè)bean里面還是通過SqlSessionFactoryBuilder來建
立對應(yīng)的SqlSessionFactory凡人,進(jìn)而獲取到對應(yīng)的SqlSession。通過SqlSessionFactoryBean我們可以通過對
其指定一些屬性來提供Mybatis的一些配置信息叹阔。-->
<bean id="sf" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="typeAliasesPackage" value="com.qianfeng.bean" />
<property name="mapperLocations" value="classpath:Mapper/*Mapper.xml" />
<property name="dataSource" ref="ds"></property>
<property name="configLocation" value="classpath:mybatis-config.xml" />
</bean>
<!--Mybatis-Spring為我們提供了一個(gè)叫做MapperScannerConfigurer的類挠轴,通過這個(gè)類
Mybatis-Spring會自動為我們注冊Mapper對應(yīng)的MapperFactoryBean對象。 如果我們
需要使用MapperScannerConfigurer來幫我們自動掃描和注冊Mapper接口的 話我們需要
在Spring的applicationContext配置文件中定義一個(gè)MapperScannerConfigurer對應(yīng)
的bean耳幢。對于MapperScannerConfigurer而言有一個(gè) 屬性是我們必須指定的岸晦,那就是
basePackage。basePackage是用來指定Mapper接口 文件所在的基包的睛藻,在這個(gè)基包或
其所有子包下面的Mapper接口都將被搜索到启上。多個(gè)基 包之間可以使用逗號或者分號進(jìn)行分隔。
最簡單的MapperScannerConfigurer定義就是 只指定一個(gè)basePackage屬性店印。-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 給出需要掃描Dao接口包 -->
<property name="basePackage" value="com.qianfeng.dao" />
<property name="sqlSessionFactoryBeanName" value="sf" />
</bean>
<!-- 配置事務(wù)管理器 -->
<bean id="dtx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="ds"></property>
</bean>
<tx:advice id="tx" transaction-manager="dtx">
<!-- 聲明屬性冈在,聲明事務(wù)的規(guī)則 -->
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception" />
<tx:method name="insert*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception" />
<tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception" />
<tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception" />
</tx:attributes>
</tx:advice>
<!-- 定義切面 -->
<aop:config>
<aop:pointcut id="mpt" expression="execution(* com.qianfeng.service.*.*(..))" />
<aop:advisor advice-ref="tx" pointcut-ref="mpt" />
</aop:config>
</beans>
其中
1、配置druid數(shù)據(jù)源時(shí)按摘,driver的name應(yīng)為driverClassName
2包券、如果想用MySQL數(shù)據(jù)庫,則driverClassName的value改為"com.mysql.jdbc.Driver"炫贤,url改為"jdbc:mysql://localhost:3307/我的數(shù)據(jù)庫名"
3溅固、<property name="mapperLocations" value="classpath:Mapper/Mapper.xml" />應(yīng)填Mapper.xml所在位置。因?yàn)槲业腎DEA版本若將Mapper放在dao下無法掃描到兰珍,因此必須放到resource下
4侍郭、<property name="basePackage" value="com.qianfeng.dao" 給出的是需要掃描的Dao接口包/>
五、在resour目錄下配置mybatis-config.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>
<settings>
<setting name="logImpl" value="LOG4J" />
</settings>
</configuration>
resource下的log4j.properties:
# Global logging configuration
log4j.rootLogger=ERROR, stdout, F
# MyBatis logging configuration...
log4j.logger.com.qfedu.dao=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
log4j.appender.F = org.apache.log4j.DailyRollingFileAppender
log4j.appender.F.File =myproj.log
log4j.appender.F.Append = true
log4j.appender.F.Threshold = DEBUG
log4j.appender.F.layout=org.apache.log4j.PatternLayout
log4j.appender.F.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss}-[%p %F\:%L] %m%n
六俩垃、配置文件結(jié)束励幼,環(huán)境搭建完畢,開始編寫代碼口柳,先是圖書類BookBean類
public class BookBean {
private int id;
private String name;
private double price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("BookBean{");
sb.append("id=").append(id);
sb.append(", name='").append(name).append('\'');
sb.append(", price=").append(price);
sb.append('}');
return sb.toString();
}
}
七苹粟、dao層,BookDao的接口類
public interface BookDao {
List<BookBean> getAllBooks();
}
八跃闹、service層
1嵌削、 注意Service的實(shí)現(xiàn)類之上一定要添加service注解
2、用@Resource(或@Autowired)動態(tài)注入dao組件
/**
* 注意Service的實(shí)現(xiàn)類之上一定要添加service注解
*/
@Service
public class BookService {
/**
* 動態(tài)注入dao組件
*/
@Resource
private BookDao bookDao;
public List<BookBean> getAllBooks(){
return bookDao.getAllBooks();
}
}
九望艺、controller層
1苛秕、Controller 實(shí)現(xiàn)類上要添加注解@RestController(用@RestController無法返回jsp頁面,如果需要返回到指定頁面找默,則需要用 @Controller配合視圖解析器InternalResourceViewResolver才行艇劫。)
2、用@Resource(或@Autowired)動態(tài)注入service組件
@RestController
public class Controller {
@Resource
private BookService bookService;
@RequestMapping("/book")
public List<BookBean> getAllBooks(){
return bookService.getAllBooks();
}
}
十惩激、在resource目錄下新建一個(gè)Mapper文件夾店煞,在里面創(chuàng)建BookMapper.xml
namespace必須是dao接口的全路徑
<?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">
<!--
第二種實(shí)現(xiàn)mybatis的方式為:接口+xml方式
這種方式有特別的要求
1. namespace必須是接口的全路徑
2. 每個(gè)節(jié)點(diǎn)的id必須是接口中的方法名
3. 該接口中的方法不允許重載蟹演,否則namespace+id將不唯一
4. 注意該接口中的增刪改的方法的返回值,最好使用int
-->
<mapper namespace="com.qianfeng.dao.BookDao">
<!--查詢?nèi)繄D書(進(jìn)行展示)-->
<select id="getAllBooks" resultType="com.qianfeng.bean.BookBean">
select * from springmvcbook
</select>
</mapper>