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