最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringMVC通過(guò)RESTful結(jié)構(gòu)實(shí)現(xiàn)頁(yè)面數(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ù)接口的場(chǎng)景,實(shí)現(xiàn)第三方OTT調(diào)用移動(dòng)網(wǎng)絡(luò)資源的功能,動(dòng)作類型為新增、變更、刪除所調(diào)用資源

需求分析

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

需求二:新增圖片,將新增圖書的數(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)完成開發(fā)。

我們的基本步驟:

  • 搭建項(xiàng)目導(dǎo)入jar包
  • 編寫Controller類,提供兩個(gè)方法,一個(gè)用來(lái)做列表查詢,一個(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依賴

<?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)的配置類

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)行測(cè)試

測(cè)試新增

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

測(cè)試查詢

頁(yè)面訪問(wèn)處理

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

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

步驟2:訪問(wèn)pages目錄下的books.html

打開瀏覽器輸入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)前類需要設(shè)置為配置類,并被掃描加載
    @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/");
    }
}

該配置類是在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è)方法,壓根就沒(méi)有bean。所以不能使用。 例如像下面這種才可以使用:

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

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

@Import注解詳解

步驟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>圖書管理</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="序號(hào)"></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>
    <!-- 引入組件庫(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è)列表查詢
                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)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • java中的connection reset 異常處理分析

    java中的connection reset 異常處理分析

    本文主要介紹了java中的connection reset 異常處理分析的相關(guān)資料,具有很好的參考價(jià)值。下面跟著小編一起來(lái)看下吧
    2017-04-04
  • java實(shí)現(xiàn)哈夫曼壓縮與解壓縮的方法

    java實(shí)現(xiàn)哈夫曼壓縮與解壓縮的方法

    這篇文章主要介紹了java實(shí)現(xiàn)哈夫曼壓縮與解壓縮的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-10-10
  • struts2入門介紹及代碼實(shí)例

    struts2入門介紹及代碼實(shí)例

    這篇文章主要介紹了struts2入門介紹及代碼實(shí)例,具有一定借鑒價(jià)值,需要的朋友可以參考下。
    2017-12-12
  • Java封裝數(shù)組之改進(jìn)為泛型數(shù)組操作詳解

    Java封裝數(shù)組之改進(jìn)為泛型數(shù)組操作詳解

    這篇文章主要介紹了Java封裝數(shù)組之改進(jìn)為泛型數(shù)組操作,結(jié)合實(shí)例形式詳細(xì)分析了Java封裝數(shù)組為泛型數(shù)組相關(guān)原理、操作技巧與注意事項(xiàng),需要的朋友可以參考下
    2020-03-03
  • java如何刪除非空文件夾

    java如何刪除非空文件夾

    這篇文章主要介紹了java如何刪除非空文件夾問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-06-06
  • MyBatis高級(jí)映射和查詢緩存

    MyBatis高級(jí)映射和查詢緩存

    這篇文章主要介紹了MyBatis高級(jí)映射和查詢緩存的相關(guān)資料,需要的朋友可以參考下
    2016-06-06
  • RocketMQ普通消息實(shí)戰(zhàn)演練詳解

    RocketMQ普通消息實(shí)戰(zhàn)演練詳解

    這篇文章主要為大家介紹了RocketMQ普通消息實(shí)戰(zhàn)演練詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-08-08
  • Java 配置log4j日志文件路徑 (附-獲取當(dāng)前類路徑的多種操作)

    Java 配置log4j日志文件路徑 (附-獲取當(dāng)前類路徑的多種操作)

    這篇文章主要介紹了Java 配置log4j日志文件路徑 (附-獲取當(dāng)前類路徑的多種操作),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-10-10
  • java中LinkedList使用迭代器優(yōu)化移除批量元素原理

    java中LinkedList使用迭代器優(yōu)化移除批量元素原理

    本文主要介紹了java中LinkedList使用迭代器優(yōu)化移除批量元素原理,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-10-10
  • Java常用函數(shù)式接口總結(jié)

    Java常用函數(shù)式接口總結(jié)

    今天給大家?guī)?lái)的是關(guān)于Java的相關(guān)知識(shí),文章圍繞著Java常用函數(shù)式接口展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下
    2021-06-06

最新評(píng)論

原平市| 宣城市| 山阳县| 冷水江市| 宁南县| 四川省| 德江县| 太谷县| 湟中县| 凭祥市| 梓潼县| 江西省| 平阳县| 杨浦区| 延寿县| 清水河县| 区。| 临清市| 宝山区| 荣昌县| 锦州市| 拉孜县| 炉霍县| 丰城市| 呼和浩特市| 新民市| 双柏县| 蓬莱市| 渭源县| 茌平县| 平江县| 和顺县| 双城市| 五常市| 岱山县| 天柱县| 宜兰县| 积石山| 德令哈市| 临颍县| 加查县|