欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringMVC通過RESTful結(jié)構(gòu)實(shí)現(xiàn)頁面數(shù)據(jù)交互

 更新時(shí)間:2022年08月19日 16:53:56   作者:十八歲討厭編程  
RESTFUL是一種網(wǎng)絡(luò)應(yīng)用程序的設(shè)計(jì)風(fēng)格和開發(fā)方式,基于HTTP,可以使用XML格式定義或JSON格式定義。RESTFUL適用于移動(dòng)互聯(lián)網(wǎng)廠商作為業(yè)務(wù)接口的場景,實(shí)現(xiàn)第三方OTT調(diào)用移動(dòng)網(wǎng)絡(luò)資源的功能,動(dòng)作類型為新增、變更、刪除所調(diào)用資源

需求分析

需求一:圖片列表查詢,從后臺(tái)返回?cái)?shù)據(jù),將數(shù)據(jù)展示在頁面上

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

說明:此次案例的重點(diǎn)是在SpringMVC中如何使用RESTful實(shí)現(xiàn)前后臺(tái)交互,所以本案例并沒有和數(shù)據(jù)庫進(jìn)行交互,所有數(shù)據(jù)使用數(shù)據(jù)來完成開發(fā)。

我們的基本步驟:

  • 搭建項(xiàng)目導(dǎo)入jar包
  • 編寫Controller類,提供兩個(gè)方法,一個(gè)用來做列表查詢,一個(gè)用來做新增
  • 在方法上使用RESTful進(jìn)行路徑設(shè)置
  • 完成請求、參數(shù)的接收和結(jié)果的響應(yīng)
  • 使用PostMan進(jìn)行測試
  • 將前端頁面拷貝到項(xiàng)目中
  • 頁面發(fā)送ajax請求
  • 完成頁面數(shù)據(jù)的展示

環(huán)境準(zhǔn)備

創(chuàng)建一個(gè)Web的Maven項(xiàng)目

pom.xml添加Spring依賴

<?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)建對應(yīng)的配置類

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")
//開啟json數(shù)據(jù)類型自動(dòng)轉(zhuǎn)換
@EnableWebMvc
public class SpringMvcConfig {
}

編寫模型類Book

public class Book {
    private Integer id;
    private String type;
    private String name;
    private String description;
    //setter...getter...toString略
}

編寫B(tài)ookController

@Controller
public class BookController {
}

項(xiàng)目結(jié)構(gòu):

后臺(tái)接口開發(fā)

步驟1:編寫Controller類并使用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入門教程");
        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ī)叢書");
        book3.setName("SpringMVC實(shí)戰(zhàn)教程進(jìn)階");
        book3.setDescription("一代宗師嘔心創(chuàng)作");
        bookList.add(book3);
        return bookList;
    }
}

步驟2:使用PostMan進(jìn)行測試

測試新增

{
    "type":"計(jì)算機(jī)叢書",
    "name":"SpringMVC終極開發(fā)",
    "description":"這是一本好書"
}

測試查詢

頁面訪問處理

步驟1:拷貝靜態(tài)頁面

將資料\功能頁面下的所有內(nèi)容拷貝到項(xiàng)目的webapp目錄下

步驟2:訪問pages目錄下的books.html

打開瀏覽器輸入http://localhost/pages/books.html

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

SpringMVC攔截了靜態(tài)資源,根據(jù)/pages/books.html去controller找對應(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)資源訪問過濾,當(dāng)前類需要設(shè)置為配置類,并被掃描加載
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        //當(dāng)訪問/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/");
    }
}

該配置類是在config目錄下,SpringMVC掃描的是controller包,所以該配置類還未生效,要想生效需要將SpringMvcConfig配置類進(jìn)行修改

@Configuration
@ComponentScan({"com.nefu.controller","com.nefu.config"})
@EnableWebMvc
public class SpringMvcConfig {
}
//或者
@Configuration
@ComponentScan("com.nefu")
@EnableWebMvc
public class SpringMvcConfig {
}

注意:

此處有人可能會(huì)想著把SpringMvcSupport配置類上的@Configuration注解給去掉,然后在SpringMvcConfig文件中使用@Import進(jìn)行引入這樣是不行的!因?yàn)檫@樣的話實(shí)際上是讓SpringMvcConfig引入SpringMvcSupport配置類中所有的bean,但是你SpringMvcSupport配置類中就重寫了一個(gè)方法,壓根就沒有bean。所以不能使用。 例如像下面這種才可以使用:

@Configuration
public class ImportedConfig {
   @Bean
   public ImportedBean getImportedBean(){
       return new ImportedBean();
   }
}

具體的@Import注解使用規(guī)則,可以參考下面的鏈接:

@Import注解詳解

步驟3:修改books.html頁面

