SpringMVC整合SSM實現(xiàn)表現(xiàn)層數(shù)據(jù)封裝詳解
SSM整合配置
SSM整合流程
1.創(chuàng)建工程
2.SSM整合
Spring
- SpringConfig
MyBatis
- MybatisConfig
- JdbcConfig
- jdbc.properties
SpringMVC
- ServletConfig
- SpringMvcConfig
3.功能模塊
表與實體類
dao(接口+自動代理)
service(接口+實現(xiàn)類)
- 業(yè)務(wù)層接口測試(整合JUnit)
controller
- 表現(xiàn)層接口測試(PostMan)
SSM整合配置
創(chuàng)建工程,添加依賴和插件
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<port>80</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>Spring整合Mybatis
創(chuàng)建數(shù)據(jù)庫和表
-- 創(chuàng)建db5數(shù)據(jù)庫
CREATE DATABASE IF NOT EXISTS db5 CHARACTER SET utf8;
-- 使用db5數(shù)據(jù)庫
USE db5;
-- 創(chuàng)建tbl_book表
CREATE TABLE tbl_book(
id INT PRIMARY KEY AUTO_INCREMENT, -- 圖書編號
TYPE VARCHAR(100), -- 圖書類型
NAME VARCHAR(100), -- 圖書名稱
description VARCHAR(100) -- 圖書描述
);
-- 添加初始化數(shù)據(jù)
INSERT INTO tbl_book VALUES(NULL,'圖書類型一','圖書名稱一','圖書描述一');
INSERT INTO tbl_book VALUES(NULL,'圖書類型二','圖書名稱二','圖書描述二');
INSERT INTO tbl_book VALUES(NULL,'圖書類型三','圖書名稱三','圖書描述三');
INSERT INTO tbl_book VALUES(NULL,'圖書類型四','圖書名稱四','圖書描述四');
INSERT INTO tbl_book VALUES(NULL,'圖書類型五','圖書名稱五','圖書描述五');
INSERT INTO tbl_book VALUES(NULL,'圖書類型六','圖書名稱六','圖書描述六');jdbc.properties屬性文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db5
jdbc.username=root
jdbc.password=123456
JdbcConfig配置類
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
//配置連接池
@Bean
public DataSource dataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
//Spring事務(wù)管理需要的平臺事務(wù)管理器對象
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource){
DataSourceTransactionManager ds = new DataSourceTransactionManager();
ds.setDataSource(dataSource);
return ds;
}
}MybatisConfig配置類
public class MyBatisConfig {
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setTypeAliasesPackage("com.moming.domain");
return factoryBean;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("com.moming.dao");
return msc;
}
}SpringConfig配置類
@Configuration
@ComponentScan({"com.moming.service"})
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MyBatisConfig.class})
@EnableTransactionManagement //開啟Spring事務(wù)管理
public class SpringConfig {
}Spring整合SpringMVC
SpringMvcConfig配置類
@Configuration
@ComponentScan("com.moming.controller")
@EnableWebMvc
public class SpringMvcConfig {
}ServletConfig配置類,加載SpringMvcConfig和SpringConfig配置類
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
protected String[] getServletMappings() {
return new String[]{"/"};
}
//亂碼處理
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
return new Filter[]{filter};
}
}功能模塊開發(fā)
數(shù)據(jù)層開發(fā)(BookDao)
Book實體類
@Data
public class Book {
private Integer id;
private String type;
private String name;
private String description;
}BookDao接口
public interface BookDao {
//@Insert("insert into tbl_book values(null,#{type},#{name},#{description})")
@Insert("insert into tbl_book (type,name,description) values(#{type},#{name},#{description})")
public int save(Book book); //返回值表示影響的行數(shù)
@Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")
public int update(Book book);
@Delete("delete from tbl_book where id = #{id}")
public int delete(Integer id);
@Select("select * from tbl_book where id = #{id}")
public Book getById(Integer id);
@Select("select * from tbl_book")
public List<Book> getAll();
}業(yè)務(wù)層開發(fā)(BookService/BookServiceImpl)
BookService接口
@Transactional //表示所有方法進行事務(wù)管理
public interface BookService {
/**
* 保存
* @param book
* @return
*/
public boolean save(Book book);
/**
* 修改
* @param book
* @return
*/
public boolean update(Book book);
/**
* 根據(jù)id刪除
* @param id
* @return
*/
public boolean delete(Integer id);
/**
* 按id查詢
* @param id
* @return
*/
public Book getById(Integer id);
/**
* 查詢?nèi)?
* @return
*/
public List<Book> getAll();
}BookServiceImpl實現(xiàn)類
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
public boolean save(Book book) {
bookDao.save(book);
return true;
}
public boolean update(Book book) {
bookDao.update(book);
return true;
}
public boolean delete(Integer id) {
bookDao.delete(id);
return true;
}
public Book getById(Integer id) {
return bookDao.getById(id);
}
public List<Book> getAll() {
return bookDao.getAll();
}
}表現(xiàn)層開發(fā)(BookController)
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private BookService bookService;
@PostMapping
public boolean save(@RequestBody Book book) {
return bookService.save(book);
}
@PutMapping
public boolean update(@RequestBody Book book) {
return bookService.update(book);
}
@DeleteMapping("/{id}")
public boolean delete(@PathVariable Integer id) {
return bookService.delete(id);
}
@GetMapping("/{id}")
public Book getById(@PathVariable Integer id) {
return bookService.getById(id);
}
@GetMapping
public List<Book> getAll() {
return bookService.getAll();
}
}接口測試
Spring整合Junit測試業(yè)務(wù)層方法
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class BookServiceTest {
@Autowired
private BookService bookService;
@Test
public void testGetById(){
Book book = bookService.getById(1);
System.out.println(book);
}
@Test
public void testGetAll(){
List<Book> all = bookService.getAll();
System.out.println(all);
}
}
postman測試表現(xiàn)層接口
測試保存圖書


