一、搭建整合環境
整合說明:SSM整合可以使用多種方式,咱們會選擇XML + 註解的方式
整合的思路:
- 先搭建整合的環境
- 先把Spring的配置搭建完成
- 再使用Spring整合SpringMVC框架
- 最後使用Spring整合MyBatis框架
每一個環境搭建好之後,需要單獨測試下,通過後,再進行下一步操作。
所以整個過程重要的是靠 Spring 整合兩者,將三者關聯起來
二、搭建Spring框架
保證 Spring 框架在 web 工程中獨立運行
(1)編寫 spring 配置文件 applicationContext.xml
,編寫具體的配置信息
(2)編寫測試方法,進行測試
@Test
public void run1(){
//1.加載配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
//2.獲取對象
AccountService as = (AccountService) ac.getBean("accountService");
//3.調用方法
as.findAll();
}
三、搭建SpringMVC框架
(1)在web.xml
中配置DispatcherServlet前端控制器
(2)在web.xml
中配置DispatcherServlet過濾器解決中文亂碼
(3)創建springmvc.xml
的配置文件,編寫配置文件
(4)測試SpringMVC的框架搭建是否成功
編寫index.jsp和list.jsp編寫,超鏈接
創建AccountController類,編寫方法,進行測試
四、Spring整合SpringMVC框架
(1)目的:在 controller 中能成功的調用 service 對象中的方法
(2)在項目啓動的時候,就去加載applicationContext.xml
的配置文件,在web.xml
中配置
ContextLoaderListener監聽器(該監聽器只能加載 WEB-INF 目錄下的applicationContext.xml
的配置文件)
爲了保證配置文件都在 resources下方便管理,這裏還需另外配置文件的路徑
<!--配置Spring的監聽器,默認只加載WEB-INF目錄下的applicationContext.xml配置文件-->
<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>
(3)在controller中注入service對象,調用service對象的方法進行測試
五、搭建 MyBatis 的環境並整合到 spring 中
(1)在 web 項目中編寫SqlMapConfig.xml
的配置文件,編寫核心配置文件
(2)在 AccountDao 接口的方法上添加註解,編寫SQL語句
(3)把SqlMapConfig.xml
配置文件中的內容配置到applicationContext.xml
配置文件中
(4)配置 Spring 的聲明式事務管理
六、代碼文件
(1)AccountServiceImpl.java
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public List<Account> findAll() {
System.out.println("業務層:查詢所有賬戶...");
return accountDao.findAll();
}
@Override
public void saveAccount(Account account) {
System.out.println("業務層:保存帳戶...");
accountDao.saveAccount(account);
}
}
(2)AccountDao.java
/**
* 帳戶dao接口
*/
@Repository
public interface AccountDao {
/**
* 查詢所有賬戶
* @return
*/
@Select("select * from account")
public List<Account> findAll();
/**
* 保存賬戶信息
* @param account
*/
@Insert("insert into account(id,name,money)values(#{id},#{name},#{money})")
public void saveAccount(Account account);
}
(3)AccountController.java
/**
* 賬戶控制層
*/
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/findAll")
public String findAll(Model model){
System.out.println("表現層:查詢所有賬戶");
List<Account> list = accountService.findAll();
model.addAttribute("list",list);
return "list";
}
@RequestMapping("/save")
public String save(Account account){
System.out.println("表現層:保存賬戶");
accountService.saveAccount(account);
//保存之後重定向到查詢方法
return "redirect:/account/findAll";
}
}