Spring Boot
如果有错误,欢迎评论
一,Spring Boot 介绍
如果使用ssm作为项目架构,需要进行大量的配置(springmvc,mybatis,web.xml,tomcat等配置),配置相当繁琐,微服务系统开发效率低
Springboot其实就是一些jar包的集合,并没有增加新的功能,主要就是很大程度上简化了配置,进而提高开发效率,其主要有以下特点:
1.创建独立的Spring应用程序
2. 嵌入的Tomcat,无需部署WAR文件
3. 简化Maven配置
4. 自动配置Spring
5. 提供生产就绪型功能,如指标,健康检查和外部配置
6. 绝对没有代码生成和对XML没有要求配置
采用maven管理项目
二,构建Spring Boot项目及启动器
1.使用maven构建SpringBoot项目
2.注入SpringBoot启动坐标
<!-- springBoot的启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> |
3.SpringBoot启动器。
所谓的springBoot启动器其实就是一些jar包的集合。SprigBoot一共提供44启动器。
4.1 spring-boot-starter-web
支持全栈式的web开发,包括了romcat和springMVC等jar
4.2 spring-boot-starter-jdbc
支持spring以jdbc方式操作数据库的jar包的集合
4.3 spring-boot-starter-redis
支持redis键值存储的数据库操作
三,Spring Boot入门HelloWorld
1.编写返回HelloWorld的Controller
/** * SpringBoot HelloWorld * @author Administrator * */ @Controller publicclass HelloWorld {
@RequestMapping("/hello") @ResponseBody public Map<String, Object> showHelloWorld(){ Map<String, Object> map = new HashMap<>(); map.put("msg", "HelloWorld"); returnmap; } } |
2.启动SpringBoot 编写启动类
/** * SpringBoot 启动类 * @author Administrator * */ @SpringBootApplication publicclass App {
publicstaticvoid main(String[] args) { SpringApplication.run(App.class, args); } } |
3.关于编写启动器需要注意的问题
启动器存放的位置。启动器可以和controller位于同一个包下,或者位于controller的上一级包中,但是不能放到controller的平级以及子包下。 |
四 整合Servlet
1,通过注解扫描完成Servlet组件的注册
1.1编写servlet
/** *SpringBoot整合Servlet方式一 * *<servlet> * <servlet-name>FirstServlet</servlet-name> * <servlet-class>com.bjsxt.servlet.FirstServlet</servlet-class> *</servlet> * *<servlet-mapping> * <servlet-name>FirstServlet</servlet-name> * <url-pattern>/first</url-pattern> *</servlet-mapping> * */
@WebServlet(name="FirstServlet",urlPatterns="/first") publicclass FirstServlet extends HttpServlet {
@Override protectedvoid doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub super.doGet(req, resp); } } |
1.2编写启动类
/** * SpringBoot整合Servlet方式一 * * */ @SpringBootApplication @ServletComponentScan //在springBoot启动时会扫描@WebServlet,并将该类实例化 publicclass App {
publicstaticvoid main(String[] args) { SpringApplication.run(App.class, args); }
} |
2,通过方法完成Servlet组件的注册
2.1编写servlet
/** *SpringBoot整合Servlet方式二 * */
publicclass SecondServlet extends HttpServlet {
@Override protectedvoid doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("SecondServlet.........."); }
}
|
2.2编写启动类
/** * SpringBoot整合Servlet方式二 * * */ @SpringBootApplication publicclass App2 {
publicstaticvoid main(String[] args) { SpringApplication.run(App2.class, args); }
@Bean public ServletRegistrationBean getServletRegistrationBean(){ ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet()); bean.addUrlMappings("/second"); return bean; } }
|
五. 整合Filter
1,通过注解扫描完成Filter组件的注册
1.1编写Filter
/** *SpringBoot整合Filter 方式一 *<filter> * <filter-name>FirstFilter</filter-name> * <filter-class>com.bjsxt.filter.FirstFilter</filter-class> *</filter> *<filter-mapping> * <filter-name>FirstFilter</filter-name> * <url-pattern>/first</url-pattern> *</filter-mapping> */ //@WebFilter(filterName="FirstFilter",urlPatterns={"*.do","*.jsp"}) @WebFilter(filterName="FirstFilter",urlPatterns="/first") publicclass FirstFilter implements Filter {
@Override publicvoid destroy() { // TODO Auto-generated method stub
} @Override publicvoid doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { System.out.println("进入Filter"); arg2.doFilter(arg0, arg1); System.out.println("离开Filter"); }
@Override publicvoid init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } } |
1.2编写启动类
/** *SpringBoot整合Filter 方式一 * */ @SpringBootApplication @ServletComponentScan publicclass App {
publicstaticvoid main(String[] args) { SpringApplication.run(App.class, args);
}
} |
2,通过方法完成Filter组件的注册
2.1编写Filter
/** * *SpringBoot整合Filter 方式二 * */ publicclass SecondFilter implements Filter { @Override publicvoid destroy() { // TODO Auto-generated method stub } @Override publicvoid doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { System.out.println("进入SecondFilter"); arg2.doFilter(arg0, arg1); System.out.println("离开SecondFilter"); }
@Override publicvoid init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } } |
2.2编写启动类
/** * SpringBoot整合Filter方式二 * * */ @SpringBootApplication publicclass App2 {
publicstaticvoid main(String[] args) { SpringApplication.run(App2.class, args); }
/** * 注册Servlet * @return */ @Bean public ServletRegistrationBean getServletRegistrationBean(){ ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet()); bean.addUrlMappings("/second"); returnbean; }
/** * 注册Filter */ @Bean public FilterRegistrationBean getFilterRegistrationBean(){ FilterRegistrationBean bean = new FilterRegistrationBean(new SecondFilter()); //bean.addUrlPatterns(new String[]{"*.do","*.jsp"}); bean.addUrlPatterns("/second"); returnbean; } }
|
六. 整合Listener
1,通过注解扫描完成Listener组件的注册
1.1编写Listener
/** * springBoot整合Listener * *<listener> * <listener-class>com.bjsxt.listener.FirstListener</listener-class> *</listener> */ @WebListener publicclass FirstListener implements ServletContextListener {
@Override publicvoid contextDestroyed(ServletContextEvent arg0) { // TODO Auto-generated method stub
}
@Override publicvoid contextInitialized(ServletContextEvent arg0) { System.out.println("Listener...init......");
}
} |
1.2编写启动类
/** * springBoot整合Listener方式一 * * */ @SpringBootApplication @ServletComponentScan publicclass App {
publicstaticvoid main(String[] args) { SpringApplication.run(App.class, args); }
} |
2. 通过方法完成Listener组件注册
2.1编写Listener
/** * springBoot整合Listener方式二。 * * */ publicclass SecondListener implements ServletContextListener {
@Override publicvoid contextDestroyed(ServletContextEvent arg0) { // TODO Auto-generated method stub }
@Override publicvoid contextInitialized(ServletContextEvent arg0) { System.out.println("SecondListener..init....."); }
} |
2.2编写启动类
/** * SpringBoot整合Listener方式二 * * */ @SpringBootApplication publicclass App2 {
publicstaticvoid main(String[] args) { SpringApplication.run(App2.class, args);
} /** * 注册listener */ @Bean public ServletListenerRegistrationBean<SecondListener> getServletListenerRegistrationBean(){ ServletListenerRegistrationBean<SecondListener> bean= new ServletListenerRegistrationBean<SecondListener>(new SecondListener()); returnbean; } } |
七. 访问静态资源
1. SpringBoot从classpath/static的目录
注意目录名称必须是static
2. ServletContext根目录下
在src/main/webapp 目录名称必须要webapp
八. 文件上传
1. 编写Controller
/** * SpringBoot文件上传 * * */ //@Controller @RestController //表示该类下的方法的返回值会自动做json格式的转换 publicclass FileUploadController {
/* * 处理文件上传 */ @RequestMapping("/fileUploadController") public Map<String, Object> fileUpload(MultipartFile filename)throws Exception{ System.out.println(filename.getOriginalFilename()); filename.transferTo(new File("e:/"+filename.getOriginalFilename())); Map<String, Object> map = new HashMap<>(); map.put("msg", "ok"); returnmap; } }
|
2. 编写启动类
/** * SpringBoot文件上传 * * */ @SpringBootApplication publicclass App {
publicstaticvoid main(String[] args) { SpringApplication.run(App.class, args);
} } |
3. 设置上传文件大小的默认值
Springboot1.5.0中支持第一种方式,但是在springboot2.0.1当中,只支持第二种方式
第一种方式:
需要添加一个springBoot的配置文件
application.properties
设置单个上传文件的大小
spring.http.multipart.maxFileSize=200MB
设置一次请求上传文件的总容量
spring.http.multipart.maxRequestSize=200MB
第二种方式(在启动类当中)
@Bean public MultipartConfigElement multipartConfigElement() { MultipartConfigFactory factory = new MultipartConfigFactory(); //允许上传的文件最大值 factory.setMaxFileSize("20000MB"); //KB,MB /// 设置总上传数据总大小 factory.setMaxRequestSize("20000MB"); returnfactory.createMultipartConfig(); } |
Spring Boot(视图层技术)
一. SpringBoot整合jsp技术
1,创建项目
2,修改pom文件,添加坐标
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.10.RELEASE</version> </parent> <groupId>com.bjsxt</groupId> <artifactId>08-spring-boot-view-jsp</artifactId> <version>0.0.1-SNAPSHOT</version>
<dependencies> <!-- springBoot的启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <!-- jasper --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> </dependencies> </project> |
3,创建springBoot的全局配置文件,application.properties
spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp |
4,创建Controller
/** * SpringBoot整合jsp * * */ @Controller publicclass UserController { /* * 处理请求,产生数据 */ @RequestMapping("/showUser") public String showUser(Model model){ List<Users> list = new ArrayList<>(); list.add(new Users(1,"张三",20)); list.add(new Users(2,"李四",22)); list.add(new Users(3,"王五",24));
//需要一个Model对象 model.addAttribute("list", list); //跳转视图 return"userList"; } } |
5,创建jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <table border="1" align="center" width="50%"> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> <c:forEach items="${list }" var="user"> <tr> <td>${user.userid }</td> <td>${user.username }</td> <td>${user.userage }</td> </tr> </c:forEach> </table> </body> </html> |
6,创建启动类
/** * SpringBoot启动类 * * */ @SpringBootApplication publicclass App {
publicstaticvoid main(String[] args) { SpringApplication.run(App.class, args); } } |
Thymeleaf
简介:简单说, Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP 。相较与其他的模板引擎,它有如下三个极吸引人的特点:
1.Thymeleaf在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
2.Thymeleaf 开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
3.Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
4. 前后端可以很好的分离
二. SpringBoot整合Thymeleaf (spring官方推荐使用的视图层技术)
1. 创建Thymeleaf的入门项目
1.1 创建项目
1.2修改pom文件添加坐标
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.10.RELEASE</version> </parent> <groupId>com.bjsxt</groupId> <artifactId>10-spring-boot-view-thymeleaf</artifactId> <version>0.0.1-SNAPSHOT</version>
<properties> <java.version>1.7</java.version> </properties>
<dependencies> <!-- springBoot的启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- springBoot的启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies> </project> |
1.3创建存放视图的目录
目录位置:src/main/resources/templates
templates:该目录是安全的。意味着该目录下的内容是不允许外界直接访问的。
2. Thymeleaf的基本使用
2.1Thymeleaf特点:
Thymelaef是通过他特定语法对html的标记做渲染。
2.2编写Controller
/** * Thymeleaf入门案例 * * */ @Controller publicclass DemoController { @RequestMapping("/show") public String showInfo(Model model){ model.addAttribute("msg", "Thymeleaf 第一个案例"); return"index"; } } |
2.3创建视图.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Thymeleaf入门</title> </head> <body> <span th:text="Hello"></span> <hr/> <span th:text="${msg}"></span> </body> </html> |
2.4编写启动类
/** * *Thymeleaf入门案例 * */ @SpringBootApplication publicclass App {
publicstaticvoid main(String[] args) { SpringApplication.run(App.class, args); } } |
2.5 解决异常
2.5.1解决异常方式1
让html的标记按照严禁的语法去编写。
2.5.2解决异常方式2
Thymeleaf.jar:更新为3.0以上的版本
thymeleaf-layout-dialect.jar:更新为2.0以上的版本
更换thymeleaf的jar包的版本
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.10.RELEASE</version> </parent> <groupId>com.bjsxt</groupId> <artifactId>10-spring-boot-view-thymeleaf</artifactId> <version>0.0.1-SNAPSHOT</version>
<properties> <java.version>1.7</java.version> <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version> <thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version> </properties>
<dependencies> <!-- springBoot的启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- springBoot的启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies> </project> |
3. Thymeleaf语法详解
3.1变量输出与字符串操作
3.1.1th:text
th:text |
在页面中输出值 |
3.1.2th:value
th:value 只针对于常量 |
可以将一个值放入到input标签的value中 如果是从数据库中查出来的值则为 th:field |
3.1.3判断字符串是否为空
Thymeleaf内置对象
注意语法:
1,调用内置对象一定要用#
2,大部分的内置对象都以s结尾 strings、numbers、dates
${#strings.isEmpty(key)} |
判断字符串是否为空,如果为空返回true,否则返回false |
|
${#strings.contains(msg,'T')} |
判断字符串是否包含指定的子串,如果包含返回true,否则返回false |
|
${#strings.startsWith(msg,'a')} |
判断当前字符串是否以子串开头,如果是返回true,否则返回false |
|
${#strings.endsWith(msg,'a')} |
判断当前字符串是否以子串结尾,如果是返回true,否则返回false |
|
${#strings.length(msg)} |
返回字符串的长度 |
|
${#strings.indexOf(msg,'h')} |
查找子串的位置,并返回该子串的下标,如果没找到则返回-1 |
|
${#strings.substring(msg,13)} ${#strings.substring(msg,13,15)} |
截取子串,用户与jdk String类下SubString方法相同 |
|
${#strings.toUpperCase(msg)} ${#strings.toLowerCase(msg)} |
字符串转大小写。 |
|
3.2日期格式化处理
${#dates.format(key)} |
格式化日期,以浏览器的默认语言为格式化标准 |
|
${#dates.format(key,'yyy/MM/dd')} |
按照自定义的格式做日期转换 |
|
${#dates.year(key)} ${#dates.month(key)} ${#dates.day(key)} |
year:取年 Month:取月 Day:取日 |
3.3条件判断
3.3.1th:if
<span th:if="${sex} == '男'"> 性别:男 </span> <span th:if="${sex} == '女'"> 性别:女 </span> |
3.3.2th:switch
<div th:switch="${id}"> <span th:case="1">ID为1</span> <span th:case="2">ID为2</span> <span th:case="3">ID为3</span> </div> |
3.4迭代遍历
3.4.1 th:each 类似于foreach循环
@RequestMapping("/show3") public String showInfo3(Model model){ List<Users> list = new ArrayList<>(); list.add(new Users(1,"张三",20)); list.add(new Users(2,"李四",22)); list.add(new Users(3,"王五",24)); model.addAttribute("list", list); return"index3"; } |
<table border="1"> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> <tr th:each="u : ${list}"> <td th:text="${u.userid}"></td> <td th:text="${u.username}"></td> <td th:text="${u.userage}"></td> </tr> </table> |
3.4.2 th:each 状态变量
@RequestMapping("/show3") public String showInfo3(Model model){ List<Users> list = new ArrayList<>(); list.add(new Users(1,"张三",20)); list.add(new Users(2,"李四",22)); list.add(new Users(3,"王五",24)); model.addAttribute("list", list); return"index3"; } |
<table border="1"> <tr> <th>ID</th> <th>Name</th> <th>Age</th> <th>Index</th> <th>Count</th> <th>Size</th> <th>Even</th> <th>Odd</th> <th>First</th> <th>lase</th> </tr> <tr th:each="u,var : ${list}"> <td th:text="${u.userid}"></td> <td th:text="${u.username}"></td> <td th:text="${u.userage}"></td> <td th:text="${var.index}"></td> <td th:text="${var.count}"></td> <td th:text="${var.size}"></td> <td th:text="${var.even}"></td> <td th:text="${var.odd}"></td> <td th:text="${var.first}"></td> <td th:text="${var.last}"></td> </tr> </table> |
状态变量属性
1,index:当前迭代器的索引 从0开始
2,count:当前迭代对象的计数 从1开始
3,size:被迭代对象的长度
4,even/odd:布尔值,当前循环是否是偶数/奇数 从0开始
5,first:布尔值,当前循环的是否是第一条,如果是返回true否则返回false
6,last:布尔值,当前循环的是否是最后一条,如果是则返回true否则返回false
3.4.3th:each迭代Map
@RequestMapping("/show4") public String showInfo4(Model model){ Map<String, Users> map = new HashMap<>(); map.put("u1", new Users(1,"张三",20)); map.put("u2", new Users(2,"李四",22)); map.put("u3", new Users(3,"王五",24)); model.addAttribute("map", map); return"index4"; } |
<table border="1"> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> <tr th:each="maps : ${map}"> <td th:text="${maps}"></td> </tr> </table> <th/> <table border="1"> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> <tr th:each="maps : ${map}"> <td th:each="entry:${maps}" th:text="${entry.value.userid}" ></td> <td th:each="entry:${maps}" th:text="${entry.value.username}"></td> <td th:each="entry:${maps}" th:text="${entry.value.userage}"></td> </tr> </table> |
3.5域对象操作
3.5.1HttpServletRequest
request.setAttribute("req", "HttpServletRequest"); |
Request:<span th:text="${#httpServletRequest.getAttribute('req')}"></span><br/> |
3.5.2HttpSession
request.getSession().setAttribute("sess", "HttpSession"); |
Session:<span th:text="${session.sess}"></span><br/> |
3.5.3ServletContext
request.getSession().getServletContext().setAttribute("app", "Application"); |
Application:<span th:text="${application.app}"></span> |
3.6 URL表达式
th:href
th:src
3.6.1 url表达式语法
基本语法:@{}
3.6.2 URL类型
3.6.2.1绝对路径
<a th:href="@{http://www.baidu.com}">绝对路径</a><br/> |
3.6.2.2 相对路径
1)相对于当前项目的根
相对于项目的上下文的相对路径
<a th:href="@{/show}">相对路径</a> |
2) 相对于服务器路径的根
<a th:href="@{~/project2/resourcename}">相对于服务器的根</a> |
3.6.3在url中实现参数传递
<a th:href="@{/show(id=1,name=zhagnsan)}">相对路径-传参</a> |
3.6.4在url中通过restful风格进行参数传递
<a th:href="@{/path/{id}/show(id=1,name=zhagnsan)}">相对路径-传参-restful</a> |
SpringBoot
(SpringBoot整合SpringMVC+MyBatis)
一、 创建项目
1 修改pom文件(导入相关jar包)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.10.RELEASE</version> </parent> <groupId>com.bjsxt</groupId> <artifactId>12-spring-boot-springmvc-mybatis</artifactId> <version>0.0.1-SNAPSHOT</version>
<properties> <java.version>1.7</java.version> <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version> <thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version> </properties>
<dependencies> <!-- springBoot的启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- web启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- Mybatis启动器 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <!-- mysql数据库驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- druid数据库连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.9</version> </dependency> </dependencies> </project> |
2 添加application.properties全局配置文件(其实就是配置数据源,springboot当中唯一需要配置的东西)
spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/ssm spring.datasource.username=root spring.datasource.password=root
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
mybatis.type-aliases-package=com.bjsxt.pojo |
3 数据库表
二、 添加用户(以对数据库的插入为例)
1 创建实体类
publicclass Users { private Integer id; private String name; private Integer age; public Integer getId() { returnid; } publicvoid setId(Integer id) { this.id = id; } public String getName() { returnname; } publicvoid setName(String name) { this.name = name; } public Integer getAge() { returnage; } publicvoid setAge(Integer age) { this.age = age; }
}
|
2 创建mapper接口以及映射配置文件
import com.bjsxt.pojo.Users;
publicinterface UsersMapper {
void insertUser(Users users); }
|
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.bjsxt.mapper.UsersMapper"> <insert id="insertUser" parameterType="users"> insert into users(name,age) values(#{name},#{age}) </insert> </mapper> |
3 创建业务层
@Service @Transactional //所经过的事务 publicclass UsersServiceImpl implements UsersService {
@Autowired private UsersMapper usersMapper;
@Override publicvoid addUser(Users users) { this.usersMapper.insertUser(users); } } |
4 创建Controller
@Controller @RequestMapping("/users") publicclass UsersController {
@Autowired private UsersService usersService;
/** * 页面跳转 */ @RequestMapping("/{page}") public String showPage(@PathVariable String page){ returnpage; }
/** * 添加用户 */ @RequestMapping("/addUser") public String addUser(Users users){ this.usersService.addUser(users); return"ok"; } }
|
5 编写页面
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>添加用户</title> </head> <body>
<form th:action="@{/users/addUser}" method="post"> 用户姓名:<input type="text" name="name"/><br/> 用户年龄:<input type="text" name="age"/><br/> <input type="submit" value="确定"/><br/> </form> </body> </html> |
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>操作提示页面</title> </head> <body> 操作成功!!! </body> </html> |
6 启动类
@SpringBootApplication @MapperScan("com.bjsxt.mapper") //@MapperScan 用户扫描MyBatis的Mapper接口 publicclass App {
publicstaticvoid main(String[] args) { SpringApplication.run(App.class, args); } } |