一创建html页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>用get方式提交数据给服务器</title>
</head>
<body>
<a href="http://localhost:8080/user/save?id=857&name=jack&age=666">点我提交数据get</a>
<a href="http://localhost:8080/user/save2/857/jack/666">点我提交数据restful</a>
</body>
</html>
二创建启动类
package cn.tedu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//启动类
@SpringBootApplication
public class RunApp {
public static void main(String[] args) {
SpringApplication.run(RunApp.class);
}
}
三创建car类
package cn.tedu.pojo;
//Model用来封装数据
public class Car {
private int id;
private String name;
private double price;
//Constructor构造方法,用来方便的new
public Car(){}
public Car(int id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
三添加mysql-connector-java的依赖
四创建UserController 类
package cn.tedu.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
@RestController
@RequestMapping("user")
public class UserController {
//1. 解析get的请求参数 http://localhost:8080/user/save?id=857&name=jack&age=666
@RequestMapping("save")
public void save(Integer id,String name,Integer age) throws Exception {
// System.out.println(id+name+age);
/* 把解析出来的参数,利用jdbc技术入库*/
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接
String url ="jdbc:mysql:///cgb2104?characterEncoding=utf8&serverTimezone=Asia/Shanghai";
Connection conn = DriverManager.getConnection(url,"root","root");
//获取传输器
// String sql= "insert into user(id,name) values(?,?)";//给指定的字段设置值
String sql= "insert into user values(?,?,?)";//所有字段设置值
PreparedStatement ps = conn.prepareStatement(sql);
//给SQL设置参数
ps.setInt(1,id);//给第一个?设置值
ps.setString(2,name);//给第二个?设置值
ps.setInt(3,age);//给第三个?设置值
//执行SQL
int rows = ps.executeUpdate();
//释放资源 -- OOM(OutOfMemory)
ps.close();
conn.close();
}
//2. 解析restful的请求参数 http://localhost:8080/user/save2/857/jack/666
//get和restful的区别?
//get的好处是数据都在地址栏拼接,restful的好处是相对安全
//restful主要是用来优化、简化get提交数据的写法
@RequestMapping("save2/{x}/{y}/{z}")
public void save2(@PathVariable Integer x,
@PathVariable String y,
@PathVariable Integer z){
System.out.println(x+y+z);
}
}
五创建表
CREATE TABLE `user` (
`id` int(3) default NULL,
`name` varchar(10) default NULL,
`age` int(2) default NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
————————————————
版权声明:本文为CSDN博主「cgblpx」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u012932876/article/details/117918962