一共有两种方法
1.继承WebMvcConfigurerAdapter
类或实现WebMvcConfigurer接口
创建一个config包,然后在包内创建MyMvcConfig类。
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
super.addViewControllers(registry);
}
}
注意:如果用这个方法html页面需要在static下,不然会出现404错误,找不到页面。
2.@Controller路由设置
在controller层中创建一个IndexController类
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping({"/","/index"})
public String index(){
return "index";
}
}