三、 Web开发

3.1、静态资源访问

在我们开发Web应用的时候,需要引用大量的js、css、图片等静态资源。

默认配置

Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:

/static

/public

/resources

/META-INF/resources

举例:我们可以在src/main/resources/目录下创建static,在该位置放置一个图片文件。启动程序后,尝试访问http://localhost:8080/D.jpg。如能显示图片,配置成功。

3.2、渲染Web页面

渲染Web页面

在之前的示例中,我们都是通过@RestController来处理请求,所以返回的内容为json对象。那么如果需要渲染html页面的时候,要如何实现呢?

模板引擎

在动态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.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>

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;

}

}

springboot2.0(二)的更多相关文章

  1. SpringBoot2.0(二) 配置文件多环境

    在SpringBoot中,多环节的配置文件名基于application-{profile}.properties的格式,其中{profile}对应环境标识,比如: application-daily. ...

  2. SpringBoot2.0源码分析(二):整合ActiveMQ分析

    SpringBoot具体整合ActiveMQ可参考:SpringBoot2.0应用(二):SpringBoot2.0整合ActiveMQ ActiveMQ自动注入 当项目中存在javax.jms.Me ...

  3. 零基础快速入门SpringBoot2.0教程 (二)

    一.SpringBoot2.x使用Dev-tool热部署 简介:介绍什么是热部署,使用springboot结合dev-tool工具,快速加载启动应用 官方地址:https://docs.spring. ...

  4. spring-boot-2.0.3启动源码篇二 - run方法(一)之SpringApplicationRunListener

    前言 Springboot启动源码系列还只写了一篇,已经过去一周,又到了每周一更的时间了(是不是很熟悉?),大家有没有很期待了?我会尽量保证启动源码系列每周一更,争取不让大家每周的期望落空.一周之中可 ...

  5. springboot学习入门简易版二---springboot2.0项目创建

    2 springboot项目创建(5) 环境要求:jdk1.8+ 项目结构: 2.1创建maven工程 Group id :com.springbootdemo Artifact id: spring ...

  6. springboot2.0+websocket集成【群发消息+单对单】(二)

    https://blog.csdn.net/qq_21019419/article/details/82804921 版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上 ...

  7. Activiti工作流框架学习笔记(二)之springboot2.0整合工作流Activiti6.0

    以前在工作当中做过不少与工作流Activiti有关的工作,当时都是spring集成activiti5.22的项目,现在回过头去看,其实版本已经稍微老了,因此,基于先前的工作经验,决定用较新版本的技术来 ...

  8. (六)SpringBoot2.0基础篇- Redis整合(JedisCluster集群连接)

    一.环境 Redis:4.0.9 SpringBoot:2.0.1 Redis安装:Linux(Redhat)安装Redis 二.SpringBoot整合Redis 1.项目基本搭建: 我们基于(五) ...

  9. SpringBoot2.0之四 简单整合MyBatis

    从最开始的SSH(Struts+Spring+Hibernate),到后来的SMM(SpringMVC+Spring+MyBatis),到目前的S(SpringBoot),随着框架的不断更新换代,也为 ...

随机推荐

  1. SSD论文学习

    SSD: Single Shot MultiBox Detector——目标检测 参考https://blog.csdn.net/u010167269/article/details/52563573 ...

  2. 阶段5 3.微服务项目【学成在线】_day17 用户认证 Zuul_16-网关-过虑器

    4.5 过虑器 Zuul的核心就是过虑器,通过过虑器实现请求过虑,身份校验等. 4.5.1 ZuulFilter 自定义过虑器需要继承 ZuulFilter,ZuulFilter是一个抽象类,需要覆盖 ...

  3. 算法习题---3.08循环小数(UVa202)

    一:题目 输入整数a和b(<=a<=,<=b<=),输出a/b的循环小数表示以及循环节长度. 例如,a=,b=,小数表示为0.(),循环字节长度为21 当循环节长度超过50时, ...

  4. PAT 甲级 1054 The Dominant Color (20 分)(简单题)

    1054 The Dominant Color (20 分)   Behind the scenes in the computer's memory, color is always talked ...

  5. mysql命令、mysqldump命令找不到解决

    1.解决bash: mysql: command not found 的方法 [root@DB-02 ~]# mysql -u root -bash: mysql: command not found ...

  6. 看看BeginInvoke的用法,亲爱的们

    看看它是杂带参数的哈 using System; using System.Threading; class MyTest { delegate bool deleTest(string a,stri ...

  7. 第二十四章 在线会话管理——《跟我学Shiro》

    目录贴:跟我学Shiro目录贴 有时候需要显示当前在线人数.当前在线用户,有时候可能需要强制某个用户下线等:此时就需要获取相应的在线用户并进行一些操作. 本章基于<第十六章 综合实例>代码 ...

  8. 【谷歌浏览器】修改和添加Cookie

    一.使用谷歌浏览器 1.1.修改ookie 方法一:直接用开发者工具修改: 操作如图:   参考: 检查和删除 Cookie · Chrome 开发者工具中文文档 http://www.css88.c ...

  9. WebStorm 2018.2安装激活教程

    1.下载解压,得到jetbrains webstorm 2018.2主程序,破解文件和中文语言包: 2.运行“WebStorm-2018.2.exe”开始安装,默认安装目录[C:\Program Fi ...

  10. python 字体染色

    字体染色 <font face="黑体">我是黑体字</font> <font face="微软雅黑">我是微软雅黑< ...