Springboot 正确跳转页面的几种方式

写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/");
    }
}

三种方式都能实现页面的正确跳转.综合而言,第三种还是很方便!

 

  • 8
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值