SpringMVC學(xué)習(xí)筆記(三)
ssm框架整合
使用Intelij Idear 進(jìn)行ssm整合思恐,javaweb項目通常采用三層架構(gòu)挡育,表現(xiàn)層、業(yè)務(wù)層蚪腋、持久層,表現(xiàn)層對應(yīng)的式SpringMVC框架姨蟋、業(yè)務(wù)層對應(yīng)的是Spring框架屉凯、持久層對應(yīng)的是Mybatis框架。而業(yè)務(wù)層Spring框架是表現(xiàn)層和持久層中間不可缺少眼溶,所以通常是spring和springmvc整合悠砚,spring和mybatis整合。
整合我們可以使用xml的方式堂飞,也可以使用注解的方式灌旧。
整合思路
- 先搭建整合的環(huán)境
- 先把Spring的配置搭建完成
- 再使用Spring整合SpringMVC框架 4. 最后使用Spring整合MyBatis框架
一绑咱、Spring整合
1、創(chuàng)建工程枢泰,選擇maven的webapp工程
2描融、創(chuàng)建包結(jié)構(gòu)
- 在src目錄下分別創(chuàng)建
java
和resource
兩個包,分別設(shè)置成根目錄衡蚂。
image - 在java目錄下我們根據(jù)三層架構(gòu)創(chuàng)建包
domain
包下通常是實體類窿克、javabean等
dao
包下是實體類的接口,通常是我們對SQL語句處理
service
包下是業(yè)務(wù)處理相關(guān),包含接口和實現(xiàn)類毛甲,通常和業(yè)務(wù)邏輯相關(guān)
controller
包下是前端控制器年叮,處理請求和頁面跳轉(zhuǎn)。
test
包下通常是我們的單元測試類 - 創(chuàng)建一個
Account
類
public class Account implements Serializable {
private Integer id;
private String name;
private double 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;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
- 在
dao
包下創(chuàng)建account接口玻募,創(chuàng)建findAll()
和saveAccount
方法
public interface AccountDao {
//查詢所有
public List<Account> findAll();
//保存賬戶
public void saveAccount(Account account);
}
- 在
service
包下創(chuàng)建AccountService
接口只损,和impl.AccountServiceImpl
實現(xiàn)類
public interface AccountService {
//查詢所有
public List<Account> findAll();
//保存賬戶
public void saveAccount(Account account);
}
public class AccountServiceImpl implements AccountService {
@Override
public List<Account> findAll() {
System.out.println("業(yè)務(wù)層:查詢所有賬戶");
return null;
}
@Override
public void saveAccount(Account account) {
System.out.println("業(yè)務(wù)層:保存賬戶");
accountDao.saveAccount(account);
}
}
- 在
controller
包下創(chuàng)建AccountController
類
3、在resource資源包下补箍,我們創(chuàng)建spring的配置文件,取名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中業(yè)務(wù)層中由于使用注解開發(fā)改执,所以我們需要開啟注解掃描,由于我們只希望處理service和dao,而Controller有SpringMVC框架幫我們處理坑雅,所以這里我們可以將Controller的注解過濾掉辈挂。
<!-- 開啟注解掃描,希望處理service和dao,controller不需要處理 -->
<context:component-scan base-package="com.fanyang">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
Spring框架這一步完成
二裹粤、springmvc框架整合
1终蒂、首先我們需要在web.xml
中配置servlet前端控制器,在初始化中加載在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:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</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>
- 2遥诉、由于初始化加載了springmvc.xml文件拇泣,所以我們在
resource
目錄下創(chuàng)建springmvc框架的配置文件:
設(shè)置約束
<?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">
開啟注解的掃面,只需要掃面Controller注解,代碼如下:
<!-- 開啟注解掃描矮锈,只掃描Controller注解 -->
<context:component-scan base-package="com.fanyang">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 開啟SpringMVC注解的支持 -->
<mvc:annotation-driven></mvc:annotation-driven>
配置視圖解析器
<!-- 配置視圖解析器對象 -->
<bean id="internalResourceViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
過濾靜態(tài)資源霉翔,由于Servlet會攔截所有的資源文件,所以在頁面加載過程中需要過濾靜態(tài)資源
<!-- 過濾靜態(tài)資源 -->
<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
<mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
如何整合Spring和SpringMVC
我們在Controller中由于使用到了service層處理的數(shù)據(jù)苞笨,但是我們的applictionContext.xml
文件并沒有隨著我們的服務(wù)器啟動而加載债朵,所以我們唯一要做的是,需要在服務(wù)啟動后瀑凝,我們的spring配置文件能夠加載序芦,這里就用到了spring-web
這個jar包。
我們在啟動tomcat
服務(wù)器時粤咪,會創(chuàng)建一個ServletContext的唯一的域?qū)ο笱柚校@個對象隨著服務(wù)器開啟創(chuàng)建,隨著服務(wù)器關(guān)閉消失,這一過程都是有一個監(jiān)聽器在操作宪塔,監(jiān)聽ServletContext域?qū)ο髣?chuàng)建和銷毀磁奖。所以我們可以使用監(jiān)聽器去加載Spring配置文件。
<!-- 配置Spring的監(jiān)聽器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
三蝌麸、Mybatis配置
我們使用注解的方式配置Mybatis点寥,在到dao接口方法中進(jìn)行sql語句處理,查詢和保存操作艾疟!
//查詢所有
@Select("select * from account")
public List<Account> findAll();
//保存賬戶
@Insert("insert into account(name,money) values(#{name},#{money})")
public void saveAccount(Account account);
在service
包下来吩,進(jìn)行業(yè)務(wù)處理相關(guān)代碼
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public List<Account> findAll() {
System.out.println("業(yè)務(wù)層:查詢所有賬戶");
List<Account> accounts = accountDao.findAll();
for (Account account : accounts) {
System.out.println(account);
}
return accounts;
}
@Override
public void saveAccount(Account account) {
System.out.println("業(yè)務(wù)層:保存賬戶");
accountDao.saveAccount(account);
}
}
controller
包下進(jìn)行頁面控制
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/findAll")
public String findAll(Model model){
//調(diào)用業(yè)務(wù)層方法
List<Account> list = accountService.findAll();
model.addAttribute("list",list);
return "success";
}
@RequestMapping("/save")
public void save(Account account, HttpServletRequest request,
HttpServletResponse response) throws Exception {
accountService.saveAccount(account);
response.sendRedirect(request.getContextPath()+"/account/findAll");
}
這里基本代碼寫完,如何進(jìn)行spring和mybatis的整合
在applicationContext.xml
中進(jìn)行配置
- 配置數(shù)據(jù)庫連接池:
<!-- 配置連接池 -->
<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/ssm?characterEncoding=utf8"/>
<property name="user" value="root"/>
<property name="password" value="1234"/>
</bean>
- 配置SqlSessionFactory,這里使用注解方式
<!-- 配置SqlSessionFactory工程 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
</bean>
- 掃描dao包蔽莱,添加映射文件
<bean id="mapperScanner"
class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.fanyang.dao"></property>
</bean>
- 配置事務(wù)相關(guān)
<!-- 配置Spring框架聲明式事務(wù)管理 -->
<!-- 配置事務(wù)管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事務(wù)通知-->
<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增強(qiáng) -->
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* com.fanyang.service.impl.*ServiceImpl.*(..))" />
</aop:config>
mybatis和spring的整合完成