如何排查 Grails UrlMappings 问题?

使用 grails url-mappings-report 命令报告当前项目的所有 url 映射

执行下面的命令

grails url-mappings-report

将显示

Grails application running at http://localhost:0 in environment: development
Dynamic Mappings
 |    *     | ERROR: 404                                        | View:   /notFound        |
 |    *     | ERROR: 500                                        | View:   /error           |
 |    *     | ERROR: 404                                        | View:   /notFound        |
 |    *     | ERROR: 500                                        | View:   /error           |
 |    *     | /                                                 | View:   /index           |
 |    *     | /api/${controller}/${action}                      | Action: (default action) |
 |    *     | /${controller}/${action}?/${id}?(.${format)?      | Action: (default action) |

这个能知道你配置的 url mapping 是否真的生效了。

常见错误

没有调用 URL mapping 方法

下面是错误的写法

static mappings = {
        // 配置一个通用的 url mapping
        "/api/$controller/$action"
}

正确的写法

static mappings = {
        // 配置一个通用的 url mapping
        "/api/$controller/$action"()
}

URL 串要作为方法名执行调用,否则只是一个字符串而已,grails 的这个设计不太友好啊。

被插件中的 UrlMappings.groovy 干扰

插件里面的 UrlMappings.groovy 会编译为一个类,会被使用的 web 项目访问到,融合进 url mappings 中。
要想去掉干扰,可以将插件中无用的 url mappings 注释掉即可。

其实 plugin 中的 views GSP 页面、layout GSP 页面也都会融合到父 web 项目中,所以想要去掉干扰,一个方法就是让 plugin 不要提供这些资源。

写错了 Application 的包名、类名

现象是访问设定的 url 居然报告 404.

在 UrlMappings 类中设置的 mapping 断点不工作,怀疑没有加载 mapping 配置。

正常时,UrlMapping 类会被 org.grails.web.mapping.DefaultUrlMappingEvaluator#evaluateMappings(groovy.lang.Closure) 加载。

分析过程:
UrlMappings 配置是这个 FactoryBean 调用的
org.grails.web.mapping.UrlMappingsHolderFactoryBean#afterPropertiesSet

发现错误原因:
原来是在 vlog-api 项目中的 build.gradle 脚本配置出错了。
写错了 Applicaiton 启动类的包名,使用了插件中的 Application 类,导致使用了插件的 UrlMapping 从而导致找不到 controller。

springBoot {
    mainClassName = 'vlog.Application'
}

改为

springBoot {
    mainClassName = 'vlog_api.Application'
}

问题解决!

猜你喜欢

转载自blog.csdn.net/yangbo_hr/article/details/105515569