<!DOCTYPE html>
<html>
    <head>
        <!-- 頁面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>圖書管理</h1>
            </div>
            <div class="app-container">
                <div class="box">
                    <div class="filter-container">
                        <el-input placeholder="圖書名稱" style="width: 200px;" class="filter-item"></el-input>
                        <el-button class="dalfBut">查詢</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="序號"></el-table-column>
                        <el-table-column prop="type" label="圖書類別" align="center"></el-table-column>
                        <el-table-column prop="name" label="圖書名稱" 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="新增圖書" :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="圖書類別" prop="type">
                                            <el-input v-model="formData.type"/>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="圖書名稱" 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>
    <!-- 引入組件庫 -->
    <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)前頁要展示的分頁列表數(shù)據(jù)
                formData: {},//表單數(shù)據(jù)
                dialogFormVisible: false,//增加表單是否可見
                dialogFormVisible4Edit:false,//編輯表單是否可見
                pagination: {},//分頁模型數(shù)據(jù),暫時(shí)棄用
            },
            //鉤子函數(shù),VUE對象初始化完成后自動(dòng)執(zhí)行
            created() {
                this.getAll();
            },
            methods: {
                // 重置表單
                resetForm() {
                    //清空輸入框
                    this.formData = {};
                },
                // 彈出添加窗口
                openSave() {
                    this.dialogFormVisible = true;
                    this.resetForm();
                },
                //添加
                saveBook () {
                    axios.post("/books",this.formData).then((res)=>{
                    });
                },
                //主頁列表查詢
                getAll() {
                    axios.get("/books").then((res)=>{
                        this.dataList = res.data;
                    });
                },
            }
        })
    </script>
</html>

到此這篇關(guān)于SpringMVC通過RESTful結(jié)構(gòu)實(shí)現(xiàn)頁面數(shù)據(jù)交互的文章就介紹到這了,更多相關(guān)SpringMVC RESTful內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • JavaWeb中導(dǎo)出excel文件的簡單方法

    JavaWeb中導(dǎo)出excel文件的簡單方法

    下面小編就為大家?guī)硪黄狫avaWeb中導(dǎo)出excel文件的簡單方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2016-10-10
  • spring cloud 之 Feign 使用HTTP請求遠(yuǎn)程服務(wù)的實(shí)現(xiàn)方法

    spring cloud 之 Feign 使用HTTP請求遠(yuǎn)程服務(wù)的實(shí)現(xiàn)方法

    下面小編就為大家?guī)硪黄猻pring cloud 之 Feign 使用HTTP請求遠(yuǎn)程服務(wù)的實(shí)現(xiàn)方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-06-06
  • Java web spring異步方法實(shí)現(xiàn)步驟解析

    Java web spring異步方法實(shí)現(xiàn)步驟解析

    這篇文章主要介紹了Java web spring異步方法實(shí)現(xiàn)步驟解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-08-08
  • Spring Cloud CLI簡單介紹

    Spring Cloud CLI簡單介紹

    本文我們將介紹Spring Boot Cloud CLI(或簡稱Cloud CLI)。該工具為Spring Boot CLI提供了一組命令行增強(qiáng)功能,有助于進(jìn)一步抽象和簡化Spring Cloud部署。感興趣的小伙伴們可以參考一下
    2018-12-12
  • Java實(shí)現(xiàn)的對稱加密算法3DES定義與用法示例

    Java實(shí)現(xiàn)的對稱加密算法3DES定義與用法示例

    這篇文章主要介紹了Java實(shí)現(xiàn)的對稱加密算法3DES定義與用法,結(jié)合實(shí)例形式簡單分析了Java 3DES加密算法的相關(guān)定義與使用技巧,需要的朋友可以參考下
    2018-04-04
  • httpclient 請求http數(shù)據(jù),json轉(zhuǎn)map的實(shí)例

    httpclient 請求http數(shù)據(jù),json轉(zhuǎn)map的實(shí)例

    下面小編就為大家?guī)硪黄猦ttpclient 請求http數(shù)據(jù),json轉(zhuǎn)map的實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2016-12-12
  • Spring純注解配置實(shí)現(xiàn)代碼示例解析

    Spring純注解配置實(shí)現(xiàn)代碼示例解析

    這篇文章主要介紹了Spring純注解配置實(shí)現(xiàn)代碼示例解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(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)方法

    這篇文章主要介紹了spring-cloud-gateway動(dòng)態(tài)路由的實(shí)現(xiàn)方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-01-01
  • Spring中IOC和AOP的核心組成架構(gòu)詳解

    Spring中IOC和AOP的核心組成架構(gòu)詳解

    這篇文章主要介紹了Spring中IOC和AOP的核心組成架構(gòu)詳解,本文是對Spring的2大核心功能——IoC和AOP 的總結(jié)提煉,并增加了環(huán)境profile和條件化bean的內(nèi)容,篇幅較短,更像是一個(gè)大綱,或者思維導(dǎo)圖,需要的朋友可以參考下
    2023-08-08
  • 一篇文章帶你入門java注解

    一篇文章帶你入門java注解

    這篇文章主要介紹了Java注解詳細(xì)介紹,本文講解了Java注解是什么、Java注解基礎(chǔ)知識、Java注解類型、定義Java注解類型的注意事項(xiàng)等內(nèi)容,需要的朋友可以參考下
    2021-08-08

最新評論