SpringMVC通過(guò)RESTful結(jié)構(gòu)實(shí)現(xiàn)頁(yè)面數(shù)據(jù)交互
需求分析
需求一:圖片列表查詢(xún),從后臺(tái)返回?cái)?shù)據(jù),將數(shù)據(jù)展示在頁(yè)面上

需求二:新增圖片,將新增圖書(shū)的數(shù)據(jù)傳遞到后臺(tái),并在控制臺(tái)打印

說(shuō)明:此次案例的重點(diǎn)是在SpringMVC中如何使用RESTful實(shí)現(xiàn)前后臺(tái)交互,所以本案例并沒(méi)有和數(shù)據(jù)庫(kù)進(jìn)行交互,所有數(shù)據(jù)使用假數(shù)據(jù)來(lái)完成開(kāi)發(fā)。
我們的基本步驟:
- 搭建項(xiàng)目導(dǎo)入jar包
- 編寫(xiě)Controller類(lèi),提供兩個(gè)方法,一個(gè)用來(lái)做列表查詢(xún),一個(gè)用來(lái)做新增
- 在方法上使用RESTful進(jìn)行路徑設(shè)置
- 完成請(qǐng)求、參數(shù)的接收和結(jié)果的響應(yīng)
- 使用PostMan進(jìn)行測(cè)試
- 將前端頁(yè)面拷貝到項(xiàng)目中
- 頁(yè)面發(fā)送ajax請(qǐng)求
- 完成頁(yè)面數(shù)據(jù)的展示
環(huán)境準(zhǔn)備
創(chuàng)建一個(gè)Web的Maven項(xiàng)目
pom.xml添加Spring依賴(lài)
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.nefu</groupId>
<artifactId>springmvc_try</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<port>80</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>創(chuàng)建對(duì)應(yīng)的配置類(lèi)
public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class[0];
}
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
protected String[] getServletMappings() {
return new String[]{"/"};
}
//亂碼處理
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
return new Filter[]{filter};
}
}
@Configuration
@ComponentScan("com.nefu.controller")
//開(kāi)啟json數(shù)據(jù)類(lèi)型自動(dòng)轉(zhuǎn)換
@EnableWebMvc
public class SpringMvcConfig {
}編寫(xiě)模型類(lèi)Book
public class Book {
private Integer id;
private String type;
private String name;
private String description;
//setter...getter...toString略
}編寫(xiě)B(tài)ookController
@Controller
public class BookController {
}項(xiàng)目結(jié)構(gòu):

后臺(tái)接口開(kāi)發(fā)
步驟1:編寫(xiě)Controller類(lèi)并使用RESTful進(jìn)行配置
@RestController
@RequestMapping("/books")
public class BookController {
@PostMapping
public String save(@RequestBody Book book){
System.out.println("book save ==> "+ book);
return "{'module':'book save success'}";
}
@GetMapping
public List<Book> getAll(){
System.out.println("book getAll is running ...");
List<Book> bookList = new ArrayList<Book>();
Book book1 = new Book();
book1.setType("計(jì)算機(jī)");
book1.setName("SpringMVC入門(mén)教程");
book1.setDescription("小試牛刀");
bookList.add(book1);
Book book2 = new Book();
book2.setType("計(jì)算機(jī)");
book2.setName("SpringMVC實(shí)戰(zhàn)教程");
book2.setDescription("一代宗師");
bookList.add(book2);
Book book3 = new Book();
book3.setType("計(jì)算機(jī)叢書(shū)");
book3.setName("SpringMVC實(shí)戰(zhàn)教程進(jìn)階");
book3.setDescription("一代宗師嘔心創(chuàng)作");
bookList.add(book3);
return bookList;
}
}步驟2:使用PostMan進(jìn)行測(cè)試
測(cè)試新增
{
"type":"計(jì)算機(jī)叢書(shū)",
"name":"SpringMVC終極開(kāi)發(fā)",
"description":"這是一本好書(shū)"
}

測(cè)試查詢(xún)

頁(yè)面訪問(wèn)處理
步驟1:拷貝靜態(tài)頁(yè)面
將資料\功能頁(yè)面下的所有內(nèi)容拷貝到項(xiàng)目的webapp目錄下

步驟2:訪問(wèn)pages目錄下的books.html
打開(kāi)瀏覽器輸入http://localhost/pages/books.html

