1.1 Freemarker 其他用法

@RequestMapping("/freemarkerIndex")
public String index(Map result) {

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

}

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

1.2 Freemarker配置
新建application.properties文件

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>

1.4 在application.properties创建以下配置
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

1.5 后台代码@Controller
br/>@Controller

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

}

注意:创建SpringBoot整合JSP,一定要为war类型,否则会找不到页面.
不要把JSP页面存放在resources// 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; }

}