写springboot项目的时候,我们经常把js,css放在static下面,把html放在templates下面,然后如果不进行任何配置或者处理的话,我们想 访问页面,springboot会给我们抛出错误页,现在就说一下怎么能够正确跳转页面,我这边了解了三种方式
1. 使用controller的方式
这种方式比较简单粗暴就是对每一个要请求的页面需要加上对应的controller进行跳转,比如templates下面有index.html,想跳转的话需要写对应的controller
@Controller
public class JumpController {
@RequestMapping("/index.html")
public String index(){
return "index";
}
}
这样你访问http://127.0.0.1:8080/index.html 才能够正确跳转页面
这种每一个页面都要写对应的controller,虽然能实现功能,只是过于麻烦
2.自定义一个类实现WebMvcConfigurer 接口,并重写里面的addViewControllers方法添加关系对应
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
//addViewController就相当于上面第一种方式中的 @RequestMapping中的值,setViewName相当于返回的值
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/index.html").setViewName("index");
}
}
不过这种也需要所有的页面都在这里添加,所以还是很麻烦,于是就来到了第三种方式
3.自定义一个类,实现WebMvcConfigurer接口,并重写addResourceHandlers方法添加关系对应
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
/* @Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/index.html").setViewName("index");
}*/
//所有css,js,images等等都调到static路径下,其他的都跳到templates下
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("/**").addResourceLocations("classpath:/templates/");
}
}
三种方式都能实现页面的正确跳转.综合而言,第三种还是很方便!
2339





