三、 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. HTML5 地理位置定位API(2)

    HTML5 Geolocation API (地理位置应用程序接口) 目前PC浏览器支持情况: Firefox 3.5+Chrome 5.0+Safari 5.0+Opera 10.60+Intern ...

  2. 产品运营数据分析—SPSS数据分组案例

    产品运营数据分析-SPSS数据分组案例 当我们的样本量过大,譬如以前讲过的,EXCEL2010最大只支持1048576行.16384列,尤其是当行数大于30万,一般的办公电脑处理都比较吃力,所以推荐数 ...

  3. sonarqube-jenkins-config

    Sonar Config .Jenkinsfile config stage('SonarQube analysis') { steps { script { scannerHome = tool ' ...

  4. jQuery学习二

    1.id选择器: // 4.如果页面中多个元素id相同,jquery只会获取第一个id的jquery对象 var jquery = $('#name'); alert(jquery.val()); v ...

  5. Node.js ORM框架Sequelize使用示例

    示例代码: const Sequelize = require('sequelize'); const sequelize = new Sequelize('database', 'username' ...

  6. CSS3 @font-face详细用法

    @font-face是CSS3中的一个模块,他主要是把自己定义的Web字体嵌入到你的网页中,随着@font-face模块的出现,我们在Web的开发中使用字体就不用再为只能使用Web安全字体烦恼了!肯定 ...

  7. 编写高质量iOS代码与OS X代码的effective方法(小结)

    一.熟悉OC: 了解OC的起源: OC和C++,Java等面向对象语言类似,不过有很方面差别.因为该语言使用  消息结构而非函数调用. 消息结构和函数调用的区别:前者是在其运行时所应执行的代码由运行环 ...

  8. WebStorm+Chrome调试Vue步骤

    在调试时请 注意 : 在WebStorm中启动调试时,WebStorm会根据你设置的url,自动打开新的Chrome浏览器进程访问这个设置的url,而且这个浏览器页面和你平常看到的浏览器差异会比较大, ...

  9. eclipse界面

    Eclipse工作空间的基本配置 A:行号的显示和隐藏 显示:在代码区域的最左边的空白区域,右键 -- Show Line Numbers即可. 隐藏:把上面的动作再做一次. B:字体大小及颜色 a: ...

  10. linux中的pvmove,pvremove,pvs,pvscan

    PV,VG,LV的关系和操作 PV,VG,LV构成了一种易于管理拥有一个或多个硬盘的主机的文件系统,这些硬盘可能只有一个分区也可能有多个.通过将这些物理存在的分区(或称为卷)PV(physical v ...