栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot核心技术-Web开发-视图解析与模板引擎

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot核心技术-Web开发-视图解析与模板引擎

一、视图解析

视图解析:SpringBoot默认不支持 JSP,需要引入第三方模板引擎技术实现页面渲染。

1.1 视图解析原理

1、目标方法处理的过程中,所有数据都会被放在ModelAndViewContainer里面,包括数据和视图地址。

2、如果方法的参数是一个自定义类型对象(从请求参数中确定的),会把它重新放在ModelAndViewContainer。

3、任何目标方法执行完成后都会返回ModelAndView(数据和试图地址)。

4、processDispatchResult处理派发结果(页面如何响应)

        render(mv,request,resposne);进行页面渲染逻辑,mv是ModelAndView对象。

                根据方法的String返回值得到了View对象【定义了页面的渲染逻辑】,以下是具体流程

                1、所有的视图解析器尝试是否能根据当前返回值得到View对象

                2、得到了 redirect:/main.html --> Thymeleaf创建new RedirectView()【重定向】

                3、ContentNegotiationViewResolver 里面包含了下面所有的视图解析器,内部还是利用下面所有视图解析器得到视图对象。

                4、view.render(mv.getModelInternal(), request, response); 视图对象调用自定义的render进行页面渲染工作

                        RedirectView如何渲染【重定向到一个界面】

                                1、获取目标url地址

                                2、response.sendRedirect(encodedURL);               

所有的视图解析器:

视图对象: 

视图解析:

  • 返回值以 forward: 开始: new InternalResourceView(forwardUrl); --> 转发request.getRequestDispatcher(path).forward(request, response);
  • 返回值以 redirect: 开始: new RedirectView() --> render就是重定向
  • 返回值是普通字符串: new ThymeleafView()--->

                   

二、模板引擎-Thymeleaf 2.1 thymeleaf简介

现代化、服务端Java模板引擎

2.2 基本语法

 三、thymeleaf使用 3.1 引入starter
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
 3.2 引入之后会自动配置好thymeleaf
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration { }

自动配好的策略

  1. 所有thymeleaf的配置值都在 ThymeleafProperties
  2. 配置好了 SpringTemplateEngine
  3. 配好了 ThymeleafViewResolver
  4. 我们只需要直接开发页面
//Thymeleaf配置类
public static final String DEFAULT_PREFIX = "classpath:/templates/";

public static final String DEFAULT_SUFFIX = ".html";  //xxx.html
3.3 页面开发 



    
    Title


哈哈 去百度
去百度2

    @GetMapping("/test/thymleaf")
    public String testThymleaf(Model model) {
        model.addAttribute("msg", "消息来了");
        //要加http,不然会把link直接接在项目路径后面
        model.addAttribute("link", "http://www.baidu.com");
        return "success";
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/434474.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号