springboot render 和 重定向

一、前提条件

1、导入thymeleaf

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
</dependency>

2、html

templates文件夹中创建html文件

<html lang="en"  xmlns:th="http://www.thymeleaf.org">

 3、视图

@Controller
public class TestController {
    @GetMapping("/test")
    public String isTest(Model model){
        // 前后端传递数据
        model.addAttribute("msg", "Hello World");
        return "text1";
    }
}

 二、重定向

1、通过视图重定向

/ 跳转到 /abc

@GetMapping("/")
private String vb(){
    return "redirect:/abc";
}

2、通过WebMvcConfigurationSupport重定向

package com.wt.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class WebStaticConfig extends WebMvcConfigurationSupport {
    // 访问静态文件
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        super.addResourceHandlers(registry);
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }

    // 重定向
    @Override
    protected void addViewControllers(ViewControllerRegistry registry) {
        super.addViewControllers(registry);
        // urlPath /  , setViewName -> templates 中html的名字
        registry.addViewController("/").setViewName("test");
    }
}

 

posted @ 2020-07-23 22:07  市丸银  阅读(382)  评论(0编辑  收藏  举报