Spring Boot前后端分離直接訪問靜態頁+ajax實現動態網頁。
一般java里面Spring Boot項目的靜態資源resources/下面有兩個文件夾和一個配置文件,分別是static/目錄,templates/目錄,application.properties配置文件。
static/目錄是用來放置純靜態資源,比如js,css,html,圖片,視頻,音頻等;
static/目錄是放置頁面模板,springboot訪問template依靠thymeleaf模板,並且spring.thymeleaf.enabled=true才行。
這里我不想用thymeleaf模板,前后端分離直接訪問靜態頁+ajax實現動態網頁。那么我可以將.html頁面直接放到static/目錄下然后通過Controller訪問。
示例:
package com.xxh.demo.account; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import java.util.ArrayList; @Controller @RequestMapping("/account") public class login { /* 請求響應返回字符串 */ @RequestMapping("/hello") @ResponseBody public String world() { System.out.println("/account/hello > return String Hello world!"); return "Hello world!"; } /* 請求響應返回JSON數據 */ @RequestMapping("/hello2") @ResponseBody public ArrayList world2() { System.out.println("/account/hello2 > return json data."); ArrayList al = new ArrayList<String>(); al.add("曹操"); al.add("劉備"); al.add("孫權"); return al; } /* 請求響應返回/static/下的靜態頁面(需要在 .properties中添加:spring.mvc.static-path-pattern=/static/** ) */ @RequestMapping("/") public String index() { System.out.println("/account/ > /static/index.html"); return "/static/index.html"; } /* 請求響應返回/templates/下的靜態頁面響應404,無法直接訪問 */ @RequestMapping("/index") public String index2() { System.out.println("/account/index > /templates/index.html"); return "/templates/index.html"; } /* 用ModelAndView也可以返回/static/下的靜態頁面(需要在 .properties中添加:spring.mvc.static-path-pattern=/static/** ) */ @RequestMapping("/login") public ModelAndView login() { System.out.println("/account/login > login.html"); ArrayList al = new ArrayList<String>(); al.add("曹操"); al.add("劉備"); al.add("孫權"); ModelAndView mv = new ModelAndView(); mv.setViewName("/static/index.html"); // 這是視圖名稱 或 路徑/視圖名稱 mv.addObject("myEntity", al); // 請求返回實體變量名及實體對象 return mv; } }
同時,要想static下的靜態文件能被訪問,需要在application.properties配置文件里面添加:spring.mvc.static-path-pattern=/static/**
# 應用名稱 spring.application.name=demo # 應用服務 WEB 訪問端口 server.port=8080 # 允許/static/下的靜態資源被訪問,否則404錯誤 spring.mvc.static-path-pattern=/static/**
頁面結構:
訪問效果:
上一篇:idea創建一個入門Spring Boot項目(controller層)使用Maven代碼管理
下一篇:Java一個入門級MVC基於Spring Boot項目
【完】