Day15 get/post方式提交数据

一,练习:GET方式提交的数据
–1,需求:http://localhost:8080/user/add?id=100&name=jack&pwd=123
把地址栏里的数据,解析成功,并存入数据库中(入库)
–2,创建RunApp.java
package cn.tedu;

		import org.springframework.boot.SpringApplication;
		import org.springframework.boot.autoconfigure.SpringBootApplication;

		//用来启动springboot程序
		@SpringBootApplication
		public class RunApp {
		    public static void main(String[] args) {
		        SpringApplication.run(RunApp.class);
		    }
		}

--3,创建User.java
		package cn.tedu.pojo;
		//MVC里的Model
		public class User {
		    private int id ;
		    private String name ;
		    private String pwd ;

		    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 String getPwd() {
		        return pwd;
		    }

		    public void setPwd(String pwd) {
		        this.pwd = pwd;
		    }

		    @Override
		    public String toString() {
		        return "User{" +
		                "id=" + id +
		                ", name='" + name + '\'' +
		                ", pwd='" + pwd + '\'' +
		                '}';
		    }
		}

--5,修改pom.xml添加jdbc依赖包
		<?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">
		    <parent>
		        <artifactId>springbootcgb2103</artifactId>
		        <groupId>cn.tedu</groupId>
		        <version>0.0.1-SNAPSHOT</version>
		    </parent>
		    <modelVersion>4.0.0</modelVersion>

		    <artifactId>springmvc02</artifactId>

		    <!--使用jdbc,需要导入jar包-->
		    <dependencies>
		        <dependency>
		            <groupId>mysql</groupId>
		            <artifactId>mysql-connector-java</artifactId>
		            <version>5.1.48</version>
		        </dependency>
		    </dependencies>
		</project>
--4,创建UserController.java
		package cn.tedu.controller;
		import cn.tedu.pojo.User;
		import org.springframework.web.bind.annotation.RequestMapping;
		import org.springframework.web.bind.annotation.RestController;
		import javax.sound.midi.Soundbank;
		import java.sql.Connection;
		import java.sql.DriverManager;
		import java.sql.PreparedStatement;

		//接受浏览器发来的请求
		@RestController
		@RequestMapping("/user")
		public class UserController {
				//测试:http://localhost:8080/user/add/id=100&name=jack&pwd=123456
		    @RequestMapping("/add")
		    public void add(User user) throws Exception {
		        //User{id=100, name='jack', pwd='123456'}
		        System.out.println(user);
		        //jdbc入库 -- 在pom.xml添加jar包的依赖
		        //获取驱动
		        Class.forName("com.mysql.jdbc.Driver");
		        //获取数据库的连接
		        String url="jdbc:mysql://localhost:3306/cgb2103" +
		                    "?characterEncoding=utf8" +
		                    "&serverTimezone=Asia/Shanghai" ;
		        String username="root" ;
		        String password="root" ;
		        Connection conn = DriverManager.getConnection(url,username,password);
		        //获取传输器
		        String sql = "insert into user values(?,?,?)" ;
		        PreparedStatement ps  = conn.prepareStatement(sql);
		        //给SQL设置参数
		        ps.setInt(1,user.getId());
		        ps.setString(2,user.getName());
		        ps.setString(3,user.getPwd());
		        //执行SQL
		        int rows = ps.executeUpdate();
		        System.out.println(rows);
		        System.out.println("插入成功!");
		    }
		}

