最近要把一個spirngboot項目和vue整合一下。於是百度了一下,大部分的教程都是build前端vue項目,然後把生成的dist目錄下的文件拷貝到resources下的static下即可,但是按照以上教程實際上項目啓動後無法正常訪問。在摸索了一段時間之後,總結如下,
首先看下整合後的目錄結構
之後我們看下具體的教程步驟
編譯前端工程
使用下面命令編譯vue工程
npm run build
編譯後文件目錄如下
拷貝文件到springboot目錄
將static下是css、fonts、img、js拷貝到springboot項目的/resources/static目錄下
將index.html文件拷貝到springboot項目的/resources/templates目錄下
新增IndexController
@Controller
@RequestMapping("")
public class IndexController {
@RequestMapping("/index")
public String index() {
return "index";
}
}
此controller的作用是在訪問項目的/index路勁時,能夠跳轉到index.html
新增靜態資源映射
@Configuration
public class MvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
}
這樣就能解決靜態資源無法訪問的問題
啓動springboot項目
在上述步驟都完成之後,啓動springboot項目。以本地爲例,瀏覽器訪問http://localhost:8080/index即可