目录
准备数据库表:
-- auto-generated definition
CREATE TABLE tbl_book
(
id INT AUTO_INCREMENT
PRIMARY KEY,
type VARCHAR(20) NULL,
name VARCHAR(50) NULL,
description VARCHAR(255) NULL
)
ENGINE = InnoDB
CHARSET = utf8;
1.框架整合
1.1导坐标
<dependencies>
<!--spring-->
<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>
<scope>test</scope>
</dependency>
<!--spring整合mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</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>8.0.21</version>
</dependency>
<!--数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!--springMVC容器使用-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--json-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
1.2准备配置文件jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_db?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
jdbc.username=root
jdbc.password=1234
1.3配置类整合框架
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 druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(driver);
druidDataSource.setUrl(url);
druidDataSource.setUsername(username);
druidDataSource.setPassword(password);
return druidDataSource;
}
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource) {
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
}
}
public class MybatisConfig {
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setTypeAliasesPackage("com.pojo");
return sqlSessionFactoryBean;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.dao");
return mapperScannerConfigurer;
}
}
public class ServletCongif extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
@Configuration
@ComponentScan("com.service")
@PropertySource("classpath:jdbc.properties")
//@PropertySource("jdbc.properties")
@Import({JdbcConfig.class, MybatisConfig.class})
@EnableTransactionManagement//事务
public class SpringConfig {
}
@Configuration
@ComponentScan("com.controller")
@EnableWebMvc
public class SpringMvcConfig {
}
1.4开启事务
@Transactional
public interface BookService {
public boolean add(Book book);
public boolean update(Book book);
public boolean delete(Integer id);
public Book getById(Integer id);
public List<Book> getAll();
}
2.业务层
2.1 pojo
public class Book {
private Integer id;
private String type;
private String name;
private String description;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", type='" + type + '\'' +
", name='" + name + '\'' +
", description='" + description + '\'' +
'}';
}
}
2.2 dao
public interface BookDao {
@Insert("insert into tbl_book values(null,#{type},#{name},#{description})")
public int add(Book book);//返回行计数
@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();
}
2.3service
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
@Override
public boolean add(Book book) {
int add = bookDao.add(book);
return add > 0;
}
@Override
public boolean update(Book book) {
int update = bookDao.update(book);
return update > 0;
}
@Override
public boolean delete(Integer id) {
int delete = bookDao.delete(id);
return delete > 0;
}
@Override
public Book getById(Integer id) {
return bookDao.getById(id);
}
@Override
public List<Book> getAll() {
return bookDao.getAll();
}
}
2.4业务层测试
@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);
}
}
3.表现层
3.1数据封装
public class Result {
private Integer code;
private Object data;
private String message;
public Result() {
}
public Result(Integer code, Object data, String massage) {
this.data = data;
this.code = code;
this.message = massage;
}
public Result(Integer code, Object data) {
this.data = data;
this.code = code;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String massage) {
this.message = massage;
}
}
public class Code {
public static final Integer ADD_OK = 20011;
public static final Integer DELETE_0K = 20021;
public static final Integer UPDATE_OK = 20031;
public static final Integer GET_OK = 20041;
public static final Integer ADD_ERR = 20010;
public static final Integer DELETE_ERR = 20020;
public static final Integer UPDATE_ERR = 20030;
public static final Integer GET_ERR = 20048;
}
3.2controller
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private BookService bookService;
@PostMapping
public Result add(@RequestBody Book book) {
boolean flag = bookService.add(book);
return new Result(flag ? Code.ADD_OK : Code.ADD_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_0K : 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 massage = book != null ? "" : "数据查询失败,请重试";
return new Result(code, book, massage);
}
@GetMapping
public Result getAll() {
List<Book> list = bookService.getAll();
Integer code = list != null ? Code.GET_OK : Code.GET_ERR;
String massage = list != null ? "" : "数据查询失败,请重试";
return new Result(code, list, massage);
}
}
3.3异常处理
public class BusinessException extends RuntimeException {
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public BusinessException(Integer code, String message) {
super(message);
this.code = code;
}
public BusinessException(Integer code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
}
public class SystemException extends RuntimeException {
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public SystemException(Integer code, String message) {
super(message);
this.code = code;
}
public SystemException(Integer code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
}
@RestControllerAdvice
public class ProjectExceptionAdvice {
//系统异常处理
@ExceptionHandler(SystemException.class)//定义处理哪一种异常
public Result doSystemException(SystemException ex) {
//记录日志
//发送消息给运维
//发送邮件给开发人员
return new Result(ex.getCode(), null, ex.getMessage());
}
//业务异常处理
@ExceptionHandler(BusinessException.class)//定义处理哪一种异常
public Result doBusinessException(BusinessException ex) {
return new Result(ex.getCode(), null, ex.getMessage());
}
//其他异常处理
@ExceptionHandler(Exception.class)//定义处理哪一种异常
public Result doException(BusinessException ex) {
//记录日志
//发送消息给运维
//发送邮件给开发人员
return new Result(Code.SYSTEM_UNKNOWN_ERR, null, "系统繁忙,请稍后再试");
}
}
public class Code {
public static final Integer SYSTEM_ERR = 50001;
public static final Integer SYSTEM_TIMEOUT_ERR = 50002;
public static final Integer SYSTEM_UNKNOWN_ERR = 59999;
public static final Integer BUSINESS_ERR = 60002;
}
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
@Override
public boolean add(Book book) {
try {
int add = bookDao.add(book);
return add > 0;
} catch (Exception e) {
throw new SystemException(Code.SYSTEM_TIMEOUT_ERR, "服务器异常", e);
}
}
@Override
public boolean update(Book book) {
try {
int update = bookDao.update(book);
return update > 0;
} catch (Exception e) {
throw new SystemException(Code.SYSTEM_TIMEOUT_ERR, "服务器异常", e);
}
}
@Override
public boolean delete(Integer id) {
if (id <= 0) {
throw new BusinessException(Code.BUSINESS_ERR, "无效的id");
}
try {
int delete = bookDao.delete(id);
return delete > 0;
} catch (Exception e) {
throw new SystemException(Code.SYSTEM_TIMEOUT_ERR, "服务器异常", e);
}
}
@Override
public Book getById(Integer id) {
if (id <= 0) {
throw new BusinessException(Code.BUSINESS_ERR, "无效的id");
}
try {
return bookDao.getById(id);
} catch (Exception e) {
throw new SystemException(Code.SYSTEM_TIMEOUT_ERR, "服务器异常", e);
}
}
@Override
public List<Book> getAll() {
try {
return bookDao.getAll();
} catch (Exception e) {
throw new SystemException(Code.SYSTEM_TIMEOUT_ERR, "服务器异常", e);
}
}
}
4.前后台联合
4.1静态资源放行
//静态资源放行
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
}
}
@Configuration
@ComponentScan({"com.controller","com.config"})
@EnableWebMvc
public class SpringMvcConfig {
}
4.2前后台联合
<!DOCTYPE html>
<html>
<head>
<!-- 页面meta -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>SpringMVC案例</title>
<meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
<!-- 引入样式 -->
<link rel="stylesheet" href="../plugins/elementui/index.css">
<link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="../css/style.css">
</head>
<body class="hold-transition">
<div id="app">
<div class="content-header">
<h1>图书管理</h1>
</div>
<div class="app-container">
<div class="box">
<div class="filter-container">
<el-input placeholder="图书名称" v-model="pagination.queryString" style="width: 200px;"
class="filter-item"></el-input>
<el-button @click="getAll()" class="dalfBut">查询</el-button>
<el-button type="primary" class="butT" @click="handleCreate()">新建</el-button>
</div>
<el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row>
<el-table-column type="index" align="center" label="序号"></el-table-column>
<el-table-column prop="type" label="图书类别" align="center"></el-table-column>
<el-table-column prop="name" label="图书名称" align="center"></el-table-column>
<el-table-column prop="description" label="描述" align="center"></el-table-column>
<el-table-column label="操作" align="center">
<template slot-scope="scope">
<el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
<el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<!-- 新增标签弹层 -->
<div class="add-form">
<el-dialog title="新增图书" :visible.sync="dialogFormVisible">
<el-form ref="dataAddForm" :model="formData" :rules="rules" label-position="right"
label-width="100px">
<el-row>
<el-col :span="12">
<el-form-item label="图书类别" prop="type">
<el-input v-model="formData.type"/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="图书名称" prop="name">
<el-input v-model="formData.name"/>
</el-form-item>
</el-col>
</el-row>
<el-row>
<el-col :span="24">
<el-form-item label="描述">
<el-input v-model="formData.description" type="textarea"></el-input>
</el-form-item>
</el-col>
</el-row>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false">取消</el-button>
<el-button type="primary" @click="handleAdd()">确定</el-button>
</div>
</el-dialog>
</div>
<!-- 编辑标签弹层 -->
<div class="add-form">
<el-dialog title="编辑检查项" :visible.sync="dialogFormVisible4Edit">
<el-form ref="dataEditForm" :model="formData" :rules="rules" label-position="right"
label-width="100px">
<el-row>
<el-col :span="12">
<el-form-item label="图书类别" prop="type">
<el-input v-model="formData.type"/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="图书名称" prop="name">
<el-input v-model="formData.name"/>
</el-form-item>
</el-col>
</el-row>
<el-row>
<el-col :span="24">
<el-form-item label="描述">
<el-input v-model="formData.description" type="textarea"></el-input>
</el-form-item>
</el-col>
</el-row>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible4Edit = false">取消</el-button>
<el-button type="primary" @click="handleEdit()">确定</el-button>
</div>
</el-dialog>
</div>
</div>
</div>
</div>
</body>
<!-- 引入组件库 -->
<script src="../js/vue.js"></script>
<script src="../plugins/elementui/index.js"></script>
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script src="../js/axios-0.18.0.js"></script>
<script>
var vue = new Vue({
el: '#app',
data: {
pagination: {},
dataList: [],//当前页要展示的列表数据
formData: {},//表单数据
dialogFormVisible: false,//控制表单是否可见
dialogFormVisible4Edit: false,//编辑表单是否可见
rules: {//校验规则
type: [{required: true, message: '图书类别为必填项', trigger: 'blur'}],
name: [{required: true, message: '图书名称为必填项', trigger: 'blur'}]
}
},
//钩子函数,VUE对象初始化完成后自动执行
created() {
this.getAll();
},
methods: {
//列表
getAll() {
var _this = this;
axios({
method: "get",
url: "http://localhost:8080/SSM-case/books"
}).then(function (resp) {
_this.dataList = resp.data.data;
});
},
//弹出添加窗口
handleCreate() {
this.dialogFormVisible = true;
this.resetForm();
},
//重置表单
resetForm() {
this.formData = {};
},
//添加
handleAdd() {
var _this = this;
axios({
method: "post",
url: "http://localhost:8080/SSM-case/books",
data: _this.formData
}).then(function (resp) {
if (resp.data.code == 20011) {
//如果操作成功,关闭弹窗
_this.dialogFormVisible = false;
_this.$message.success("添加成功");
} else if (resp.data.code == 20010) {
_this.$message.error("添加失败");
} else {
_this.$message.error(resp.data.message);
}
}).finally(() => {
_this.getAll();
})
},
//弹出编辑窗口
handleUpdate(row) {
//数据回显
var _this = this;
axios({
method: "get",
url: "http://localhost:8080/SSM-case/books/" + row.id
}).then(function (resp) {
if (resp.data.code == 20041) {
_this.formData = resp.data.data;
_this.dialogFormVisible4Edit = true;
} else {
_this.$message.error(resp.data.message);
}
})
},
//编辑
handleEdit() {
var _this = this;
axios({
method: "put",
url: "http://localhost:8080/SSM-case/books",
data: _this.formData
}).then(function (resp) {
if (resp.data.code == 20031) {
//如果操作成功,关闭弹窗
_this.dialogFormVisible4Edit = false;
_this.$message.success("编辑成功");
} else if (resp.data.code == 20030) {
_this.$message.error("编辑失败");
} else {
_this.$message.error(resp.data.message);
}
}).finally(() => {
_this.getAll();
})
},
// 删除
handleDelete(row) {
//1.确认是否删除的弹框
this.$confirm('此操作将删这些文件, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
//删除业务
var _this = this;
axios({
method: "delete",
url: "http://localhost:8080/SSM-case/books/"+row.id
}).then(function (resp) {
if (resp.data.code == 20021) {
_this.$message.success("删除成功");
}else{
_this.$message.error("删除失败");
}
}).finally(()=>{
//重新查询所有
_this.getAll();
})
}).catch(() => {
//取消删除业务
this.$message.success("取消删除成功");
});
}
}
})
</script>
</html>