二,解析POST方式提交的数据
–1,说明:把要给服务器发送的数据后台拼接,安全,数据没有大小的限制
–2,代码:
–创建stutest.html文件(在HBuilder里)
package cn.tedu.pojo;

			import org.springframework.format.annotation.DateTimeFormat;

			import java.util.Arrays;
			import java.util.Date;
			//封装网页中发来的数据
			public class Student {
			    private String user;//封装网页中输入的用户
			    private int age;//封装网页中输入的年龄
			    private int sex;//封装网页中选择的性别
			    private String[] hobby;
			    //封装网页中选择的多个爱好
			    private int edu;//封装网页中选择的学历

			 //格式化日期的:浏览器上选择的日期是string类型,要转成Date类型就要用注解,否则页面400
			    @DateTimeFormat(pattern = "yyyy-MM-dd")
			    private Date intime;//封装网页中填的日期
			    //提供 set/get 和 toString
			    public String getUser() {
			        return user;
			    }

			    public void setUser(String user) {
			        this.user = user;
			    }

			    public int getAge() {
			        return age;
			    }

			    public void setAge(int age) {
			        this.age = age;
			    }

			    public int getSex() {
			        return sex;
			    }

			    public void setSex(int sex) {
			        this.sex = sex;
			    }

			    public String[] getHobby() {
			        return hobby;
			    }

			    public void setHobby(String[] hobby) {
			        this.hobby = hobby;
			    }

			    public int getEdu() {
			        return edu;
			    }

			    public void setEdu(int edu) {
			        this.edu = edu;
			    }

			    public Date getIntime() {
			        return intime;
			    }

			    public void setIntime(Date intime) {
			        this.intime = intime;
			    }

			    @Override
			    public String toString() {
			        return "Student{" +
			                "user='" + user + '\'' +
			                ", age=" + age +
			                ", sex=" + sex +
			                ", hobby=" + Arrays.toString(hobby) +
			                ", edu=" + edu +
			                ", intime=" + intime +
			                '}';
			    }
			}

	--创建StudentController.java文件(在IDEA里)
			package cn.tedu.controller;

			import cn.tedu.pojo.Student;
			import org.springframework.web.bind.annotation.RequestMapping;
			import org.springframework.web.bind.annotation.RestController;

			//接受浏览器发来的数据
			@RestController
			@RequestMapping("/stu")
			public class StuController {
			    //接受浏览器里form里提交的数据
			    @RequestMapping("/add")
			    public void add(Student s){
			        System.out.println(s);
			    }
			}


--3,改造成ajax提交数据
	--改造stutest.html文件(在HBuilder里)
		<!DOCTYPE html>
		<html>
			<head>
				<meta charset="utf-8">
				<title>测试 前后端 连接</title>
				
				<!-- 在HTML中嵌入css代码 -->
				<style>
					input[type='text']{
						width: 300px;
						height: 30px;
					}
				</style>
				
				<!-- 引入jQuery -->
				<script src="js/jquery-1.8.3.min.js"></script>
				<!-- ajax异步访问局部刷新,经常用!! -->
				<script>
					function sub(){
						$.ajax({
							type: "POST" , 
		// 'http://localhost:8080/stu/add' from origin 'http://127.0.0.1:8848' has been blocked by CORS policy: No 'Access-Control-Allow-Origin'
							url: "https://localhost:8080/stu/add" , 
							data: $("#form1").serialize() , //把表单里的所有数据变成串提交给服务器
							dataType: "json" ,
							success: function(data){ 
								console.log(data);
							}
						});
					}
				</script>
			</head>
			<body style="margin: 100px;">
				<form method="post" action="#" id="form1">
					<table>
						<h2>学生信息管理系统MIS</h2>
						<tr>
							<td>姓名:</td>
						</tr>
						<tr>
							<td>
								<input type="text" name="user" placeholder="请输入姓名..."/>
							</td>
						</tr>
						<tr>
							<td>年龄:</td>
						</tr>
						<tr>
							<td>
								<input type="text" name="age"  placeholder="请输入年龄..."/>
							</td>
						</tr>
						<tr>
							<td>
								性别:(单选框)
								<input type="radio"  name="sex" value="1" checked="checked"/>男
								<input type="radio"  name="sex" value="0"  />女
							</td>
						</tr>
						<tr>
							<td>
								爱好:(多选)
								<input type="checkbox"  name="hobby" value="ppq"   checked="checked"/>乒乓球
								<input type="checkbox"  name="hobby"  value="ps" />爬山
								<input type="checkbox"  name="hobby" value="cg"  />唱歌
							</td>
						</tr>
						<tr>
							<td>
								学历:(下拉框)
								<select   name="edu">
									<option value="0">本科</option>
									<option value="1">专科</option>
									<option value="2">研究生</option>
									<option value="3">博士</option>
								</select>
							</td>
						</tr>
						<tr>
							<td>
								入学日期: <br />
								<input type="date"  name="intime"/>
							</td>
						</tr>
						<tr>
							<td>
								<input type="button" onclick="sub();" value="保存" style="background-color: blue;color: white;border: blue;width: 50px;height: 30px;"/>
								<input type="reset" value="取消" style="background-color: palevioletred;color: white;border: blue;width: 50px;height: 30px;"/>
							</td>
						</tr>
					</table>
				</form>
			</body>
		</html>
	--创建StudentController.java文件(在IDEA里)
		--只在StudentController的类上加一个注解
			@CrossOrigin(origins = "*") //解决跨域问题,放行所有请求

上一篇:每日一题 | day15( 查找输入整数二进制中1的个数 | 手套)


下一篇:jQuery Ajax 操作函数及deferred对象