如何提取URI中的路径参数值? [英] How to extract path parameter value in URI?

查看:50
本文介绍了如何提取URI中的路径参数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提取HttpServletRequest中的路径参数值

I want to extract the path parameter value in HttpServletRequest

示例网址:abc.api.com/learn/sections/{sectionId}/assignments/{assignmentId}

Sample URL: abc.api.com/learn/sections/{sectionId}/assignments/{assignmentId}

sectionString = Optional.ofNullable(request.getServletPath().split("/")[3]);

我尝试通过拆分 URI 路径来提取部分 ID,但此 URI 可以更改.有没有人对此有可靠的解决方案?谢谢

I try to extract section id by splitting the URI path, but this URI can be changed. Does anybody have solid solutions for this? Thanks

推荐答案

假设 sectionId 总是在 sections 之后,你可以使用一个简单的正则表达式,例如

Assuming that sectionId comes always after sections, you can use a simple regex, e.g.

String uri = "abc.api.com/learn/sections/asdf-987/assignments/dsfwq98r7sdfg";
Matcher m = Pattern.compile(".*\\/sections\\/([a-zA-Z0-9-]+)(\\/?).*").matcher(uri);
if (m.matches()) {
    System.out.println(m.group(1)); //asdf-987
}

(这里假设 UUID 的格式为 aaa-AAAA-9999)

(This assumes that the UUID has a format aaa-AAAA-9999)

您可以对 assignmentId 执行类似的操作,甚至可以在 1 个正则表达式中执行此操作

You can do it similarly for assignmentId, or even do it in 1 regex

这篇关于如何提取URI中的路径参数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