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文件的格式
[email protected]@
[email protected]@
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/#/
web service访问数据库
配置你的pom.xml文件
<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>
<groupId>jky.yjw</groupId>
<artifactId>FirstMaven</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>我的第一个Maven</name>
<description>我的第一个Maven</description>
<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>
<dependencies>
<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>
<!-- Use MySQL Connector-J -->
<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>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
<includes>
<include>**/*Test.java</include>
</includes>
<excludes>
<exclude>**/*TestCase.java</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.3</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>2.7</version>
</plugin>
<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>
</plugins>
</build>
</project>
配置文件
application.properties
# application.properties
[email protected]@
[email protected]@
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}")