三分钟搭建Spring Boot项目框架以及框架的应用
Posted GYTTking
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了三分钟搭建Spring Boot项目框架以及框架的应用相关的知识,希望对你有一定的参考价值。
一、新建springboot项目
1、
- new–>Project–>Spring Initralizr
- Group:com.zb
- Artifact:zbook
- springboot version:2.0.4
2、
- 将
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
- 改成
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
3、此时项目结构
- maven clean一下,右键ZbookApplication运行,项目就跑起来了,就是这么简单,真正做到了开箱即用。
二、RestFul Api接口
package com.zb.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HomeController
@RequestMapping("/")
public String home()
return "Hello, Zbook!";
-
:RestController和Controller注解的区别是:RestController是返回的内容就是返回的内容,相当于加个@ResponseBody,而controller一般是返回的页面
-
此时打开网页,输入 http://localhost:8080/
就会看到Hello,Zbook!
三、集成Thymleaf
1、
- 上面的可以当作是提供服务的接口,假设我们要开发一个web应用,springboot默认是集成的thymleaf。
springboot是约定大于配置的,我们来看看关于thymleaf的约定 - (1)默认静态文件(js,css,jpg等)放在resources下面的static文件夹下面
- (2)页面文件放在templates文件夹下面
我们采用bootstrap来渲染页面,如下图
login.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>登录</title>
<link href="/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<form action="login_in" method="post" class="form-horizontal" role="form" >
<div class="form-group">
<h2 class="col-sm-offset-5 col-sm-4">用户登录</h2>
</div>
<div class="form-group">
<label for="username" class="col-sm-offset-3 col-sm-2 control-label">用户名:</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="username" name="username" placeholder="请输入用户名" />
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-offset-3 col-sm-2 control-label">密码:</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="password" name="password" placeholder="请输入密码" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-5 col-sm-4">
<button type="submit" class="btn btn-default">登录</button>
</div>
</div>
</form>
</div>
<script src="/js/jquery-2.2.1.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
</body>
</html>
2、写一个LoginController
package com.zb.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class LoginController
@RequestMapping("/login")
public String login()
return "login";
3、加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
4、
- 重启, http://localhost:8080/login
则会看到登录页面
四、集成mybatis
1、springboot的配置文件分为两种:
- application.properties和application.yml我们把它改成application.yml这种更直观
spring:
application:
name: myspringboot
output:
ansi:
enabled: always
profiles:
active: dev
thymeleaf:
encoding: UTF-8
prefix: classpath:/templates/
server:
tomcat:
uri-encoding: UTF-8
max-connections: 500
min-spare-threads: 25
max-threads: 300
accept-count: 200
port: 8080
mybatis:
type-aliases-package: com.zb.mapper
mapper-locations: classpath:mapping/*.xml
pagehelper:
helper-dialect: mysql
reasonable: true
support-methods-arguments: true
params: count=countSql
logging:
level:
com.zb.mapper: debug
---
#开发配置
spring:
profiles: dev
datasource:
url: jdbc:mysql://localhost:3306/zb_db?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false&useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
2、添加依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>RELEASE</version>
</dependency>
<!-- 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
3、建表
CREATE datebase zb_db;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`mobile` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`sex` varchar(255) DEFAULT NULL,
`nickname` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(1, 'admin', '123456', '13918891675','mmc@163.com', '男', '管理员');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(2, 'lisi2', '123456', '13918891675','mmc@163.com', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(3, 'lisi3', '123456', '13918891675','mmc@163.com', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(4, 'lisi4', '123456', '13918891675','mmc@163.com', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(5, 'lisi5', '123456', '13918891675','mmc@163.com', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(6, 'lisi6', '123456', '13918891675','mmc@163.com', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(7, 'lisi7', '123456', '13918891675','mmc@163.com', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(8, 'lisi8', '123456', '13918891675','mmc@163.com', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(9, 'lisi9', '123456', '13918891675','mmc@163.com', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(10, 'lisi10', '123456', '13918891675','mmc@163.com', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(11, 'lisi11', '123456', '13918891675','mmc@163.com', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(12, 'lisi12', '123456', '13918891675','mmc@163.com', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(13, 'lisi13', '123456', '13918891675','mmc@163.com', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(14, 'lisi14', '123456', '13918891675','mmc@163.com', 'm', 'lisi1');
4、用mybatisgenerator自动生成文件
<?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:\\Users\\DELL\\Downloads\\mysql-connector-java-5.1.22-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/zb_db" userId="root" password="123456">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置-->
<javaModelGenerator targetPackage="com.zb.model" 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.zb.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
<table tableName="role_permission" domainObjectName="RolePermission" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
5、在pom里面添加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>
6、用mvn mybatis-generator:generate -e命令生成文件
- 此时目录结构
7、写dao和service,controller,mapper
- mapper增加了几个方法
@Select("Select * from user")
List<User> selectAll();
@Select("Select * from user where username = #username and password = #password")
User selectByUsernamePass(@Param("username") String username, @Param("password") String password);
@Select("Select * from user where username = #username")
User selectByUsername(@Param("username") String username);
- dao和service都是正常调用,下面是controller
package com.zb.controller;
import com.github.pagehelper.PageInfo;
import com.zb.model.User;
import com.zb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class UserController
@Autowired
private UserService userService;
@RequestMapping("/user")
@ResponseBody
public User getUserById(int id)
User user = userService.selectByPrimaryKey(id);
return user;
@RequestMapping("/userlist")
public String getUserList(Model model, PageInfo pageInfo)
int pageNum = (pageInfo.getPageNum() == 0)? 1 : pageInfo.getPageNum();
int pageSize = (pageInfo.getPageSize() == 0)? 10 : pageInfo.getPageSize();
PageInfo<User> result = userService.selectAll(pageNum, pageSize);
model.addAttribute("users", result.getList());
model.addAttribute("pageInfo", result);
return "userlist";
@RequestMapping("/userdelete")
public String userdelete(int id)
userService.以上是关于三分钟搭建Spring Boot项目框架以及框架的应用的主要内容,如果未能解决你的问题,请参考以下文章