您当前的位置: 首页 >  微服务

微服务技术系列教程(02) - SpringBoot - Web开发

杨林伟 发布时间:2019-11-05 15:52:21 ,浏览量:3

代码已提交至Github,有兴趣的同学可以下载来看看:https://github.com/ylw-github/SpringBoot-Web-Demo

本文目录结构: l____1.静态资源访问 l____2.渲染Web页面 l_______2.1 使用FreeMarker模板引擎渲染Web视图 l_______2.2 使用JSP渲染Web视图 l____3.异常捕获 l____总结

1. 静态资源访问

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

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

/static
/public
/resources	
/META-INF/resources

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

项目结构图: 在这里插入图片描述 运行程序后: 在这里插入图片描述

2. 渲染Web页面

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

答:可以使用到模板引擎

在动态HTML实现上Spring Boot依然可以完美胜任,并且提供了多种模板引擎的默认配置支持,所以在推荐的模板引擎下,我们可以很快的上手开发动态网站。

Spring Boot提供了默认配置的模板引擎主要有以下几种:

  • Thymeleaf
  • FreeMarker
  • Velocity
  • Groovy
  • Mustache

Spring Boot建议使用这些模板引擎,避免使用JSP,若一定要使用JSP将无法实现Spring Boot的多种特性。当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为:src/main/resources/templates

2.1 使用FreeMarker模板引擎渲染Web视图

1.添加Maven依赖:



    org.springframework.boot
    spring-boot-starter-freemarker
    2.1.3.RELEASE

2.在src/main/resources/创建一个templates文件夹,后缀为*.ftl,创建index.ftl:




    
        
        首页
    

    
        ${name}
        
            男
        
            女
        
            其他

        
        
            ${user}
        
    

3.IndexController

package com.ylw.springboot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController {

    @RequestMapping("/index")
    public String index(Map result) {
        result.put("name", "Dumas");
        result.put("sex", "male");
        List listResult = new ArrayList();
        listResult.add("Jim");
        listResult.add("David");
        listResult.add("Hary");
        result.put("userlist", listResult);
        return "index";
    }
}

4.运行程序,浏览器输入 localhost:8080/index 在这里插入图片描述 关于Freemarker配置:

可以新建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
2.2 使用JSP渲染Web视图

1.添加Maven依赖:


   org.springframework.boot
   spring-boot-starter-tomcat
   2.1.6.RELEASE



   org.apache.tomcat.embed
   tomcat-embed-jasper
   8.5.31

2.新建webapp/WEB-INF/jsp/index1.jsp文件 在这里插入图片描述 3.编写Controller

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

4.浏览器输入:http://localhost:8080/indexJsp,运行程序: 在这里插入图片描述 注意:创建SpringBoot整合JSP,一定要为war类型,否则会找不到页面

3.异常捕获

@ExceptionHandler 表示拦截异常

  • @ControllerAdvice 是 controller 的一个辅助类,最常用的就是作为全局异常处理的切面类
  • @ControllerAdvice 可以指定扫描范围
  • @ControllerAdvice 约定了几种可行的返回值,如果是直接返回 model 类的话,需要使用 @ResponseBody 进行 json 转换

请求返回的格式有如下几种:

  • 返回 String,表示跳到某个 view
  • 返回 modelAndView
  • 返回 model + @ResponseBody

例如:

package com.ylw.springboot.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {
    
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Map exceptionHandler() {
        Map map = new HashMap();
        map.put("errorCode", "101");
        map.put("errorMsg", "系统错误!");
        return map;
    }
}

测试方法:

@RequestMapping("/testException")
public String testException() {
    throw new RuntimeException("模拟运行时异常!");
}

浏览区输入:http://localhost:8080/testException,运行: 在这里插入图片描述

总结

在这里插入图片描述

关注
打赏
1688896170
查看更多评论

杨林伟

暂无认证

  • 3浏览

    0关注

    3183博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0853s