整合ssm框架步驟
阿新 • • 發佈:2018-12-17
整合SSM框架步驟:
結構概況:
一,表與domain實體類的建立:
注意:開發的第一步就是優先去建立資料庫表與實體類,欄位與屬性要對應; 1,表; CREATE DATABASE ssm_db; USE ssm_db; CREATE TABLE account( id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(20), money FLOAT(8,2) ); INSERT INTO account VALUES(NULL,'張三',1000.00); INSERT INTO account VALUES(NULL,'張四',2000.00); INSERT INTO account VALUES(NULL,'張五',3000.00); INSERT INTO account VALUES(NULL,'張六',4000.00); 2,實體類; package com.it.domain; public class Account { private Integer id; private String username; private Float money; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Float getMoney() { return money; } public void setMoney(Float money) { this.money = money; } }
二,Dao層與Service層介面建立:
1,dao層介面: package com.it.dao; import com.it.domain.Account; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import java.util.List; public interface AccountDao { /** * 1,查詢全部 * @return */ @Select("select * from account") public List<Account> queryAll(); /** * 2,根據id查詢; * @return */ @Select("select * from account where id=#{id}") public Account queryById(Integer id); /** * 3,儲存賬戶 * @param account */ @Insert("insert into account values(null,#{username},#{money})") public void insert(Account account); /** * 4,更新 * @param account */ @Update("update account set username=#{username},money=#{money} where id=#{id}") public void update(Account account); /** * 5,根據id刪除 * @param id */ @Delete("delete from account where id=#{id}") public void delete(Integer id); } 2,service層介面: package com.it.service; import com.it.domain.Account; import java.util.List; public interface AccountService { /** * 1,查詢全部 * @return */ public List<Account> queryAll(); /** * 2,根據id查詢; * @return */ public Account queryById(Integer id); /** * 3,儲存賬戶 * @param account */ public void insert(Account account); /** * 4,更新 * @param account */ public void update(Account account); /** * 5,根據id刪除 * @param id */ public void delete(Integer id); }
三,Service層實現類的編寫:
package com.it.service.impl; import com.it.dao.AccountDao; import com.it.domain.Account; import com.it.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 List<Account> queryAll() { return accountDao.queryAll(); } @Override public Account queryById() { return accountDao.queryById(); } @Override public void insert(Account account) { accountDao.insert(account); } @Override public void update(Account account) { accountDao.update(account); } @Override public void delete(Integer id) { accountDao.delete(id); } }
四,spring與mybatis的整合:
c3p0屬性集合建立:
1,jdbc.properties:(c3p0屬性集);
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_db
jdbc.user=root
jdbc.password=root
2,applicatinContext.xml:(把mybatis配置檔案整合至spring配置檔案中);
<!--spring與mybatis的整合 開始-->
<!--1,引入c3p0屬性集-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!--2,配置資料來源-->
<bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource">
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--3,建立sqlSessionFactory,也就是sqlSession的工廠類;sqlSession相當於是connection執行緒不安全;-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sessionFactory">
<!--3,1,配置資料庫的連結的資料來源-->
<property name="dataSource" ref="dataSource"></property>
<!--3.2,也可以在這裡配置其他屬性;-->
</bean>
<!--4,建立AccountDao介面的動態代理物件;-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="mapperScannerConfiguer">
<!--4.1,掃描的包-->
<property name="basePackage" value="com.it.dao"></property>
</bean>
<!--spring與mybatis整合 結束-->
3,spring與mybatis整合需要依賴的jar包:
<!--測試依賴 開始-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--測試依賴 結束-->
<!--spring與mabits整合 開始-->
<!--mybatis 框架核心依賴-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!--mysql 資料庫-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<!--c3p0連線池資料來源-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--spring與mybatis整合依賴-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!--spring 核心依賴-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!--spring jdbcTemplate-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!--spring與mybatis整合 結束-->
五,整合以後測試Dao層介面的query操作:
package com.it;
import com.it.dao.AccountDao;
import com.it.domain.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class SpringDaoTest {
@Autowired
private AccountDao accountDao;
@Test
public void testDao(){
List<Account> accountList = accountDao.queryAll();
for (Account account : accountList) {
System.out.println(account.getUsername());
}
}
}
六,spring業務層配置檔案的配置情況:
1,applicationContext.xml配置(與spring整合mybatis在同一個配置檔案中):
<!--業務層配置檔案 開始-->
<!--1,事務管理器-->
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
<!--1.1 配置事務需要管理的物件-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--2,事務增強-->
<tx:advice transaction-manager="transactionManager" id="txAdvice">
<!--2.1 配置哪些方法需要事務增強-->
<tx:attributes>
<tx:method name="query*" read-only="true"/>
<tx:method name="*"></tx:method>
</tx:attributes>
</tx:advice>
<!--3,aop 管理事務-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.it.service..*.*(..))"></aop:advisor>
</aop:config>
<!--4,開啟註解掃描包,建立自動注入的物件-->
<context:component-scan base-package="com.it.service.impl"></context:component-scan>
<!--業務層配置檔案 結束-->
<!--攔截器配置 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.it.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
<!--建立攔截器物件-->
<bean class="com.it.interceptor.LoginInterceptor" id="interceptor"></bean>
2,該service配置aop需要引入的jar包依賴:
<!--service業務層 開始-->
<!--aop 切面程式設計-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
<!--spring tx事務-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!--service業務層 結束-->
七,測試業務層service的query操作:
package com.it;
import com.it.domain.Account;
import com.it.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class SpringServiceTest {
@Autowired
private AccountService accountService;
@Test
public void testService(){
List<Account> accountList = accountService.queryAll();
for (Account account : accountList) {
System.out.println(account.getUsername());
}
}
}
八,spring與spring MVC整合:
1,springMVCConfig.xml:
<!--spring mvc 開始-->
<!--1,開啟註解掃描包,建立物件;-->
<context:component-scan base-package="com.it.controller"></context:component-scan>
<!--2,配置檢視解析器;-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="resourceViewResolver">
<!--2,1 解析檢視頁面的字首後後綴;-->
<property name="prefix" value="/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--3,註冊註解驅動;-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--4,對靜態資源放行-->
<mvc:default-servlet-handler></mvc:default-servlet-handler>
<!--spring mvc 結束-->
2,web.xml:
<!--web.xml 開始-->
<!--1,配置全域性引數,匯入spring 核心配置檔案;-->
<context-param>
<!--如果不配置,他預設會去查詢的位置:/WEB-INF/applicationContext.xml-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--2,配置編碼過濾器;-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!--2.2 配置編碼過濾器的過濾的引數-->
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<!--2.1 配置編碼過濾器的對映-->
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--3,配置spring監聽器,建立spring ioc容器,建立或銷燬容器物件;-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--3,配置前端控制器;-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--3.2 配置前端控制器需要攔截的mvc配置檔案,不配置預設查詢的位置:/WEB-INF/dispatcher-servlet.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVCConfig.xml</param-value>
</init-param>
</servlet>
<!--3.1 前端控制器的對映-->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--web.xml 結束-->
九,controller包下的類的建立:
1,自定義處理器AccountController類的建立:
package com.it.controller;
import com.it.domain.Account;
import com.it.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
/**
* 查詢使用者
* @return ModelAndView :返回資料時,需要該物件;
*/
@RequestMapping("/findAll")
public ModelAndView findAll(){
List<Account> accountList = accountService.queryAll();
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("accountList",accountList);
modelAndView.setViewName("show");
return modelAndView;
}
@RequestMapping("/insert")
public String insert(Account account){
accountService.insert(account);
/**
* 這裡需要用到請求轉發:一次請求,伺服器內部自己做方法處理;
* redirect:轉發的方法
*/
return "redirect:findAll";
}
/**
* 修改的操作剖析:
* 1,根據id查詢account;
* 2,把查到的account封裝到ModelAndView 模型中在新頁面展示;
* 3,把資料更新到資料庫中;
* @param id
* @return ModelAndView :修改後的資料展示需要一個帶有資料的模型檢視物件;
*/
@RequestMapping("/updateUI")
public ModelAndView updateUI(Integer id){
Account account = accountService.queryById(id);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("account",account);
modelAndView.setViewName("accountUpdate");
return modelAndView;
}
/**
* 把更新的資料回顯至首頁
* @param account
* @return 頁面
*/
@RequestMapping("/update")
public String update(Account account){
accountService.update(account);
return "redirect:findAll";
}
/**
* 刪除
* @param id
* @return 返回頁面;
*/
@RequestMapping("/delete")
public String delete(Integer id){
accountService.delete(id);
return "redirect:findAll";
}
}
2,自定義處理器LoginController類的建立:
package com.it.controller;
import com.it.domain.Account;
import com.it.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
/**
* 查詢使用者
* @return ModelAndView :返回資料時,需要該物件;
*/
@RequestMapping("/findAll")
public ModelAndView findAll(){
List<Account> accountList = accountService.queryAll();
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("accountList",accountList);
modelAndView.setViewName("show");
return modelAndView;
}
@RequestMapping("/insert")
public String insert(Account account){
accountService.insert(account);
/**
* 這裡需要用到請求轉發:一次請求,伺服器內部自己做方法處理;
* redirect:轉發的方法
*/
return "redirect:findAll";
}
/**
* 修改的操作剖析:
* 1,根據id查詢account;
* 2,把查到的account封裝到ModelAndView 模型中在新頁面展示;
* 3,把資料更新到資料庫中;
* @param id
* @return ModelAndView :修改後的資料展示需要一個帶有資料的模型檢視物件;
*/
@RequestMapping("/updateUI")
public ModelAndView updateUI(Integer id){
Account account = accountService.queryById(id);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("account",account);
modelAndView.setViewName("accountUpdate");
return modelAndView;
}
/**
* 把更新的資料回顯至首頁
* @param account
* @return 頁面
*/
@RequestMapping("/update")
public String update(Account account){
accountService.update(account);
return "redirect:findAll";
}
/**
* 刪除
* @param id
* @return 返回頁面;
*/
@RequestMapping("/delete")
public String delete(Integer id){
accountService.delete(id);
return "redirect:findAll";
}
}
十,頁面的建立:
1,show.jsp展示頁面:
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2018\10\24 0024
Time: 9:32
To change this template use File | Settings | File Templates.
--%>
<%@ page isELIgnored="false" contentType="text/html;charset=UTF-8" language="java" %>
<%--匯入jstl的核心庫--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
<%--匯入CSS樣式--%>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/bootstrap.min.css" >
</head>
<body>
<%--${accountList}--%>
<%--建立樣式表格,填充後端資料;--%>
<table class="table table-striped">
<caption>
歡迎光臨,王者農藥<a href="${pageContext.request.contextPath}/pages/acccountAdd.jsp" class="btn btn-default btn-sm">新增英雄</a>
</caption>
<thead>
<tr>
<th>id</th>
<th>英雄</th>
<th>金幣</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach items="${accountList}" var="account">
<tr>
<td>${account.id}</td>
<td>${account.username}</td>
<td>${account.money}</td>
<td>
<a href="${pageContext.request.contextPath}/account/updateUI?id=${account.id}"
class="btn btn-default btn-sm">修改</a>
<a href="${pageContext.request.contextPath}/account/delete?id=${account.id}"
class="btn btn-default btn-sm" onclick="return del()">刪除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
<script type="text/javascript">
function del() {
if (confirm("召喚師,您確定要刪除該英雄嗎?")){
return true;
}else {
return false;
}
}
</script>
<%--匯入js檔案--%>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/bootstrap.min.js"></script>
</html>
2,accountAdd,jsp新增資料的頁面:
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2018\10\24 0024
Time: 10:22
To change this template use File | Settings | File Templates.
--%>
<%@ page isELIgnored="false" contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
<%--引入CSS樣式--%>
<link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<%--建立賬戶需要一個表單去提交--%>
<form class="form-horizontal" role="form" action="${pageContext.request.contextPath}/account/insert" method="post">
<div class="form-group">
<label for="firstname" class="col-sm-2 control-label">英雄</label>
<div class="col-sm-10">
<input type="text" name="username" class="form-control" id="firstname"
placeholder="請輸入英雄名">
</div>
</div>
<div class="form-group">
<label for="lastname" class="col-sm-2 control-label">金幣</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="lastname" name="money"
placeholder="請輸入金幣">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">新增英雄</button>
</div>
</div></form>
</body>
<%--引入js檔案--%>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/bootstrap.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.9.1.js"></script>
</html>
3,accountUpdate.jsp更改資料的頁面:
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2018\10\24 0024
Time: 11:25
To change this template use File | Settings | File Templates.
--%>
<%@ page isELIgnored="false" contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
<%--匯入CSS樣式--%>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/bootstrap.min.css">
</head>
<body>
<%--建立賬戶需要一個表單去提交--%>
<form class="form-horizontal" role="form" action="${pageContext.request.contextPath}/account/update" method="post">
<%--這裡需要一個id的屬性,基本上都是使用隱藏域--%>
<input type="hidden" name="id" value="${account.id}">
<div class="form-group">
<label for="firstname" class="col-sm-2 control-label">英雄</label>
<div class="col-sm-10">
<input type="text" name="username" class="form-control" id="firstname"
value="${account.username}" placeholder="請輸入英雄名">
</div>
</div>
<div class="form-group">
<label for="lastname" class="col-sm-2 control-label">金幣</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="lastname" name="money"
value="${account.money}" placeholder="請輸入金額">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">更新英雄</button>
</div>
</div></form>
</body>
<%--匯入js檔案--%>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/bootstrap.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.9.1.js"></script>
</html>
4,login.jsp登入頁面:
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2018\10\25 0025
Time: 10:13
To change this template use File | Settings | File Templates.
--%>
<%@ page isELIgnored="false" contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>登入</title>
<%--匯入css樣式--%>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/bootstrap.min.css">
</head>
<body>
<%--建立賬戶需要一個表單去登入--%>
<form class="form-horizontal" role="form" action="${pageContext.request.contextPath}/loginUser" method="post">
<div class="form-group">
<label for="firstname" class="col-sm-2 control-label">使用者名稱</label>
<div class="col-sm-10">
<input type="text" name="username" class="form-control" id="firstname"
placeholder="請輸入使用者名稱">
</div>
</div>
<div class="form-group">
<label for="lastname" class="col-sm-2 control-label">密碼</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="lastname" name="password"
placeholder="請輸入密碼">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">登入</button>
</div>
</div>
</form>
</body>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/bootstrap.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.9.1.js"></script>
</html>
十一,生成頁面:
query:
insert:
update:
delete:
login: