thymeleaf请求跳转页面,每一个请求都需要写一个controller的空方法return回页面的解决办法

正常thymeleaf使用中,前端发送的请求如果单纯想跳转页面的话,需要在controller写一个方法去return回页面,例如:
在这里插入图片描述
如果请求多,且都只是单纯跳转页面的话,每一个都这么写实在是太难受了。解决方案就是实现springmvc的WebMvcConfigurer接口,重写addViewControllers方法,将请求html页面映射过来;不需要写空方法。

写一个配置类即可:

package com.***.***.auth.config;

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

/**
 * @author guanghaocheng
 * @version 1.0
 * 翼以尘雾之微补益山海,荧烛末光增辉日月
 * @date 2021/6/29 20:32
 */
@Configuration
public class ManagerWebConfig implements WebMvcConfigurer {
    
    

    /**
     * 视图映射
     * @param registry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
    
    
        //registry相当于viewcontroller的注册中心,想让哪些请求跳到哪些页面,在这里注册就行了
        registry.addViewController("/login.html").setViewName("login");//添加视图控制器,第一个参数urlPath是请求地址等同于requestMapping的地址。第二个参数viewName是视图名,也就是原来controller中return的页面的名。
        registry.addViewController("/register.html").setViewName("register");
    }
}

这个配置写完就ok了,以后想请求直接跳转页面就写这个就行。controller中的方法就没用了,可以注释掉了:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42969135/article/details/118343472