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

–2,創(chuàng)建RunApp類
package cn.tedu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//啟動(dòng)類
@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層,用來接受請(qǐng)求和做出響應(yīng)(springmvc)
import cn.tedu.pojo.Car;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController//接受請(qǐng)求,并把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解析請(qǐng)求參數(shù)
SpringMVC框架,可以自動(dòng)解析請(qǐng)求中,攜帶的參數(shù)。甚至可以直接封裝成Java對(duì)象。而不必自己一個(gè)個(gè)解析參數(shù)。
–1,普通的GET提交
package cn.tedu.controller;
//MVC里的C層,用來接受請(qǐng)求和做出響應(yīng)(springmvc)
import cn.tedu.pojo.Car;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController//接受請(qǐng)求,并把json數(shù)據(jù)返回
@RequestMapping("car") //規(guī)定了url地址的寫法
public class CarController {
//SpringMVC框架解析請(qǐng)求中的參數(shù)
//http://localhost:8080/car/get5?id=10&name=BMW&price=9.9
@RequestMapping("get5")
public void get5(Car c){//springmvc框架會(huì)把請(qǐng)求的參數(shù),封裝給car對(duì)象
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ù)是基本類型,訪問這個(gè)方法必須帶參數(shù),否則有異常
public void get3(Integer id){//參數(shù)是引用類型,訪問這個(gè)方法沒帶參數(shù)就是null
System.out.println(id);
}
//自己解析請(qǐng)求中的參數(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;
//對(duì)比,請(qǐng)求參數(shù)的不同獲取方式:get/restful
@RestController
@RequestMapping("car2")
public class CarController2 {
//1.普通的get方式獲取請(qǐng)求參數(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方式獲取請(qǐng)求參數(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,需求
點(diǎn)擊頁面的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">點(diǎn)我提交數(shù)據(jù)get</a> <a href="http://localhost:8080/user/save2/857/jack/666">點(diǎn)我提交數(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的請(qǐng)求參數(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的請(qǐng)求參數(shù) http://localhost:8080/user/save2/857/jack/666
//get和restful的區(qū)別?
//get的好處是數(shù)據(jù)都在地址欄拼接,restful的好處是相對(duì)安全
//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ù),把請(qǐng)求參數(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,準(zhǔn)備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的請(qǐng)求參數(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ù)入庫*/
//注冊(cè)驅(qū)動(dòng)
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);//給第一個(gè)?設(shè)置值
ps.setString(2,name);//給第二個(gè)?設(shè)置值
ps.setInt(3,age);//給第三個(gè)?設(shè)置值
//執(zhí)行SQL
int rows = ps.executeUpdate();
//釋放資源 -- OOM(OutOfMemory)
ps.close();
conn.close();
}
//2. 解析restful的請(qǐng)求參數(shù) http://localhost:8080/user/save2/857/jack/666
//get和restful的區(qū)別?
//get的好處是數(shù)據(jù)都在地址欄拼接,restful的好處是相對(duì)安全
//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,測(cè)試


六、總結(jié)
本篇文章就到這里了,希望能給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
Java實(shí)現(xiàn)在線編輯預(yù)覽office文檔詳解
PageOffice是一款在線的office編輯軟件,幫助Web應(yīng)用系統(tǒng)或Web網(wǎng)站實(shí)現(xiàn)用戶在線編輯Word、Excel、PowerPoint文檔,下面我們就來看看如何使用Java實(shí)現(xiàn)在線預(yù)覽office吧2024-01-01
關(guān)于HashMap 并發(fā)時(shí)會(huì)引起死循環(huán)的問題解析
JDK1.8之前采用頭插,即在鏈表結(jié)構(gòu)上每次都把數(shù)據(jù)放在鏈表頭部。JDK1.8采用尾插方法,很多朋友在學(xué)習(xí)Java并發(fā)容器和框架時(shí),看到為什么要使用ConcurrentHashMap時(shí)不知道究其原因,今天小編通過本文給大家介紹下HashMap 并發(fā)死循環(huán)問題,一起看看吧2021-05-05
SpringBoot實(shí)現(xiàn)接口參數(shù)加密解密的示例代碼
加密解密本身并不是難事,問題是在何時(shí)去處理?SpringMVC?中給我們提供了?ResponseBodyAdvice?和?RequestBodyAdvice,利用這兩個(gè)工具可以對(duì)請(qǐng)求和響應(yīng)進(jìn)行預(yù)處理,非常方便。廢話不多說,我們一起來學(xué)習(xí)一下2022-09-09
Windows環(huán)境使用bat腳本啟動(dòng)Java服務(wù)的過程
Java項(xiàng)目一般會(huì)被打包成jar后啟動(dòng),在windows系統(tǒng)中可以通過終端窗口cmd啟動(dòng)jar包,即在jar包所在的目錄中打開cmd,或在cmd中進(jìn)入到j(luò)ar包目錄,這篇文章主要介紹了Windows環(huán)境使用bat腳本啟動(dòng)Java服務(wù),需要的朋友可以參考下2023-08-08
使用IDEA將Java/Kotliin工程導(dǎo)出Jar包的正確姿勢(shì)
這篇文章主要介紹了使用IDEA將Java/Kotliin工程導(dǎo)出Jar包的正確姿勢(shì),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03
全面理解java中的構(gòu)造方法以及this關(guān)鍵字的用法
本篇文章主要概述了如何用構(gòu)造方法初始化對(duì)象,this屬性名訪問成員變量方法,和this()的用法,感興趣的小伙伴一起來學(xué)習(xí)吧2023-03-03

