SpringBoot中扩展SpringMVC

在我们一般的SpringBoot中,实现页面的跳转只需写一个controller,在上面加上注解

package com.hzy.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {
    @RequestMapping("/test")
    public String test() {
        return "test";
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
</head>
<body>
hello world
</body>
</html>

现在我们可以通过扩展SpringMVC来实现同样的功能,我们需要写一个config类实现WebMvcConfigurer接口,加上@Configuration,并重写addViewControllers方法,我们把之前的controller类删除,加上这个config,也可以实现页面跳转

package com.hzy.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 MyMvcConfig implements WebMvcConfigurer {

    //视图跳转
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/test").setViewName("test");
    }
}

发布了423 篇原创文章 · 获赞 273 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/HeZhiYing_/article/details/104328685