一共有兩種方法
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";
}
}