thymeleaf请求切换页面,每一个请求都要有写一个controller的空方法return回内容的解决方式

原创
小哥 3年前 (2022-11-09) 阅读数 9 #大杂烩

正常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中的方法无用,可以注释掉:

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除