springboot2.0學習筆記
經過對springboot的多日學習,其中遇到很多問題,現總結出來以備後查。
1、SpringBoot主啟動類所能掃描到的範圍
SpringBoot主啟動類預設只會掃描自己所在的包及其子包下面,例如主啟動類包在com.meander.boot下面,而自定義的LoginController類放在了com.meander.web.controller中,LoginController是無法訪問的,解決辦法:可以將@SpringBootApplication指定掃描包@SpringBootApplication(scanBasePackages = "com.meander.web"
如需掃描多個包,可以採用如下方式@SpringBootApplication(scanBasePackages = {"com.meander.sys.**.*","com.meander.web"})
package com.meander.boot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class StartMeanderWebApplication { public static void main(String[] args) { SpringApplication.run(StartMeanderWebApplication.class, args); } }
2、使用intelliJ idea開發工具,通過maven多模組構建springboot web工程:
如何使用idea建立maven多模組此處省略...
主要講講其中web子模組:
2.1 首先在maven父pom.xml檔案中新增相關依賴:
pom.xml: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--使用jasper解析jsp --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> <!-- jstl標籤庫 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency>
2.2 配置resources/application.properties
spring.mvc.view.prefix=/WEB-INF/pages/ spring.mvc.view.suffix=.jsp 2.3 編寫的FrontController: import org.springframework.stereotype.Controller; @Controller public class FrontController { @RequestMapping("/toHome") public String toHome() { System.out.println("前置控制器"); return "front/home"; }
2.4 編寫簡單的home.jsp
<%@ page language="java" contentType="text/html;charset=UTF-8" isELIgnored="false" %> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <h1>Welcome to spring boot world!</h1> </body> </html>
maven多模組專案大體結構如下:
執行如下啟動類
package com.meander.boot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication(scanBasePackages = "com.meander") public class StartMeanderWebApplication { public static void main(String[] args) { SpringApplication.run(StartMeanderWebApplication.class, args); } }
開啟瀏覽器訪問http://127.0.0.1:8080/toHome報404,如圖:
嘗試如果把web子模組src/main/webapp目錄放到工程meander-boot目錄下,jsp就能訪問到。這是因為idea預設路徑是工程的路徑而不是模組的路徑 所以導致多模組無法定位到/WEB-INF/pages/index.jsp,而獨立的模組工程路徑就是模組路徑 故可以定位,解決辦法如下下圖,點選idea的“Edit Configurations”,彈出的介面,指定工作路徑working directory為模組的即可,或手工選擇web模組路徑(meander-web)