(1)出現(xiàn)錯(cuò)誤的原因?

SpringMVC攔截了靜態(tài)資源,根據(jù)/pages/books.html去controller找對(duì)應(yīng)的方法,找不到所以會(huì)報(bào)404的錯(cuò)誤。
(2)SpringMVC為什么會(huì)攔截靜態(tài)資源呢?

(3)解決方案?
SpringMVC需要將靜態(tài)資源進(jìn)行放行。
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
//設(shè)置靜態(tài)資源訪問(wèn)過(guò)濾,當(dāng)前類(lèi)需要設(shè)置為配置類(lèi),并被掃描加載
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
//當(dāng)訪問(wèn)/pages/????時(shí)候,從/pages目錄下查找內(nèi)容
registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
}
}該配置類(lèi)是在config目錄下,SpringMVC掃描的是controller包,所以該配置類(lèi)還未生效,要想生效需要將SpringMvcConfig配置類(lèi)進(jìn)行修改
@Configuration
@ComponentScan({"com.nefu.controller","com.nefu.config"})
@EnableWebMvc
public class SpringMvcConfig {
}
//或者
@Configuration
@ComponentScan("com.nefu")
@EnableWebMvc
public class SpringMvcConfig {
}
注意:
此處有人可能會(huì)想著把SpringMvcSupport配置類(lèi)上的@Configuration注解給去掉,然后在SpringMvcConfig文件中使用@Import進(jìn)行引入這樣是不行的!因?yàn)檫@樣的話實(shí)際上是讓SpringMvcConfig引入SpringMvcSupport配置類(lèi)中所有的bean,但是你SpringMvcSupport配置類(lèi)中就重寫(xiě)了一個(gè)方法,壓根就沒(méi)有bean。所以不能使用。 例如像下面這種才可以使用:
@Configuration
public class ImportedConfig {
@Bean
public ImportedBean getImportedBean(){
return new ImportedBean();
}
}
具體的@Import注解使用規(guī)則,可以參考下面的鏈接:
步驟3:修改books.html頁(yè)面
<!DOCTYPE html>
<html>
<head>
<!-- 頁(yè)面meta -->
<meta charset="utf-8">
<title>SpringMVC案例</title>
<!-- 引入樣式 -->
<link rel="stylesheet" href="../plugins/elementui/index.css" rel="external nofollow" >
<link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css" rel="external nofollow" >
<link rel="stylesheet" href="../css/style.css" rel="external nofollow" >
</head>
<body class="hold-transition">
<div id="app">
<div class="content-header">
<h1>圖書(shū)管理</h1>
</div>
<div class="app-container">
<div class="box">
<div class="filter-container">
<el-input placeholder="圖書(shū)名稱(chēng)" style="width: 200px;" class="filter-item"></el-input>
<el-button class="dalfBut">查詢(xún)</el-button>
<el-button type="primary" class="butT" @click="openSave()">新建</el-button>
</div>
<el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row>
<el-table-column type="index" align="center" label="序號(hào)"></el-table-column>
<el-table-column prop="type" label="圖書(shū)類(lèi)別" align="center"></el-table-column>
<el-table-column prop="name" label="圖書(shū)名稱(chēng)" align="center"></el-table-column>
<el-table-column prop="description" label="描述" align="center"></el-table-column>
<el-table-column label="操作" align="center">
<template slot-scope="scope">
<el-button type="primary" size="mini">編輯</el-button>
<el-button size="mini" type="danger">刪除</el-button>
</template>
</el-table-column>
</el-table>
<div class="pagination-container">
<el-pagination
class="pagiantion"
@current-change="handleCurrentChange"
:current-page="pagination.currentPage"
:page-size="pagination.pageSize"
layout="total, prev, pager, next, jumper"
:total="pagination.total">
</el-pagination>
</div>
<!-- 新增標(biāo)簽彈層 -->
<div class="add-form">
<el-dialog title="新增圖書(shū)" :visible.sync="dialogFormVisible">
<el-form ref="dataAddForm" :model="formData" :rules="rules" label-position="right" label-width="100px">
<el-row>
<el-col :span="12">
<el-form-item label="圖書(shū)類(lèi)別" prop="type">
<el-input v-model="formData.type"/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="圖書(shū)名稱(chēng)" prop="name">
<el-input v-model="formData.name"/>
</el-form-item>
</el-col>
</el-row>
<el-row>
<el-col :span="24">
<el-form-item label="描述">
<el-input v-model="formData.description" type="textarea"></el-input>
</el-form-item>
</el-col>
</el-row>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false">取消</el-button>
<el-button type="primary" @click="saveBook()">確定</el-button>
</div>
</el-dialog>
</div>
</div>
</div>
</div>
</body>
<!-- 引入組件庫(kù) -->
<script src="../js/vue.js"></script>
<script src="../plugins/elementui/index.js"></script>
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script src="../js/axios-0.18.0.js"></script>
<script>
var vue = new Vue({
el: '#app',
data:{
dataList: [],//當(dāng)前頁(yè)要展示的分頁(yè)列表數(shù)據(jù)
formData: {},//表單數(shù)據(jù)
dialogFormVisible: false,//增加表單是否可見(jiàn)
dialogFormVisible4Edit:false,//編輯表單是否可見(jiàn)
pagination: {},//分頁(yè)模型數(shù)據(jù),暫時(shí)棄用
},
//鉤子函數(shù),VUE對(duì)象初始化完成后自動(dòng)執(zhí)行
created() {
this.getAll();
},
methods: {
// 重置表單
resetForm() {
//清空輸入框
this.formData = {};
},
// 彈出添加窗口
openSave() {
this.dialogFormVisible = true;
this.resetForm();
},
//添加
saveBook () {
axios.post("/books",this.formData).then((res)=>{
});
},
//主頁(yè)列表查詢(xún)
getAll() {
axios.get("/books").then((res)=>{
this.dataList = res.data;
});
},
}
})
</script>
</html>到此這篇關(guān)于SpringMVC通過(guò)RESTful結(jié)構(gòu)實(shí)現(xiàn)頁(yè)面數(shù)據(jù)交互的文章就介紹到這了,更多相關(guān)SpringMVC RESTful內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringMVC使用RESTful接口案例詳解
- SpringMVC?Restful風(fēng)格與中文亂碼問(wèn)題解決方案介紹
- SpringMVC?RESTFul及REST架構(gòu)風(fēng)格介紹
- SpringMVC?RESTFul實(shí)體類(lèi)創(chuàng)建及環(huán)境搭建
- SpringMVC?RESTFul實(shí)戰(zhàn)案例訪問(wèn)首頁(yè)
- SpringMVC?RESTFul實(shí)現(xiàn)列表功能
- SpringMVC?RESTFul實(shí)戰(zhàn)案例刪除功能實(shí)現(xiàn)
- SpringMVC使用RESTful接口案例
相關(guān)文章
JavaWeb中導(dǎo)出excel文件的簡(jiǎn)單方法
下面小編就為大家?guī)?lái)一篇JavaWeb中導(dǎo)出excel文件的簡(jiǎn)單方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-10-10
spring cloud 之 Feign 使用HTTP請(qǐng)求遠(yuǎn)程服務(wù)的實(shí)現(xiàn)方法
下面小編就為大家?guī)?lái)一篇spring cloud 之 Feign 使用HTTP請(qǐng)求遠(yuǎn)程服務(wù)的實(shí)現(xiàn)方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-06-06
Java web spring異步方法實(shí)現(xiàn)步驟解析
這篇文章主要介紹了Java web spring異步方法實(shí)現(xiàn)步驟解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08
Java實(shí)現(xiàn)的對(duì)稱(chēng)加密算法3DES定義與用法示例
這篇文章主要介紹了Java實(shí)現(xiàn)的對(duì)稱(chēng)加密算法3DES定義與用法,結(jié)合實(shí)例形式簡(jiǎn)單分析了Java 3DES加密算法的相關(guān)定義與使用技巧,需要的朋友可以參考下2018-04-04
httpclient 請(qǐng)求http數(shù)據(jù),json轉(zhuǎn)map的實(shí)例
下面小編就為大家?guī)?lái)一篇httpclient 請(qǐng)求http數(shù)據(jù),json轉(zhuǎn)map的實(shí)例。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-12-12
Spring純注解配置實(shí)現(xiàn)代碼示例解析
這篇文章主要介紹了Spring純注解配置實(shí)現(xiàn)代碼示例解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08
spring-cloud-gateway動(dòng)態(tài)路由的實(shí)現(xiàn)方法
這篇文章主要介紹了spring-cloud-gateway動(dòng)態(tài)路由的實(shí)現(xiàn)方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01

