Skip to content

Conversation

@icoco
Copy link

@icoco icoco commented Jun 17, 2024

现有 mvc viewcontroller 定义固化:

registry.addViewController("/").setViewName("doc.html");

希望可配置,

此次更新的实现方案:

1)增加注解标示类: MvcMapping
2)增加 mvc 定义类: MvcDef
3)修改 WebMvcConfiguration.java

代码:

 /**
     * 方案一: 默认访问根路径跳转 doc.html页面 (swagger文档页面)
     * 方案二: 访问根路径改成跳转 index.html页面 (简化部署方案: 可以把前端打包直接放到项目的 webapp,上面的配置)
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //registry.addViewController("/").setViewName("doc.html");
       handleMappingViewControllers(registry);
    }

    @Bean
    @MvcMapping
    public Map defaultMvcMapping() {
        Map result = new HashMap();
        MvcDef root = MvcDef.create("/","doc.html");
        result.put(root.getPath(),root);
        return result;
    }

    private void handleMappingViewControllers(ViewControllerRegistry registry) {

        ApplicationContext context = SpringContextUtils.getApplicationContext();

        Map<String, Object> beanMaps = context.getBeansWithAnnotation(MvcMapping.class);

        if (null == beanMaps) {
            return;
        }
        HashMap<String,MvcDef> mvc = new HashMap();
        for (Object val : beanMaps.values()) {
            if (!(val instanceof Map)) {continue;}
            Map mvcMaps = (Map)val;
            for (Object def : mvcMaps.values()) {
                if (def instanceof MvcDef) {
                    handleOverrideMapping(mvc, (MvcDef)def);
                }
            }
        }

        for (MvcDef def : mvc.values()) {
           registry.addViewController(def.getPath()).setViewName(def.getView());
        }
    }
    private void handleOverrideMapping(HashMap mvc,MvcDef def){
        Object val = mvc.get(def.getPath());
        if (null == val){
            mvc.put(def.getPath(),def);
            return ;
        }
        MvcDef existDef = (MvcDef)val;
        if (existDef.getPriority()< def.getPriority()){
            mvc.put(def.getPath(),def);
        }
    }

usage

    @Bean
    @MvcMapping
    public Map indexMvcMapping() {
        Map result = new HashMap();
        MvcDef root = MvcDef.create("/","index.html",999);
        result.put(root.getPath(),root);
        return result;
    }

replace exist path '/' with new page

this way should easy extends the mvc mapping feature .

@icoco icoco closed this Jun 29, 2024
@icoco
Copy link
Author

icoco commented Nov 1, 2025

没合并? 最新工程代码,没这个feature ??

@icoco icoco reopened this Nov 1, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

1 participant