springboot2.0(二)

3、 Web開發

3.1靜態資源訪問

在咱們開發Web應用的時候,須要引用大量的js、css、圖片等靜態資源。css

默認配置html

Spring Boot默認提供靜態資源目錄位置需置於classpath下,目錄名需符合以下規則:web

/staticspring

/publicapache

/resourcesjson

/META-INF/resourcestomcat

舉例:咱們能夠在src/main/resources/目錄下建立static,在該位置放置一個圖片文件。啓動程序後,嘗試訪問http://localhost:8080/D.jpg。如能顯示圖片,配置成功。springboot

3.2、渲染Web頁面

 

渲染Web頁面session

在以前的示例中,咱們都是經過@RestController來處理請求,因此返回的內容爲json對象。那麼若是須要渲染html頁面的時候,要如何實現呢?mvc

模板引擎

在動態HTML實現上Spring Boot依然能夠完美勝任,而且提供了多種模板引擎的默認配置支持,因此在推薦的模板引擎下,咱們能夠很快的上手開發動態網站。

Spring Boot提供了默認配置的模板引擎主要有如下幾種:

  • Thymeleaf
  • FreeMarker
  • Velocity
  • Groovy
  • Mustache

Spring Boot建議使用這些模板引擎,避免使用JSP,若必定要使用JSP將沒法實現Spring Boot的多種特性,具體可見後文:支持JSP的配置

當你使用上述模板引擎中的任何一個,它們默認的模板配置路徑爲:src/main/resources/templates。固然也能夠修改這個路徑,具體如何修改,可在後續各模板引擎的配置屬性中查詢並修改。

3.3使用Freemarker模板引擎渲染web視圖

3.3.1pom文件引入

<!-- 引入freeMarker的依賴包. -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-freemarker</artifactId>

</dependency>

3.3.2、後臺代碼

src/main/resources/建立一個templates文件夾,後綴*.ftl

@RequestMapping("/index")

public String index(Map<String, Object> map) {

    map.put("name","美麗的天使...");

   return "index";

}

 

3.3.3、前臺代碼

 

<!DOCTYPE html>

<html>

<head lang="en">

<meta charset="UTF-8" />

<title></title>

</head>

<body>

  ${name}

</body>

</html>

3.3.4Freemarker其餘用法

@RequestMapping("/freemarkerIndex")

public String index(Map<String, Object> result) {

result.put("name", "xiaohong");

result.put("sex", "0");

List<String> listResult = new ArrayList<String>();

listResult.add("zhangsan");

listResult.add("lisi");

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>

 

3.3.5Freemarker配置

新建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

 

3.4、使用JSP渲染Web視圖

3.4.1pom文件引入如下依賴

<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>

 

3.4.2、在application.properties建立如下配置

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

spring.mvc.view.suffix=.jsp

 

3.4.3、後臺代碼

@Controller

public class IndexController {

@RequestMapping("/index")

public String index() {

return "index";

}

}

 

 

 

 

注意:建立SpringBoot整合JSP,必定要爲war類型,不然找不到頁面.

不要把JSP頁面存放在resources// jsp 不能被訪問到

 

 

 

 

 

 

 

 

 

 

3.5全局捕獲異常

@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;

}

}

相關文章
相關標籤/搜索