Springboot是如何实现页面间的跳转的

SpringBoot 中html的页面间跳转_晓风残月( ̄ε(# ̄)~的博客-CSDN博客

HTML网页如何在SpringBoot框架下进行跳转?

两种方法:

  • Controller类中编写相关Mapper方法,将方法通过@RequestMapping与具体的URL进行关联
  • 实现WebMvcConfigurer接口,通过参数ViewControllerRegistry调用addViewController方法。

方法一:Controller类与@RequestMapper方法

1)访问单一页面

在SpringBoot中,简单访问单一页面时,需要编写Controller类来实现,给这个页面传递信息,则需要具体的方法和对应的@RequestMapping:

 

以上图为例,要访问NewLogin.html时,就要在Controller类中写个方法,该方法要return NewLogin(不用写后缀):

@Controller
public class UserController{
    @RequestMapping("/login")
    public String toLogin(){
        return "html/NewLogin";
    }
}

上文的含义是,当我们在浏览器中访问localhost/login时,返回的html页面classpath/html/NewLogin.html

也就是说,@RequestMapping中是在浏览器中输入的URL,而return的是访问该页面返回的html文件

 

 

2)页面间的跳转

接1),如果我们要在登录页面,点击左上角“立即注册”跳转到注册页面,我们就要在Controller类中添加处理注册的方法和@RequestMapping

 

@RequestMapping("/register")
public String toRegister(){
    return "html/userRegister";
}

 

上文含义是,当我们在浏览器中访问localhost/register时,返回的html页面是classpath/html/userRegister.html

 

而且,NewLoging.html中,“立即注册”这个按钮要通过href"/register"(即@RequestMapping中的URL)关联:

 

 

 

 

方法二:重写addViewControllers

用方法1的方法实现页面跳转,需要为每个页面写带@RequestMappingController类方法

在这个方法中,需要自定义一个实现了WebMvcConfigurer接口MvcConfig类,覆写addViewControllers(ViewControllerRegistry registry)

用这种方法实现方法一的页面跳转,代码如下:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer{
    @Override
    public void addViewControllers(ViewControllerRegistry registry){
        //设置URL及其对应的HTML文件
        registry.addViewController("/NewLogin").setViewName("html/NewLogin");
        registry.addViewController("/userRegister").setViewName("html/userRegister");
  }
}
  • addViewController("/url"):相当于方法一中的@RequestMapping("/url"),是在浏览器地址栏中输入的URL;
  • setViewName("path/to/html"):相当于方法一中的return "path/to/html",即访问URL对应的HTML文件,也是显示出来的页面。

通过在HTML文件中的href属性属性值就是上文addViewController("/url")中的"/url")进行按钮跳转页面之间关联

 

 

方法一和方法二是不冲突的,但是通常情况下如果用方法二addViewControllers,需要把方法一所写的Controller类给注释掉。

 

posted @ 2022-07-01 15:08  ShineLe  阅读(9357)  评论(0编辑  收藏  举报