三、 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. 机器学习 - 算法 - SVM 支持向量机 Py 实现 / 人脸识别案例

    SVM 代码实现展示 相关模块引入 %matplotlib inline import numpy as np import matplotlib.pyplot as plt from scipy i ...

  2. 扯扯python的多线程的同步锁 Lock RLock Semaphore Event Condition

    我想大家都知道python的gil限制,记得刚玩python那会,知道了有pypy和Cpython这样的解释器,当时听说是很猛,也就意味肯定是突破了gil的限制,最后经过多方面测试才知道,还是那德行… ...

  3. SQL语句里合并两个select查询结果

    SQL UNION 操作符UNION 操作符用于合并两个或多个 SELECT 语句的结果集. 请注意,UNION 内部的 SELECT 语句必须拥有相同数量的列.列也必须拥有相似的数据类型.同时,每条 ...

  4. std::function以及std::bind

    转自:https://blog.csdn.net/shuilan0066/article/details/82788954 示例1 : 普通函数 void gFunc() { cout << ...

  5. rf笔记

    1.使用robot 用例绝对路径 可执行用例 2.robot --h 可以查看命令用法 3. 创建字典 *** Settings *** Library         Collections *** ...

  6. 异步回收fork出的子进程(僵尸进程)

    #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <unistd.h&g ...

  7. 第十九章 动态URL权限控制——《跟我学Shiro》

    目录贴:跟我学Shiro目录贴 用过Spring Security的朋友应该比较熟悉对URL进行全局的权限控制,即访问URL时进行权限匹配:如果没有权限直接跳到相应的错误页面.Shiro也支持类似的机 ...

  8. Ubuntu构建LVS+Keepalived高可用负载均衡集群【生产环境部署】

    1.环境说明: 系统版本:Ubuntu 14.04 LVS1物理IP:14.17.64.2   初始接管VIP:14.17.64.13 LVS2物理IP:14.17.64.3   初始接管VIP:14 ...

  9. 如何实现批量截取整个网页完整长截图,批量将网页保存成图片web2pic/webshot/screencapture/html2picture

    如何实现批量截取整个网页完整长截图,批量将网页保存成图片web2pic/webshot/screencapture [困扰?疑问?]: 您是否正受到:如何将网页保存为图片的困扰?网页很高很长截图截不全 ...

  10. Spring 使用下列表

    模型层需要提供数据选项,设置错误信息 关键代码 @NotEmpty(message = "请选择兴趣爱好") private String[] hobbies; 控制器层需要在显示 ...