SpringMVC與前端交互案例教程
一,創(chuàng)建day13的module
選中project-右鍵-new-module-選擇maven-next-輸入module名-finish
二,復(fù)習SpringMVC
–1,需求:訪問/car/get ,獲取汽車數(shù)據(jù)

–2,創(chuàng)建RunApp類
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);
}
}
–3,創(chuàng)建Car類
package cn.tedu.pojo;
//Model用來封裝數(shù)據(jù)
public class Car {
private int id;
private String name;
private double price;
//Constructor構(gòu)造方法,用來方便的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;
}
}
–4,創(chuàng)建CarController類
package cn.tedu.controller;
//MVC里的C層,用來接受請求和做出響應(yīng)(springmvc)
import cn.tedu.pojo.Car;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController//接受請求,并把json數(shù)據(jù)返回
@RequestMapping("car") //規(guī)定了url地址的寫法
public class CarController {
@RequestMapping("get")
public Car get(){
Car c = new Car(10,"BMW",19.9);
return c ;
}
}
三,SpringMVC解析請求參數(shù)
SpringMVC框架,可以自動解析請求中,攜帶的參數(shù)。甚至可以直接封裝成Java對象。而不必自己一個個解析參數(shù)。
–1,普通的GET提交
package cn.tedu.controller;
//MVC里的C層,用來接受請求和做出響應(yīng)(springmvc)
import cn.tedu.pojo.Car;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController//接受請求,并把json數(shù)據(jù)返回
@RequestMapping("car") //規(guī)定了url地址的寫法
public class CarController {
//SpringMVC框架解析請求中的參數(shù)
//http://localhost:8080/car/get5?id=10&name=BMW&price=9.9
@RequestMapping("get5")
public void get5(Car c){//springmvc框架會把請求的參數(shù),封裝給car對象
System.out.println(c.getId()+c.getName()+c.getPrice());
}
//http://localhost:8080/car/get4?id=10&name=BMW
@RequestMapping("get4")
public void get4(Integer id,String name){
//id是用來接受url里id的值,name用來接受url里name的值
System.out.println(id+name);
}
//http://localhost:8080/car/get3?id=10
@RequestMapping("get3")
// public void get3(int id){ //參數(shù)是基本類型,訪問這個方法必須帶參數(shù),否則有異常
public void get3(Integer id){//參數(shù)是引用類型,訪問這個方法沒帶參數(shù)就是null
System.out.println(id);
}
//自己解析請求中的參數(shù)
public void get2(){
String url="http://localhost:8080/car/get2?id=10&name=BMW&price=9.9";
//先按?切出來,取第二部分,再用&切出來參數(shù)名和參數(shù)值[id=10,name=BMW,price=9.9]
String[] s = url.split("\\?")[1].split("&");
for (String ss : s) {
String key = ss.split("=")[0];
String value = ss.split("=")[1] ;
}
}
@RequestMapping("get")
public Car get(){
Car c = new Car(10,"BMW",19.9);
return c ;
}
}
–2,RestFul提交
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;
//對比,請求參數(shù)的不同獲取方式:get/restful
@RestController
@RequestMapping("car2")
public class CarController2 {
//1.普通的get方式獲取請求參數(shù)
//解析參數(shù):http://localhost:8080/car2/get?id=10&name=BMW&age=10&sex=1
@RequestMapping("get")
public String get(Integer id,String name,Integer age,Integer sex){
// return id+name+age+sex ;//直接把結(jié)果展示在瀏覽器上
return "{'id':'"+id+"'}" ;//組織成json串給瀏覽器展示
}
//2.restful方式獲取請求參數(shù):通過{}綁定地址中參數(shù)的位置 + 通過注解獲取{???}的值
//解析參數(shù):http://localhost:8080/car2/get2/10/BMW/10/1
@RequestMapping("get2/{id}/{name}/{x}/{y}")
public void get2(@PathVariable Integer id,
@PathVariable String name,
@PathVariable String x,
@PathVariable Integer y){
System.out.println(id);
System.out.println(name);
System.out.println(x);
System.out.println(y);
}
}
四,簡單的前后端關(guān)聯(lián)
–1,需求
點擊頁面的a,Get方式提交數(shù)據(jù),交給框架解析參數(shù)
–2,創(chuàng)建html頁面
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>用get方式提交數(shù)據(jù)給服務(wù)器</title> </head> <body> <a href="http://localhost:8080/user/save?id=857&name=jack&age=666">點我提交數(shù)據(jù)get</a> <a href="http://localhost:8080/user/save2/857/jack/666">點我提交數(shù)據(jù)restful</a> </body> </html>
–3,創(chuàng)建UserController類,解析參數(shù)
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;
@RestController
@RequestMapping("user")
public class UserController {
//1. 解析get的請求參數(shù) http://localhost:8080/user/save?id=857&name=jack&age=666
@RequestMapping("save")
public void save(Integer id,String name,Integer age){
System.out.println(id+name+age);
}
//2. 解析restful的請求參數(shù) http://localhost:8080/user/save2/857/jack/666
//get和restful的區(qū)別?
//get的好處是數(shù)據(jù)都在地址欄拼接,restful的好處是相對安全
//restful主要是用來優(yōu)化、簡化get提交數(shù)據(jù)的寫法
@RequestMapping("save2/{x}/{y}/{z}")
public void save2(@PathVariable Integer x,
@PathVariable String y,
@PathVariable Integer z){
System.out.println(x+y+z);
}
}
五,利用JDBC技術(shù),把請求參數(shù)入庫

