springboot创建webservice访问mysql(使用maven)

安装

使用maven,在你的pom.xml中添加如下配置
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
</parent> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency> <plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin> maven package 测试是否安装成功
mvn dependency:tree 查看你的安装依赖

起步

src/main/java 下面添加一个类,假如如下代码

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.web.bind.annotation.*; @SpringBootApplication // 声明主程序类
@RestController // 声明我们的类是一个web容器
@EnableAutoConfiguration // 自动配置spring
public class first {
@RequestMapping("/") // 监听("/")路由,返回字符串
String home() {
return "Hello World!";
}
public static void main(String[] args) {
SpringApplication.run(first.class, args); // 开启tomcat服务器,运行程序 }
} 如果端口冲突,可以配置tomcat的端口
在src/main/resources/
创建文件application.properties
加入 server.port=8888 # application.properties文件的格式
application.name=@project.name@
application.version=@project.version@ 1. maven运行spring
运行 mvn spring-boot:run
2. 打包成可执行文件执行
运行 mvn package 打包war文件
运行 jar tvf FirstMaven-0.0.1-SNAPSHOT.war 查看war包里面的内容
运行 java -jar FirstMaven-0.0.1-SNAPSHOT.war 运行可执行文件
访问 http://localhost:8888/#/

spring常用命令

mvn dependency:tree                                                 查看依赖
mvn spring-boot:run 运行程序
mvn package 打包程序
jar tvf myproject-0.0.1-SNAPSHOT.jar 查看jar包内部信息
java -jar myproject-0.0.1-SNAPSHOT.jar 运行你的jar包

spring常见注释

@RestController                                                     声明是一个控制器和@Controller等效,用来处理网络请求
@RequestMapping 声明请求的路径
@Autowired 自动注入,你可以使用构造器注入来代替@Autowired,如下
public class DatabaseAccountService implements AccountService {
private final RiskAssessor riskAssessor;
public DatabaseAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
}
}
public class DatabaseAccountService implements AccountService {
@Autowired
RiskAssessor riskAssessor;
}
上面两者等价
@SpringBootApplication 等价于开启@EnableAutoConfiguration,@ComponentScan,@Configuration
@EnableAutoConfiguration 开启spring默认依赖配置
@ComponentScan 如果这个添加入口文件,那么可以扫描到@Component, @Service, @Repository, @Controller声明的文件,并且自动注册成bean
@Configuration 允许配置其他的bean和使用@Import导入其他配置类
@Import 导入其他配置类@Import({ MyConfig.class, MyAnotherConfig.class })

springboot入门级使用

配置你的pom.xml文件


<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
</parent> <properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<java.version>1.8</java.version>
</properties> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<jvmArguments>
-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005
</jvmArguments>
</configuration>
</plugin>

配置文件

application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=1000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
server.port=8888
server.session.timeout=10
server.tomcat.uri-encoding=UTF-8

创建所需测试类

Greeting.java
public class Greeting { private final long id;
private final String content; public Greeting(long id, String content) {
this.id = id;
this.content = content;
} public long getId() {
return id;
} public String getContent() {
return content;
}
} GreetingController.java import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong; import javax.security.auth.message.callback.PrivateKeyCallback.Request; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; @RestController // 标记控制器返回一个域对象
public class GreetingController {
@Autowired
private JdbcTemplate jdbcTemplate; private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong(); @CrossOrigin(origins = "http://localhost:8080") // 跨域设置
@RequestMapping("/greeting") // 绑定路由,支持get,post,put,限定路由方式的写法@RequestMapping(method=RequestMethod.GET,value="/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(), String.format(template, name));
} @CrossOrigin(origins = "http://localhost:8080")
@RequestMapping(method=RequestMethod.GET,value="/mytest")
public List<Map<String, Object>> mytest(@RequestParam(value="name", defaultValue="小红") String name) { // @RequestBody Map<String,Object> params
String sql = "select * from test WHERE name=?;";
List<Map<String, Object>> result = jdbcTemplate.queryForList(sql, name);
return result;
}
}
first.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class first {
public static void main(String[] args) {
SpringApplication.run(first.class, args);
}
}

测试页面

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
// axios.get('http://localhost:8888/greeting').then(function (response) {
// console.log(response);
// }).catch(function (error) {
// console.log(error);
// }).then(function () {
// }); // axios.get('http://localhost:8888/greeting', {
// params: {
// name: 'User'
// }
// }).then(function (response) {
// console.log(response);
// }).catch(function (error) {
// console.log(error);
// }).then(function () {
// }); axios.post('http://localhost:8888/greeting').then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
}).then(function () {
}); axios.post('http://localhost:8888/greeting', {
name: 'User'
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
}).then(function () {
});
</script>
</head>
<body> </body>
</html>

绑定路由的其他方式

