WebMvcConfigurerAdapter的用法

写Spring MVC时,要添加一个新的页面访问:
以前:新增一个Controller 或者在 已有的一个Controller 中新增一个方法,然后再跳转到设置的页面。
原因:考虑到大部分的应用场景中View 和后台都会有数据交互,这样的处理也无可厚非。
现在:
我们肯定也有只是想通过一个URL Mapping然后不经过Controller处理直接跳转到页面上的需求。

今天在做Spring Security相关配置的时候偶然发现了Spring也为我们提供了一个办法,那就是
WebMvcConfigurerAdapter。
Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。

  import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebMvcConfig  extends WebMvcConfigurerAdapter{
    //为ws.HTML 提供便捷的路径映射。
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/ws").setViewName("/ws");
        registry.addViewController("/index").setViewName("/index");
    }
}

通过上面的配置,不用添加WsController/IndexController或者处理”ws”/”index”的方法就可以直接通过”http://localhost:8080/projectContext/ws” 或者 “http://localhost:8080/projectContext/index” 访问到 ws.html /index.html页面了!!
这样处理是不是更方便?

你可能感兴趣的:(WebSocket,WebSocket)