环境 :window10 、IDEA 2018.2.4、jdk1.8.0_131。 使用springboot框架,mybits作数据处理,Thymeleaf作试图渲染。
参考文章 th标签 项目地址 刚入门 写细点
一、项目创建与初步配置
这样一个项目就建好了:
总述:主要是第3、4的选择使得 pom.xml文件中的<dependency>出现上图中代码。其他的不重要。
两个重要配置文件, pom.xml和application.yml
<?xml version="1.0" encoding="UTF-8"?> <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>2.1.6.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <!--mybatis--> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.1</version> </dependency> <dependency> <!--mysql--> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>previous</scope> </dependency> <!-- 分页插件 <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.3</version> </dependency> --> <!-- 版本 --> <dependency> <!-- JSON --> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.12</version> </dependency> <dependency> <!--thymeleaf--> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <!-- mybatis generator 自动生成代码插件 --> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> </plugin> </plugins> </build> </project>
①把application.properties文件改名为application.properties-bak 使它失效,或者直接把它删除;②在同目录下新建application.yml (new file -> file 输入application.yml 即可)
spring: datasource: url: jdbc:mysql://localhost:3306/boot_demo?serverTimezone=UTC&useSSL=false username: root password: xu12chuan driver-class-name: com.mysql.cj.jdbc.Driver profiles: active: dev thymeleaf: mode: HTML cache: false mvc: view: prefix: /templates mybatis: mapper-locations: classpath:mapping/*.xml type-aliases-package: com.example.demo.Entity configuration: map-underscore-to-camel-case: true # springboot - mybatis - 下划线与驼峰自动转换 server: port: 9008 #pagehelper分页插件 #pagehelper: # helperDialect: mysql # reasonable: true # supportMethodsArguments: true # params: count=countSql
后面会解释这里面的东西
二、数据库与相关文件生成
① 在MySQL中建库和表:
create database boot_demo; use boot_demo; -- ---------------------------- -- Table structure for `tb_area` -- ---------------------------- DROP TABLE IF EXISTS `tb_area`; CREATE TABLE `tb_area` ( `area_id` int(2) NOT NULL AUTO_INCREMENT COMMENT '区域ID', `area_name` varchar(200) DEFAULT NULL COMMENT '区域名称', `priority` int(2) DEFAULT '0' COMMENT '优先级', `create_time` datetime DEFAULT NULL COMMENT '创建时间', `last_edit_time` datetime DEFAULT NULL COMMENT '修改时间', PRIMARY KEY (`area_id`), UNIQUE KEY `uk_area` (`area_name`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of tb_area -- ---------------------------- INSERT INTO `tb_area` VALUES ('1', '东苑', '1', null, null); INSERT INTO `tb_area` VALUES ('2', '北苑', '2', null, null);
②在pom.xml的 build -> plugins 下添加:(其中下划线部分指示下一步…)
<!-- mybatis generator 自动生成代码插件 --> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> </plugin>
③在resources目录下新建文件夹generator;在generator下新建文件generatorConfig.xml,该文件代码如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包--> <classPathEntry location="C:\Program Files (x86)\MySQL\Connector J 5.1\mysql-connector-java-5.1.45-bin.jar"/> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressDate" value="true"/> <!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressAllComments" value="true"/> </commentGenerator> <!--数据库链接URL,用户名、密码 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1/boot_demo" userId="root" password="xu12chuan"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 生成模型的包名和位置--> <javaModelGenerator targetPackage="com.example.demo.Entity" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- 生成映射文件的包名和位置--> <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- 生成DAO的包名和位置--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.demo.Dao" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名--> <table tableName="tb_area" domainObjectName="Area" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> </context> </generatorConfiguration>
注意下划线部分:找到你主机上的包mysql-connector-java-5.1.45-bin.jar的地址,修改你的数据库名、userId和password。
④点开 Maven Projects项目中的… ,双击执行; 发现目录中多了些什么东西 (就是上面代码 下划线部分所指出的Dao、映射文件之类的啦)
AreaMapper接口的具体实现 在AreaMapper.xml文件中,现在我们明白从②到④是利用数据库的表 来自动完成JavaBean和Dao的实现。
补充:在application.yml中写入
mybatis: mapper-locations: classpath:mapping/*.xml # ~Mapper接口实现文件 type-aliases-package: com.example.demo.Entity #对应的Entity中的表类
三、手动实现Dao
上面Dao/AreaMapper只是自动给出了部分SQL,我们可以仿照着 定义更多的接口并①在AreaMapper.xml中实现,或者直接②在AreaMapper中实现 :
分别在Dao/AreaMapper和AreaMapper.xml中写入
//这个方式我自己加的 --in Dao/AreaMapper List<Area> findAll(); @Select(value="select * from tb_area where area_id=#{id}") Area findOne(Integer id);
<!-- 实现AreaMapper中声明的findAll接口 -- in AreaMapper.xml--> <select id="findAll" resultType="Area"> select * from tb_area </select>
还要在application.yml中加入 mybatis.configuration.map-underscore-to-camel-case= true #springboot - mybatis - 下划线与驼峰自动转换
四、实现Controller
①在com.example.demo目录下 创建Controller目录和AreaController文件,文件代码如下:
package com.example.demo.controller; import com.example.demo.Dao.AreaMapper; import com.example.demo.Entity.Area; //import com.example.demo.service.AreaService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.websocket.server.PathParam; import java.util.HashMap; import java.util.Map; import com.alibaba.fastjson.JSON; @Controller //@RequestMapping("/area") public class AreaController { @Autowired private AreaMapper areaMapper; @ResponseBody @RequestMapping(value = "/get", produces = {"application/json;charset=UTF-8"}) public Map<String,Object> getArea(@PathParam("areaId") Integer areaId){ Map<String,Object> modelMap= new HashMap<String,Object>() ; modelMap.put("area",areaMapper.selectByPrimaryKey(areaId)); return modelMap; } @ResponseBody @RequestMapping("get/{id}") public String findById(@PathVariable("id") Integer id) { return JSON.toJSONString(areaMapper.findOne(id)); } @ResponseBody @RequestMapping("find") public String findUser() { return JSON.toJSONString(areaMapper.findAll()); } @ResponseBody @RequestMapping(value = "/add", produces = {"application/json;charset=UTF-8"}) public Map<String,Object> addArea(Area area){ Map<String,Object> modelMap= new HashMap<String,Object>() ; modelMap.put("success",areaMapper.insertSelective(area)+1); return modelMap; } @GetMapping("/test") public String Test(){ return "test"; } } /* @ResponseBody @RequestMapping(value = "/edit", produces = {"application/json;charset=UTF-8"}) public Map<String,Object> editArea(Area area){ Map<String,Object> modelMap= new HashMap<String,Object>() ; modelMap.put("success",areaMapper.updateByPrimaryKeySelective(area)); return modelMap; } @RequestMapping(value = "/all/{pageNum}/{pageSize}", produces = {"application/json;charset=UTF-8"}) public Object findAllArea(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize){ return areaService.findAllArea(pageNum,pageSize); } @ResponseBody @GetMapping(value="/del") public Map<String,Object> deleteArea(@PathParam("areaId") Integer areaId){ Map<String,Object> modelMap= new HashMap<String,Object>() ; modelMap.put("success",areaMapper.deleteByPrimaryKey(areaId)); return modelMap; }*/
②在AreaMapper类上加入@Component注释,在启动类上加入@MapperScan("com.example.demo.Dao")注释,在application.yml中加入:
spring: datasource: url: jdbc:mysql://localhost:3306/boot_demo?serverTimezone=UTC&useSSL=false username: root password: xu12chuan driver-class-name: com.mysql.cj.jdbc.Driver
③因为在AreaController.java中使用了JSON.toJSONString(),所以import com.alibaba.fastjson.JSON; 还要再pom.xml中加入:
<dependency> <!-- JSON --> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.12</version> <!--最新1.2.31--> </dependency>
运行:
五、Thymeleaf视图渲染
①分别在pom.xml、application.yml中加入:
<dependency> <!--thymeleaf in pom.xml--> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
spring:
profiles:
active: dev
thymeleaf:
mode: HTML
cache: false
mvc:
view:
prefix: /templates #路径
②在Entity/Area中改写:
@NotEmpty
@Size(min=2, max=30)
private String areaName;
@NotNull //used in org.springframework.validation.BindingResult;
@Min(1)
@Max(200)
private Integer priority;
③在com.example.demo/Controller目录下 创建AreaHtmlController文件,文件代码如下:
package com.example.demo.controller; import com.example.demo.Dao.AreaMapper; import com.example.demo.Entity.Area; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.validation.Valid; import java.util.HashMap; import java.util.Map; @Controller public class AreaHtmlController{ @Autowired private AreaMapper areaMapper; @GetMapping("/addArea") public String addArea(Model model) { model.addAttribute("msg","Spring boot集成Thymeleaf"); model.addAttribute("area", new Area()); return "addArea"; //在templates中寻找addArea.html,而不会陷入循环 } @RequestMapping(value = "/addArea",method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) public String addArea(@Valid @ModelAttribute Area area, BindingResult bindingResult){ if (bindingResult.hasErrors()) { // in com..Entity @NotEmpty @Size(min=2, max=30) and @Valid return "addArea"; //@ModelAttribute Area area --https://www.cnblogs.com/zhangshitong/p/5342076.html }else{ Map<String,Object> modelMap= new HashMap<String,Object>() ; modelMap.put("success",areaMapper.insertSelective(area)); return "addArea"; } } } AreaHtmlController.java
其中@Valid使得参数对象bindingResult能 识别参数area是否违背②中的限制 ,@ModelAttribute Area area使得Attribute.add("area",area)并传入对应的html文件中:
④编写templates/addArea.html并运行:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"><!--引入thymeleaf--> <head> <meta charset="UTF-8" /> <title>添加区域</title></head> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /> <body> <h2 style="color:green;text-align: center;">添加区域</h2> <p th:text="${msg}">你好</p> <form class="form-horizontal" role="form" action="#" th:action="@{/addArea}" th:object="${area}" method="post"> <div class="form-group"> <label for="name" class="col-sm-2 control-label"> 区域名称: </label> <div class="col-sm-8"> <input type="text" th:field="*{areaName}" class="form-control" id="areaName" placeholder="输入区域名称"> </div> <label class="col-sm-2" style="color:red" th:if="${#fields.hasErrors('areaName')}" th:errors="*{areaName}"> 区域名称错误 </label> </div> <div class="form-group"> <label for="priority" class="col-sm-2 control-label"> 优先级 </label> <div class="col-sm-8"> <input type="text" th:field="*{priority}" class="form-control" id="priority" placeholder="输入优先级"> </div> <label class="col-sm-2" style="color:red" th:if="${#fields.hasErrors('priority')}" th:errors="*{priority}"> 优先级错误 </label> </div> <div class="form-group"> <div class="col-sm-12" style="text-align: center"> <button type="submit" class="btn btn-primary" id="btn">Submit</button> <input type="reset" class="btn btn-warning" value="Reset"/> </div> </div> </form> </body> </html>
2019-07-18 16:44:43
本文暂时没有评论,来添加一个吧(●'◡'●)