@GetMapping("/employees")
@GetMapping("/employees/{id}") @PostMapping("/employees") @PutMapping("/employees/{id}")
@DeleteMapping("/employees/{id}")

springboot成神之——springboot入门使用的更多相关文章

  1. springboot成神之——springboot+mybatis+mysql搭建项目简明demo

    springboot+mybatis+mysql搭建项目简明demo 项目所需目录结构 pom.xml文件配置 application.properties文件配置 MyApplication.jav ...

  2. springboot成神之——ioc容器(依赖注入)

    springboot成神之--ioc容器(依赖注入) spring的ioc功能 文件目录结构 lang Chinese English GreetingService MyRepository MyC ...

  3. springboot成神之——mybatis和mybatis-generator

    项目结构 依赖 generator配置文件 properties配置 生成文件 使用Example 本文讲解如何在spring-boot中使用mybatis和mybatis-generator自动生成 ...

  4. springboot成神之——swagger文档自动生成工具

    本文讲解如何在spring-boot中使用swagger文档自动生成工具 目录结构 说明 依赖 SwaggerConfig 开启api界面 JSR 303注释信息 Swagger核心注释 User T ...

  5. springboot成神之——log4j2的使用

    本文介绍如何在spring-boot中使用log4j2 说明 依赖 日志记录语句 log4j2配置文件 本文介绍如何在spring-boot中使用log4j2 说明 log4j2本身使用是非常简单的, ...

  6. springboot成神之——mybatis在spring-boot中使用的几种方式

    本文介绍mybatis在spring-boot中使用的几种方式 项目结构 依赖 WebConfig DemoApplication 方式一--@Select User DemoApplication ...

  7. springboot成神之——application.properties所有可用属性

    application.properties所有可用属性 # =================================================================== # ...

  8. springboot成神之——websocket发送和请求消息

    本文介绍如何使用websocket发送和请求消息 项目目录 依赖 DemoApplication MessageModel WebConfig WebSocketConfig HttpHandshak ...

  9. springboot成神之——发送邮件

    本文介绍如何用spring发送邮件 目录结构 依赖 MailConfig TestController 测试 本文介绍如何用spring发送邮件 目录结构 依赖 <dependency> ...

随机推荐

  1. python中的mysql操作

    一. 数据库在自动化测试中的应用 存测试数据 有的时候大批量的数据,我们需要存到数据库中,在测试的时候才能用到,测试的时候就从数据库中读取出来.这点是非常重要的! 存测试结果 二. python中的数 ...

  2. pycharm(v 2018.1)新建工程没有导入本地包

    新版的pycharm默认新建的工程Virtualenv(虚拟的环境),在创建环境时一定要注意勾选 Inherit global site-packages: 导入本地包 Make available ...

  3. 三十八 Python分布式爬虫打造搜索引擎Scrapy精讲—elasticsearch(搜索引擎)介绍以及安装

    elasticsearch(搜索引擎)介绍 ElasticSearch是一个基于Lucene的搜索服务器.它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口.Elasticse ...

  4. 【lightoj-1002】Country Roads(dijkstra变形)

    light1002:传送门 [题目大意] n个点m条边,给一个源点,找出源点到其他点的‘最短路’ 定义:找出每条通路中最大的cost,这些最大的cost中找出一个最小的即为‘最短路’,dijkstra ...

  5. 条款11:记得在operator=中处理自赋值的情况。

    本来的版本是这样的: Widget & Widget::operator=(Widget rhs) { delete pb;//这里可能直接将rhs的pb删除了 pb = new (*rhs. ...

  6. 网站 安全 ---- 常见的 web 攻击

    网站 安全 ---- 常见的 web 攻击 1 sql 注入(常用的攻击性)(django的orm是做过sql防护处理的) 危害: 非法读取,篡改,删除数据库中的数据 盗取用户的各类敏感信息.获取利益 ...

  7. Arcgis for javascript map操作addLayer详解

    本节的内容很简单,说说Arcgis for Javascript里面map对象的addLayer方法.在for JS的API中,addLayer方法有两种,如下图: addLayer方法 在addLa ...

  8. lzugis——Arcgis Server for JavaScript API之POI

    POI(Point Of Interest),感兴趣点,其实呢,严格意义上说应该不是POI,但是单位就这样叫了,我也就这样叫了,其实现的功能大致是这样的:用过百度地图的朋友们都知道你在百度地图时,当鼠 ...

  9. 小程序连续点击bug解决

    问题描述: 1)wxml片段 <view bindtap="loadMulti"> <text>连续点击,加载多次</text> </vi ...

  10. LINUX命令—让人喜爱的find

    FIND命令的让人喜爱的地方在于其后面跟着的 –exec  可以执行其他linux命令 这点太让人高兴了,不过他的结尾要带一个特殊的结构 {} \: 说说实例: