天天看點

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實作無業務邏輯頁面跳轉