第一步:创建springboot-mvc项目
第二步:在src的com.pp包下创建一个config包,然后船舰MyConfig类
package com.pp.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Locale;
@Configuration
//@EnableWebMvc
//spring boot默认配置会给干掉
public class MyConfig implements WebMvcConfigurer {
//addViewControllers方法里面的addViewControllers相当于controller层
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//返回路径http://localhost:8080/ad,然后就返回到success页面
registry.addViewController("ad").setViewName("success");
}
@Bean
public ViewResolver myViewResolver(){
return new MyViewResolver();
}
public static class MyViewResolver implements ViewResolver{
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
return null;
}
}
}
这个类先让它继承WebMvcConfigurer接口,然后在使用addViewControllers相当于这是就是一个controller,然后再里面调用registry.addViewController(“ad”).setViewName(“success”);使页面访问localhost:8080/ab就可以访问到sucess.html页面
第三步:再resource下创建一个template文件夹,然后创建sucess.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
成功
</body>
</html>
第四步:点击运行,再网页中访问localhost:8080/ad页面
源码地址:https://gitee.com/yangforever/project-learning/tree/master/demo/SpringBoot/springboot-mvc