–1,添加jdbc的依賴(修改pom.xml)
<?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>cgb2104boot01</artifactId>
<groupId>cn.tedu</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>day13</artifactId>
<!--添加jar包的依賴-->
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
</dependencies>
</project>
–2,準備user表
CREATE TABLE `user` ( `id` int(3) default NULL, `name` varchar(10) default NULL, `age` int(2) default NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
–3,修改UserController類的save()
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的請求參數(shù) 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);
/* 把解析出來的參數(shù),利用jdbc技術(shù)入庫*/
//注冊驅(qū)動
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(?,?)";//給指定的字段設(shè)置值
String sql= "insert into user values(?,?,?)";//所有字段設(shè)置值
PreparedStatement ps = conn.prepareStatement(sql);
//給SQL設(shè)置參數(shù)
ps.setInt(1,id);//給第一個?設(shè)置值
ps.setString(2,name);//給第二個?設(shè)置值
ps.setInt(3,age);//給第三個?設(shè)置值
//執(zhí)行SQL
int rows = ps.executeUpdate();
//釋放資源 -- OOM(OutOfMemory)
ps.close();
conn.close();
}
//2. 解析restful的請求參數(shù) http://localhost:8080/user/save2/857/jack/666
//get和restful的區(qū)別?
//get的好處是數(shù)據(jù)都在地址欄拼接,restful的好處是相對安全
//restful主要是用來優(yōu)化、簡化get提交數(shù)據(jù)的寫法
@RequestMapping("save2/{x}/{y}/{z}")
public void save2(@PathVariable Integer x,
@PathVariable String y,
@PathVariable Integer z){
System.out.println(x+y+z);
}
}
–4,測試


六、總結(jié)
本篇文章就到這里了,希望能給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
Maven之導(dǎo)入thymeleaf依賴飄紅問題及解決
這篇文章主要介紹了Maven之導(dǎo)入thymeleaf依賴飄紅問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08
mybatisplus where QueryWrapper加括號嵌套查詢方式
這篇文章主要介紹了mybatisplus where QueryWrapper加括號嵌套查詢方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教。2022-01-01
如何使用jenkins實現(xiàn)發(fā)布部分更新文件
這篇文章主要介紹了如何使用jenkins實現(xiàn)發(fā)布部分更新文件,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-07-07
Springmvc 4.x利用@ResponseBody返回Json數(shù)據(jù)的方法
這篇文章主要介紹了Springmvc 4.x利用@ResponseBody返回Json數(shù)據(jù)的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04
spring + shiro + cas 實現(xiàn)sso單點登錄的示例代碼
本篇文章主要介紹了spring + shiro + cas 實現(xiàn)sso單點登錄的示例代碼,具有一定的參考價值,有興趣的可以了解一下2017-09-09
Spring Boot中整合Spring Security并自定義驗證代碼實例
本篇文章主要介紹了Spring Boot中整合Spring Security并自定義驗證代碼實例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04

