@RequestMapping("/freemarkerIndex")
public String index(Map result) {html
result.put("name", "yushengjun"); result.put("sex", "0"); List listResult = new ArrayList(); listResult.add("zhangsan"); listResult.add("lisi"); listResult.add("itmayiedu"); result.put("listResult", listResult); return "index";
}web
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title>首頁</title>
</head>
<body>
${name}
<#if sex=="1">
男
<#elseif sex=="2">
女
<#else>
其餘 spring
</#if> <#list userlist as user> ${user} </#list>
</body>
</html>apache
1.2 Freemarker配置
新建application.properties文件json
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
1.3 使用JSP渲染Web視圖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
<dependencies>
<!-- SpringBoot 核心組件 -->
<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>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
</dependencies>tomcat
1.4 在application.properties建立如下配置
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jspsession
1.5 後臺代碼br/>@Controller
public class IndexController {mvc
@RequestMapping("/index") public String index() { return "index"; }
}app
注意:建立SpringBoot整合JSP,必定要爲war類型,不然會找不到頁面.
不要把JSP頁面存放在resources// jsp 不能被訪問到jsp
1.6 全局捕獲異常
@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() { //開發中,通常都會講錯誤日誌記錄在日誌中,全局捕獲異常使用AOP技術,採用異常通知 //若是每一個方法均可能發生異常,每一個方法上都加上try Map<String, Object> map = new HashMap<String, Object>(); map.put("errorCode", "500"); map.put("errorMsg", "全局捕獲系統錯誤!"); return map; }
}