Hello,World!
大家看我的博客也有一段时间了,前面出了Spring和SringMVC的教程,现在就出一个综合性的教程把前面学的串联起来。
开发环境:
1.开发工具:Idea
2.Jdk版本:8
3.数据库连接架包:8以上即可
我们来回顾一下需要那些架包
1.第一SSM框架的基础Jar包springwebmvc
2.Mybaits和Juint,Servlet
3.进行事物管理的Jdbc,以及连接池的Druid
4.简化实体类开发的lombok和转换Json格式的FastJson
废话不多说,开始上手代码
1.创建一个maven项目,并引用以下架包
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.19</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.19</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</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>2.0.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.19</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
<!-- 添加slf4j日志api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.20</version>
</dependency>
<!-- 添加logback-classic依赖 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- 添加logback-core依赖 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
2.见一个Config包,用来写配置类
1.建一个applicationContextConfig.java
@Configuration
@ComponentScan(value = "com.yunhuisu",excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = Controller.class)})
@Import({DataSourceConfig.class,MybatisConfig.class})
public class ApplicationContextConfig {
}
2.建一个DataSourceConfig.java用来写数据源和开启事务,这里还有一个数据库连接配置文件db.properties
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
@PropertySource("classpath:db.properties")
@EnableTransactionManagement
public class DataSourceConfig {
@Value("${db.driver}")
private String driver;
@Value("${db.url}")
private String url;
@Value("${db.username}")
private String username;
@Value("${db.password}")
private String password;
@Bean
public DataSource setDataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(driver);
druidDataSource.setUrl(url);
druidDataSource.setUsername(username);
druidDataSource.setPassword(password);
return druidDataSource;
}
@Bean
public PlatformTransactionManager setTransactionManager(@Autowired DataSource dataSource) {
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);
return dataSourceTransactionManager;
}
}
db.properties
db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql:///ssmbuild
db.username=root
db.password=123456
3.建mybatis的配置类
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
public class MybatisConfig {
@Bean
public SqlSessionFactoryBean setSqlSessionFactoryBean(@Autowired DataSource dataSource,@Autowired ApplicationContext applicationContext) {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setTypeAliasesPackage("com.yunhuisu.pojo");
sqlSessionFactoryBean.setConfigLocation(applicationContext.getResource("classpath:mybatis-config.xml"));
return sqlSessionFactoryBean;
}
@Bean
public MapperScannerConfigurer setMapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.yunhuisu.mapper");
return mapperScannerConfigurer;
}
}
以及可建可不建的mybatis-config.xml,我这里建了是为了开启SLF4J日志
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="cacheEnabled" value="false"/>
<setting name="logImpl" value="SLF4J"/>
</settings>
</configuration>
顺带把SLF4J日志的配置文件也一起建立了logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!--
CONSOLE :表示当前的日志信息是可以输出到控制台的。
-->
<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%level] %blue(%d{HH:mm:ss.SSS}) %cyan([%thread]) %boldGreen(%logger{15}) - %msg %n</pattern>
</encoder>
</appender>
<logger name="com.itheima" level="DEBUG" additivity="false">
<appender-ref ref="Console"/>
</logger>
<!--
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF
, 默认debug
<root>可以包含零个或多个<appender-ref>元素,标识这个输出位置将会被本日志级别控制。
-->
<root level="DEBUG">
<appender-ref ref="Console"/>
</root>
</configuration>
4.最后来建SpringMVC的配置类
sprinmvcServlet.java这个类就类似于你们在web.xml里面配置的一些东西
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.Filter;
public class SpringmvcServlet extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class[]{ApplicationContextConfig.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};
}
}
还要建一个类springmvcConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@ComponentScan(value = "com.yunhuisu.controller")
public class SpringmvcConfig {
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
3.设计数据库
CREATE DATABASE `ssm`;
USE `ssm`;
DROP TABLE IF EXISTS `books`;
CREATE TABLE `books` (
`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` VARCHAR(100) NOT NULL COMMENT '书名',
`bookCounts` INT(11) NOT NULL COMMENT '数量',
`detail` VARCHAR(200) NOT NULL COMMENT '描述',
KEY `bookID` (`bookID`)
);
INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,'Java',1,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',5,'从进门到进牢');
4.建与数据库相对于的实体类和Mapper映射
1.在pojo包下面建Books.java类
import lombok.Data;
@Data
public class Books {
private int bookID;
private String bookName;
private String bookCounts;
private String detail;
}
2.在mapper包下面建BookMapper.java
import com.yunhuisu.pojo.Books;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public interface BookMapper {
@Select("SELECT * FROM books")
List<Books> findAllBook();
@Select("SELECT * FROM books WHERE bookID = #{bookID}")
Books findByIdBook(@Param("bookID")int bookID);
@Insert("INSERT INTO books(bookName, bookCounts, detail) VALUES (#{bookName}, #{bookCounts}, #{detail})")
boolean addBook(Books books);
@Update("UPDATE books SET bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail} WHERE bookID = #{bookID}")
boolean updateBook(Books books);
@Delete("DELETE FROM books WHERE bookID = #{bookID}")
boolean byIdDeleteBook(@Param("bookID")int bookID);
}
5.在Service层对数据进行处理
1.建一个BookService.java
import com.yunhuisu.pojo.Books;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Transactional
@Service
public interface BookService {
List<Books> findAllBook();
Books findByIdBook(int bookID);
boolean addBook(Books books);
boolean updateBook(Books books);
boolean byIdDeleteBook(int bookID);
}
2.在Impl进行实现,建BookServiceImpl.java
import com.yunhuisu.mapper.BookMapper;
import com.yunhuisu.pojo.Books;
import com.yunhuisu.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BookServiceImpl implements BookService {
@Autowired
BookMapper bookMapper;
public List<Books> findAllBook() {
return bookMapper.findAllBook();
}
@Override
public Books findByIdBook(int bookID) {
return bookMapper.findByIdBook(bookID);
}
@Override
public boolean addBook(Books books) {
return bookMapper.addBook(books);
}
@Override
public boolean updateBook(Books books) {
return bookMapper.updateBook(books);
}
@Override
public boolean byIdDeleteBook(int bookID) {
return bookMapper.byIdDeleteBook(bookID);
}
}
6.最后来建Controller层
import com.alibaba.fastjson.JSON;
import com.yunhuisu.pojo.Books;
import com.yunhuisu.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
public class BookController {
@Autowired
BookService bookService;
@RequestMapping(value = "/findBook", produces = "text/html;charset=utf-8")
@ResponseBody
public String findBook() {
List<Books> books = bookService.findAllBook();
String resultBooks = JSON.toJSONString(books);
return resultBooks;
}
@RequestMapping(value = "/findByIdBook/{id}" , produces = "text/html;charset=utf-8")
@ResponseBody
public String findByIdBook(@PathVariable("id") int id) {
Books byIdBook = bookService.findByIdBook(id);
String resultBook = JSON.toJSONString(byIdBook);
return resultBook;
}
@RequestMapping(value = "/addBook",produces = "text/html;charset=utf-8")
@ResponseBody
public String addBook(Books books) {
boolean insertResult = bookService.addBook(books);
return insertResult == true ? "插入成功" : "插入失败";
}
@RequestMapping(value = "/updateBook",produces = "text/html;charset=utf-8")
@ResponseBody
public String updateBook(Books books) {
boolean updateResult = bookService.addBook(books);
return updateResult == true ? "修改成功" : "修改失败";
}
@RequestMapping(value = "/deleteByIdBook/{id}",produces = "text/html;charset=utf-8")
@ResponseBody
public String deleteByIdBook(@PathVariable("id") int id) {
boolean deleteResult = bookService.byIdDeleteBook(id);
return deleteResult == true ? "删除成功" : "删除失败";
}
}
最后我们用Postman来测试我们写的接口
1.查询全部书接口
2.通过Id查询书接口
3.插入一本书接口
4.修改一本书接口
5.通过Id删除书接口