在spring中,可能会有仅仅需要页面跳转而没有具体的业务逻辑的代码,如下所示
我们点击前端某处的时候跳转到登录或者注册的HTML页面,但是controller方法都是空的,仅仅return了一个页面
@GetMapping("/login.html")
public String loginPage(){
return "login";
}
@GetMapping("/reg.html")
public String regPage(){
return "reg";
}
长此以往我们的controller中会有很多这样的空方法,为了避免,我们使用SpringMVC中的addViewController来实现与上相同的逻辑。
新建一个配置类让他去实现WebMvcConfigurer ,并重写addViewControllers方法,参数传入就是controller中的URL,setViewName中传入的参数就是原return的页面。
@Configuration
public class MyWebConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login.html").setViewName("login");
registry.addViewController("/reg.html").setViewName("reg");
}
}