美文网首页Spring Boot
SpringBoot | 第十六章:web 应用开发

SpringBoot | 第十六章:web 应用开发

作者: 小波同学 | 来源:发表于2018-12-29 19:14 被阅读1次

    原文出处: oKong

    前言

    前面讲了这么多直接,都没有涉及到前端web和后端交互的部分。因为作者所在公司是采用前后端分离方式进行web项目开发了。所以都是后端提供api接口,前端根据api文档或者服务自行调用的。后台也有读者说为何没有关于web这部分的集成文章。本章节就主要讲解下如何渲染页面的。

    一点知识

    我们知道,在web开发时,一般都会涉及到很多的静态资源,如jsimagecss文件等。

    SpringBoot的默认的静态文件目录是:

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

    默认静态文件目录

    所以一般上我们只需要把静态文件放入前面的四个任一一个即可。默认都放在static下,对应路径即为:src/main/resources/static

    而从官网文档里也可以获悉,为了实现动态的html,SpringBoot是通过模版引擎进行页面结果渲染的,目前(1.5.15)版本的提供默认配置的模版引擎主要为:

    模版引擎

    对于模版引擎而言,SpringBoot默认存放模版文件的路径为src/main/resources/templates,当然也可以通过配置文件进行修改的。因为不同的模版引擎对应的配置属性是不一样,所以在具体讲解模版引擎时,会提到的。


    当然了,使用jsp也是可以的,但官方已经不建议使用JSP,本文也会讲解下SpringBootJSP的支持的,比较有很多老的项目还是使用JSP居多的。


    知道了以上的一些默认配置和知识点后,就可以进行模版引擎的集成使用了。本章节主要讲解下常用的FreeMarkerThymeleafJSP三个的集成和使用,其他的基本用法都一样,就是各模版引擎的语法的差异了。

    FreeMarker支持

    FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据,并用来生成输出文本(HTML网页,电子邮件,配置文件,源代码等)的通用工具。

    示例 示例

    0.POM依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>
    

    1.application.properties配置加入相关配置:

    # 缓存配置 开发阶段应该配置为false 因为经常会改
    spring.freemarker.cache=false
     
    # 模版后缀名 默认为ftl
    spring.freemarker.suffix=.html
     
    # 文件编码
    spring.freemarker.charset=UTF-8
     
    # 模版加载的目录
    spring.freemarker.template-loader-path=classpath:/templates/
     
    # 配置
    # locale    该选项指定该模板所用的国家/语言选项
    # number_format 指定格式化输出数字的格式:currency、
    # boolean_format    指定两个布尔值的语法格式,默认值是true,false
    # date_format,time_format,datetime_format   定格式化输出日期的格式
    # time_zone 设置格式化输出日期时所使用的时区
    # 数字 千分位标识
    spring.freemarker.settings.number_format=,##0.00
    

    题外话:详细的配置可参见org.springframework.boot.autoconfigure.freemarker.FreeMarkerProperties类,或者直接IDE直接配置文件点击查看。

    2.编写控制层

    FreemarkerController.kava:

    //因为是返回页面 所以不能是@RestController
    @Controller
    @RequestMapping("/freemarker")
    public class FreemarkerController {
         
        //正常和springmvc设置返回参数是意义的用法了
        @GetMapping("/map")
        public String index(String name,ModelMap map) {
            map.addAttribute("name", name);
            map.addAttribute("from", "lqdev.cn");
            //模版名称,实际的目录为:src/main/resources/templates/freemarker.html
            return "freemarker";
        }
         
        @GetMapping("/mv")
        public String index(String name,ModelAndView mv) {
            mv.addObject("name", name);
            mv.addObject("from", "lqdev.cn");
            //模版名称,实际的目录为:src/main/resources/templates/freemarker.html
            return "freemarker";
        }
    }
    

    3.编写模版文件

    freemarker.html:

    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8" />
        <title>freemarker简单示例</title>
    </head>
    <body>
    <h1>Hello Freemarker</h1>
    <!-- 这里注意:默认变量都不能为null的, 当参数为null时,会发生异常的 -->
    <!-- 这里后面几个"!"避免下,这样就是空白了 -->
    <h2>名称:${name!},来自:${from}</h2>
    </body>
    </html>
    

    4.启动应用,访问:http://127.0.0.1:8080/freemarker/mv?name=oKong 或者 http://127.0.0.1:8080/freemarker/map?name=oKong 就能查看页面了。

    image

    关于一些Freemarker的语法这里就不说明了,大家可到官网查看下:https://freemarker.apache.org/docs/index.html或者,中文参考(可能版本不是最新):http://freemarker.foofun.cn/toc.html


    Thymeleaf支持

    Thymeleaf是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发。Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。相对于编写逻辑或代码,开发者只需将标签属性添加到模板中即可。接下来,这些标签属性就会在DOM(文档对象模型)上执行预先制定好的逻辑。

    0.pom依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    

    1.application.properties配置加入相关配置:

    # 启用缓存:建议生产开启
    spring.thymeleaf.cache=false
    # 建议模版是否存在
    spring.thymeleaf.check-template-location=true
    # Content-Type 值
    spring.thymeleaf.content-type=text/html 
    # 是否启用
    spring.thymeleaf.enabled=true
    # 模版编码
    spring.thymeleaf.encoding=UTF-8
    # 应该从解析中排除的视图名称列表(用逗号分隔)
    spring.thymeleaf.excluded-view-names= 
    # 模版模式
    spring.thymeleaf.mode=HTML5 
    # 模版存放路径
    spring.thymeleaf.prefix=classpath:/templates/ 
    # 模版后缀
    spring.thymeleaf.suffix=.html
    

    2.编写控制层

    ThymeleafController.java:

    @Controller
    @RequestMapping("/thymeleaf")
    public class ThymeleafController {
     
        // 正常和springmvc设置返回参数是意义的用法了
        @GetMapping("/map")
        public String index(String name, ModelMap map) {
            map.addAttribute("name", name);
            map.addAttribute("from", "lqdev.cn");
            // 模版名称,实际的目录为:src/main/resources/templates/thymeleaf.html
            return "thymeleaf";
        }
     
        @GetMapping("/mv")
        public ModelAndView index(String name) {
            ModelAndView mv = new ModelAndView();
            mv.addObject("name", name);
            mv.addObject("from", "lqdev.cn");
            // 模版名称,实际的目录为:src/main/resources/templates/thymeleaf.html
            mv.setViewName("thymeleaf");
            return mv;
        }
    }
    

    3.编写模版文件

    thymeleaf.html

    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8" />
        <title>thymeleaf简单示例</title>
    </head>
    <body>
    <h1>Hello thymeleaf</h1>
    <!-- 这里注意:拼接时 变量要单独使用${param},其他的常量使用''包裹 -->
    <h2 th:text="'名称:'+${name}+',来自:'+${from}">默认值</h2>
    </body>
    </html>
    

    4.启动应用,访问:http://127.0.0.1:8080/thymeleaf/mv?name=oKong 或者 http://127.0.0.1:8080/thymeleaf/map?name=oKong 就能查看页面了。

    image

    JSP支持

    虽然SpringBoot官方已经不建议使用jsp了。但在一些老的项目迁移时,jsp的支持是毋庸置疑的。所以还是需要兼容的。。

    0.pom依赖加入

    <!-- spring boot 内置tomcat jsp支持 -->
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>
    

    1.application.properties配置加入相关配置:

    #jsp 支持
    spring.mvc.view.suffix=.jsp
    spring.mvc.view.prefix=/WEB-INF/jsp/
    

    2.编写控制层

    JspController.java

    @Controller
    @RequestMapping("/jsp")
    public class JspController {
         
        //正常和springmvc设置返回参数是意义的用法了
            @GetMapping("/map")
            public String index(String name,ModelMap map) {
                map.addAttribute("name", name);
                map.addAttribute("from", "lqdev.cn");
                //模版名称,实际的目录为:src/main/webapp/jsp/index.html
                return "index";
            }
             
            @GetMapping("/mv")
            public ModelAndView index(String name) {
                ModelAndView mv = new ModelAndView();
                mv.addObject("name", name);
                mv.addObject("from", "lqdev.cn");
                //模版名称,实际的目录为:src/main/webapp/jsp/index.html
                mv.setViewName("index");
                return mv;
            }
    }
    

    3.webapp/WEB-INF/jsp目录下编写jsp文件

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charsetUTF-8">
    <title>jsp示例</title>
    </head>
    <body>
    <h1>Hello Jsp</h1>
    <h2 >名称:${name},来自:${from}</h2>
    </body>
    </html>
    

    5.启动应用,访问:http://127.0.0.1:8080/jsp/mv?name=oKong 或者 http://127.0.0.1:8080/jsp/map?name=oKong 就能查看页面了。

    image

    这里需要注意:在使用spring-boot-maven-plugin打包插件时,默认情况下打包的应用时访问不了jsp目录文件的,需要把版本修改为1.4.2.RELEASE版本,同时pom中加入resource配置:

    <resources>
        <!-- 打包时将jsp文件拷贝到META-INF目录下 -->
        <resource>
            <!-- 指定resources插件处理哪个目录下的资源文件 -->
            <directory>src/main/webapp</directory>
            <!--注意此次必须要放在此目录下才能被访问到 -->
            <targetPath>META-INF/resources</targetPath>
            <includes>
                <include>**/**</include>
            </includes>
        </resource>
    <!--     <resource>
            指定resources插件处理哪个目录下的资源文件
            <directory>src/main/resources/static</directory>
            注意此次必须要放在此目录下才能被访问到
            <targetPath>META-INF/resources/static</targetPath>
            <includes>
                <include>**/**</include>
            </includes>
        </resource> -->
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/**</include>
            </includes>
    <!--         <excludes>
               <exclude>src/main/resources/static/**</exclude>
            </excludes> -->
            <filtering>false</filtering>
        </resource>
    </resources>
    

    相关资料

    1. https://docs.spring.io/spring-boot/docs/1.5.14.RELEASE/reference/htmlsingle
    2. https://blog.csdn.net/qq_34665539/article/details/74783910

    总结

    本章节主要是讲解了利用模版引擎进行动态页面实现功能。对于有此需要的同学可以去看下使用的模版引擎的相关使用教程,这里就不多加阐述了,毕竟目前工作现在用这个的机会比较少了,也只是知道个大概使用,具体一些深入的使用还是看具体的官方文档吧!

    最后

    目前互联网上很多大佬都有SpringBoot系列教程,如有雷同,请多多包涵了。本文是作者在电脑前一字一句敲的,每一步都是实践的。若文中有所错误之处,还望提出,谢谢。

    相关文章

      网友评论

        本文标题:SpringBoot | 第十六章:web 应用开发

        本文链接:https://www.haomeiwen.com/subject/zdvplqtx.html