SpringbBoot學習——2——SpringBoot的Web開發

靜態資源訪問
在我們開發Web應用的時候,需要引用大量的js、css、圖片等靜態資源。
默認配置
Spring Boot默認提供靜態資源目錄位置需置於classpath下,目錄名需符合如下規則:
/static
/public
/resources
/META-INF/resources
舉例:我們可以在src/main/resources/目錄下創建static,在該位置放置一個圖片文件。啓動程序後,嘗試訪問http://localhost:8080/D.jpg。如能顯示圖片,配置成功。
渲染Web頁面
在之前的示例中,我們都是通過@RestController來處理請求,所以返回的內容爲json對象。那麼如果需要渲染html頁面的時候,要如何實現呢?
在動態HTML實現上Spring Boot依然可以完美勝任,並且提供了多種模板引擎的默認配置支持,所以在推薦的模板引擎下,我們可以很快的上手開發動態網站。
Spring Boot提供了默認配置的模板引擎主要有以下幾種:

  1. Thymeleaf
  2. FreeMarker
  3. Velocity
  4. Groovy
  5. Mustache

Spring Boot建議使用這些模板引擎,避免使用JSP,若一定要使用JSP將無法實現Spring Boot的多種特性,具體可見後文:支持JSP的配置
當你使用上述模板引擎中的任何一個,它們默認的模板配置路徑爲:src/main/resources/templates。當然也可以修改這個路徑,具體如何修改,可在後續各模板引擎的配置屬性中查詢並修改。
使用JSP渲染Web視圖
pom文件引入以下依賴:

<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
	</parent>
	<dependencies>
		<!-- SpringBoot web 核心組件 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
		</dependency>
	<!-- SpringBoot 外部tomcat支持 -->	
	<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-jasper</artifactId>
		</dependency>
	</dependencies>

在application.properties創建以下配置:

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

後臺代碼

public class IndexController {
	@RequestMapping("/index")
	public String index() {
		return "index";
	}
}

注意:創建SpringBoot整合JSP,一定要爲war類型,否則會找不到頁面.
不要把JSP頁面存放在resources/jsp 不能被訪問到,jsp頁面應該放到src/main/webapp/WEB-INF 目錄下
全局捕獲異常
下面先解釋一下幾個註解作用:
@ExceptionHandler 表示攔截異常

  • @ControllerAdvice 是 controller 的一個輔助類,最常用的就是作爲全局異常處理的切面類
  • @ControllerAdvice 可以指定掃描範圍
  • @ControllerAdvice 約定了幾種可行的返回值,如果是直接返回 model 類的話,需要使用 @ResponseBody 進行 json 轉換
  • 返回 String,表示跳到某個 view
  • 返回 modelAndView
  • 返回 model + @ResponseBody
@ControllerAdvice
public class GlobalExceptionHandler {
	@ExceptionHandler(RuntimeException.class)
	@ResponseBody
	public Map<String, Object> exceptionHandler() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("errorCode", "101");
		map.put("errorMsg", "系統錯誤!");
		return map;
	}
}

在程序運行過程中,當系統出現錯誤時,頁面不會報系統的400,404,500等錯誤,會返回上述代碼定義的兩個錯誤字段。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章