1. 程式人生 > >SpringBoot 2.0入門(1)

SpringBoot 2.0入門(1)

1.在eclipse中建立一個Maven工程

在這裡插入圖片描述

建立名為”helloworld” 型別為Jar工程專案。

2.pom檔案引入依賴

在pom中加入如下程式碼:

<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
	</parent>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies> 

1)spring-boot-starter-parent作用
在pom.xml中引入spring-boot-start-parent,spring官方的解釋是stater poms,它可以提供dependency management,也就是說依賴管理,引入以後在申明其它dependency的時候就不需要version了,後面可以看到。

2)spring-boot-starter-web作用
springweb 核心元件

3)spring-boot-maven-plugin作用
如果我們要直接Main啟動spring,那麼以下plugin必須要新增,否則是無法啟動的。如果使用maven 的spring-boot:run的話是不需要此配置的。(我在測試的時候,如果不配置下面的plugin也是直接在Main中執行的。)

3.編寫HelloWorld服務

建立package命名為com.itma.controller(根據實際情況修改)
建立HelloController類,內容如下

@RestController
@EnableAutoConfiguration
public class HelloController {
	@RequestMapping("/hello")
	public String index() {
		return "Hello World";
	}	
	public static void main(String[] args) {
		SpringApplication.run(HelloController.class, args);
	}

	
}

執行程式Run as java application,Springboot預設埠號為8080,我們在瀏覽器訪問http://192.168.3.127:8080/hello (以我的電腦的IP地址為例)

在這裡插入圖片描述
可以看到就顯示出了我們在方法中寫的內容。

上面的例子中,我們涉及到了以下幾個知識點
1)@RestController
加上RestController 表示修飾該Controller所有的方法返回JSON格式,直接可以編寫
Restful介面

2)@EnableAutoConfiguration
註解:作用在於讓 Spring Boot 根據應用所宣告的依賴來對 Spring 框架進行自動配置
這個註解告訴Spring Boot根據新增的jar依賴猜測你想如何配置Spring。由於spring-boot-starter-web添加了Tomcat和Spring MVC,所以auto-configuration將假定你正在開發一個web應用並相應地對Spring進行設定。

3)SpringApplication.run(HelloController.class, args);
將一個類標識為啟動類

4.SpringBoot的幾種啟動方式

4.1使用SpringApplication.run將一個類標識為啟動類
再次貼出上面例子中的程式碼

@RestController
@EnableAutoConfiguration
public class HelloController {
	@RequestMapping("/hello")
	public String index() {
		return "Hello World";
	}	
public static void main(String[] args) {
		SpringApplication.run(HelloController.class, args);
	}
}

4.2 宣告application,並通過@ComponentScan註解宣告控制器掃包範圍
我們在com.itma包路徑下建立一個App.java類

@ComponentScan(basePackages = "com.itma.controller")
@EnableAutoConfiguration
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}

}

@ComponentScan註解用於宣告控制器掃包範圍

在com.itma.controller下新建一個HelloController2

@RestController
@EnableAutoConfiguration
public class HelloController2 {
	@RequestMapping("/hello2")
	public String index() {
		return "Hello World 2222";
	}	
	
	
}

執行專案,訪問 http://192.168.3.127:8080/hello2,會列印Hello World 2222

4.3 宣告@SpringBootApplication註解
@SpringBootApplication 被 @Configuration、@EnableAutoConfiguration、@ComponentScan 註解所修飾,換言之 Springboot 提供了統一的註解來替代以上三個註解
掃包範圍:在啟動類上加上@SpringBootApplication註解,當前包下或者子包下所有的類都可以掃到。

@SpringBootApplication
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}

}

5.靜態資源訪問

在我們開發Web應用的時候,需要引用大量的js、css、圖片等靜態資源。
預設配置
Spring Boot預設提供靜態資源目錄位置需置於classpath下,目錄名需符合如下規則:
/static
/public
/resources
/META-INF/resources
舉例:我們可以在src/main/resources/目錄下建立static,在該位置放置一個圖片檔案。啟動程式後,嘗試訪問http://域名/Test.jpg。如能顯示圖片,配置成功。
在這裡插入圖片描述

6.渲染Web頁面

在之前的示例中,我們都是通過@RestController來處理請求,所以返回的內容為json物件。那麼如果需要渲染html頁面的時候,要如何實現呢?

6.1模板引擎
在動態HTML實現上Spring Boot依然可以完美勝任,並且提供了多種模板引擎的預設配置支援,所以在推薦的模板引擎下,我們可以很快的上手開發動態網站。
Spring Boot提供了預設配置的模板引擎主要有以下幾種:

•	Thymeleaf
•	FreeMarker
•	Velocity
•	Groovy
•	Mustache

Spring Boot建議使用這些模板引擎,避免使用JSP,若一定要使用JSP將無法實現Spring Boot的多種特性,具體可見後文:支援JSP的配置
當你使用上述模板引擎中的任何一個,它們預設的模板配置路徑為:src/main/resources/templates。當然也可以修改這個路徑,具體如何修改,可在後續各模板引擎的配置屬性中查詢並修改。

7.使用Freemarker模板引擎渲染web檢視

7.1pom檔案引入

<!-- 引入freeMarker的依賴包. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

7.2後臺程式碼
在src/main/resources/建立一個templates資料夾,字尾為*.ftl

@RequestMapping("/index")
	public String index(Map<String, Object> map) {
	    map.put("name","美麗的天使...");
		return "index";
	}

7.3前臺程式碼

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
	  ${name}
</body> 
</html>

7.4 Freemarker其他用法

後臺程式碼

@RequestMapping("/freemarkerIndex")
	public String index(Map<String, Object> result) {
		result.put("name", "yushengjun");
		result.put("sex", "0");
		List<String> listResult = new ArrayList<String>();
		listResult.add("zhangsan");
		listResult.add("lisi");
		listResult.add("itmayiedu");
		result.put("listResult", listResult);
		return "index";
	}

前臺程式碼

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title>首頁</title>
</head>
<body>
	  ${name}
<#if sex=="1">
            男
      <#elseif sex=="2">
            女
     <#else>
        其他      
	  
	  </#if>	  
	 <#list userlist as user>
	   ${user}
	 </#list>
</body> 
</html>

7.5 Freemarker配置
新建application.properties檔案

########################################################
###FREEMARKER (FreeMarkerAutoConfiguration)
########################################################
spring.freemarker.allow-request-override=false
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
#spring.freemarker.prefix=
#spring.freemarker.request-context-attribute=
#spring.freemarker.settings.*=
spring.freemarker.suffix=.ftl
spring.freemarker.template-loader-path=classpath:/templates/
#comma-separated list
#spring.freemarker.view-names= # whitelist of view names that can be resolved

8.使用JSP渲染Web檢視
8.1 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>

8.2 在application.properties建立以下配置

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

後臺程式碼

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

注意:建立SpringBoot整合JSP,一定要為war型別,否則會找不到頁面.
不要把JSP頁面存放在resources// jsp 不能被訪問到
在這裡插入圖片描述

9.全域性捕獲異常

@ExceptionHandler 表示攔截異常
•	@ControllerAdvice 是 controller 的一個輔助類,最常用的就是作為全域性異常處理的切面類
•	@ControllerAdvice 可以指定掃描範圍
•	@ControllerAdvice 約定了幾種可行的返回值,如果是直接返回 model 類的話,需要使用 @ResponseBody 進行 json 轉換
o	返回 String,表示跳到某個 view
o	返回 modelAndView
o	返回 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;
	}
}