表現(xiàn)層數(shù)據(jù)封裝(前后端通信協(xié)議)
表現(xiàn)層響應(yīng)數(shù)據(jù)的問題
問題:我們表現(xiàn)層增刪改方法返回true或者false表示是否成功,getById()方法返回一個json對象,getAll()方法返回一個json對象數(shù)組,這里就出現(xiàn)了三種格式的響應(yīng)結(jié)果,極其不利于前端解析。

解決:我們需要統(tǒng)一響應(yīng)結(jié)果的格式

定義Result類封裝響應(yīng)結(jié)果
controller/Result類封裝響應(yīng)結(jié)果
@Data
public class Result {
//描述統(tǒng)一格式中的數(shù)據(jù)
private Object data;
//描述統(tǒng)一格式中的編碼,用于區(qū)分操作,可以簡化配置0或1表示成功失敗
private Integer code;
//描述統(tǒng)一格式中的消息,可選屬性
private String msg;
public Result() {
}
public Result(Integer code,Object data) {
this.data = data;
this.code = code;
}
public Result(Integer code, Object data, String msg) {
this.data = data;
this.code = code;
this.msg = msg;
}
}注意事項:Result類中的字段并不是固定的,可以根據(jù)需要自行增減
controller/Code類封裝響應(yīng)碼
//狀態(tài)碼
public class Code {
public static final Integer SAVE_OK = 20011;
public static final Integer DELETE_OK = 20021;
public static final Integer UPDATE_OK = 20031;
public static final Integer GET_OK = 20041;
public static final Integer SAVE_ERR = 20010;
public static final Integer DELETE_ERR = 20020;
public static final Integer UPDATE_ERR = 20030;
public static final Integer GET_ERR = 20040;
}注意事項:Code類的常量設(shè)計也不是固定的,可以根據(jù)需要自行增減,例如將查詢再進行細分為GET_OK,GET_ALL_OK,GET_PAGE_OK
表現(xiàn)層數(shù)據(jù)封裝返回Result對象
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private BookService bookService;
@PostMapping
public Result save(@RequestBody Book book) {
boolean flag = bookService.save(book);
return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR,flag);
}
@PutMapping
public Result update(@RequestBody Book book) {
boolean flag = bookService.update(book);
return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR,flag);
}
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id) {
boolean flag = bookService.delete(id);
return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERR,flag);
}
@GetMapping("/{id}")
public Result getById(@PathVariable Integer id) {
Book book = bookService.getById(id);
Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
String msg = book != null ? "" : "數(shù)據(jù)查詢失敗,請重試!";
return new Result(code,book,msg);
}
@GetMapping
public Result getAll() {
List<Book> bookList = bookService.getAll();
Integer code = bookList != null ? Code.GET_OK : Code.GET_ERR;
String msg = bookList != null ? "" : "數(shù)據(jù)查詢失敗,請重試!";
return new Result(code,bookList,msg);
}
}Postman測試


到此這篇關(guān)于SpringMVC整合SSM實現(xiàn)表現(xiàn)層數(shù)據(jù)封裝詳解的文章就介紹到這了,更多相關(guān)SpringMVC表現(xiàn)層數(shù)據(jù)封裝內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java實現(xiàn)curl調(diào)用帶參數(shù)接口方法
本文主要介紹了Java實現(xiàn)curl調(diào)用帶參數(shù)接口方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-04-04
SpringBoot構(gòu)建Restful service完成Get和Post請求
這篇文章主要介紹了SpringBoot構(gòu)建Restful service完成Get和Post請求的示例代碼,感興趣的朋友一起看看吧2017-08-08
Java數(shù)據(jù)結(jié)構(gòu)學(xué)習(xí)之棧和隊列
這篇文章主要介紹了Java數(shù)據(jù)結(jié)構(gòu)學(xué)習(xí)之棧和隊列,文中有非常詳細的代碼示例,對正在學(xué)習(xí)java的小伙伴們有一定的幫助,需要的朋友可以參考下2021-05-05

