天天看点

Spring MVC 的addViewControllers实现无业务逻辑页面跳转

场景:

从一个页面跳转至另一个页面,不做业务逻辑。

比如:我们从a页面跳转到addUser页面

实现:

在springMVC中templates下面的页面不能直接通过写页面地址去实现跳转,要走Controller.

第一种方式:

@RequestMapping("/toAddUser")
    public String toAddUser(){
        return "addUser";
    }
           

第二种方式:注册的形式,不走controller

创建一个配置类,实现WebMvcConfigurer,重写其addViewControllers方法即可。

package com.demo.user_web.config;

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

@Configuration
public class ViewConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("toAddUser").setViewName("addUser");
    }
}
           
两种方式等价。

ps. 如果templates下面还有多层文件夹,则带上路径即可。

eg:

return “user/addUser”

或者

setViewName("user/addUser")

Spring MVC 的addViewControllers实现无业务逻辑页面跳转