SpringMVC通過RESTful結構實現頁面數據交互

需求分析

需求一:圖片列表查詢,從後臺返回數據,將數據展示在頁面上

需求二:新增圖片,將新增圖書的數據傳遞到後臺,並在控制臺打印

說明:此次案例的重點是在SpringMVC中如何使用RESTful實現前後臺交互,所以本案例並沒有和數據庫進行交互,所有數據使用數據來完成開發。

我們的基本步驟:

  • 搭建項目導入jar包
  • 編寫Controller類,提供兩個方法,一個用來做列表查詢,一個用來做新增
  • 在方法上使用RESTful進行路徑設置
  • 完成請求、參數的接收和結果的響應
  • 使用PostMan進行測試
  • 將前端頁面拷貝到項目中
  • 頁面發送ajax請求
  • 完成頁面數據的展示

環境準備

創建一個Web的Maven項目

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>

創建對應的配置類

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數據類型自動轉換
@EnableWebMvc
public class SpringMvcConfig {
}

編寫模型類Book

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

編寫BookController

@Controller
public class BookController {
}

項目結構:

後臺接口開發

步驟1:編寫Controller類並使用RESTful進行配置

@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("計算機");
        book1.setName("SpringMVC入門教程");
        book1.setDescription("小試牛刀");
        bookList.add(book1);
        Book book2 = new Book();
        book2.setType("計算機");
        book2.setName("SpringMVC實戰教程");
        book2.setDescription("一代宗師");
        bookList.add(book2);
        Book book3 = new Book();
        book3.setType("計算機叢書");
        book3.setName("SpringMVC實戰教程進階");
        book3.setDescription("一代宗師嘔心創作");
        bookList.add(book3);
        return bookList;
    }
}

步驟2:使用PostMan進行測試

測試新增

{
    "type":"計算機叢書",
    "name":"SpringMVC終極開發",
    "description":"這是一本好書"
}

測試查詢

頁面訪問處理

步驟1:拷貝靜態頁面

將資料\功能頁面下的所有內容拷貝到項目的webapp目錄下

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

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

(1)出現錯誤的原因?

SpringMVC攔截瞭靜態資源,根據/pages/books.html去controller找對應的方法,找不到所以會報404的錯誤。

(2)SpringMVC為什麼會攔截靜態資源呢?

(3)解決方案?

SpringMVC需要將靜態資源進行放行。

@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
    //設置靜態資源訪問過濾,當前類需要設置為配置類,並被掃描加載
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        //當訪問/pages/????時候,從/pages目錄下查找內容
        registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
        registry.addResourceHandler("/js/**").addResourceLocations("/js/");
        registry.addResourceHandler("/css/**").addResourceLocations("/css/");
        registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
    }
}

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

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

註意:

此處有人可能會想著把SpringMvcSupport配置類上的@Configuration註解給去掉,然後在SpringMvcConfig文件中使用@Import進行引入這樣是不行的!因為這樣的話實際上是讓SpringMvcConfig引入SpringMvcSupport配置類中所有的bean,但是你SpringMvcSupport配置類中就重寫瞭一個方法,壓根就沒有bean。所以不能使用。 例如像下面這種才可以使用:

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

具體的@Import註解使用規則,可以參考下面的鏈接:

@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>
                    <!-- 新增標簽彈層 -->
                    <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: [],//當前頁要展示的分頁列表數據
                formData: {},//表單數據
                dialogFormVisible: false,//增加表單是否可見
                dialogFormVisible4Edit:false,//編輯表單是否可見
                pagination: {},//分頁模型數據,暫時棄用
            },
            //鉤子函數,VUE對象初始化完成後自動執行
            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>

到此這篇關於SpringMVC通過RESTful結構實現頁面數據交互的文章就介紹到這瞭,更多相關SpringMVC RESTful內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: