java 我可以在视图层中找到 spring mvc 控制器的 URL 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1082759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:06:30  来源:igfitidea点击:

Can I find the URL for a spring mvc controller in the view layer?

javaspringjspspring-mvc

提问by Vasil

I think what I need is called reverse url resolution in Django. Lets say I have an AddUserController that goes something like this:

我认为我需要的是 Django 中的反向 url 解析。假设我有一个像这样的 AddUserController:

@Controller
@RequestMapping("/create-user")
public class AddUserController{ ... }

What I want is some way to dynamically find the url to this controller or form a url with parameters to it from the view (JSP), so I don't have to hardcode urls to controllers all over the place. Is this possible in Spring MVC?

我想要的是某种方式来动态查找此控制器的 url 或从视图 (JSP) 中形成一个带有参数的 url,因此我不必到处将 url 硬编码到控制器。这在 Spring MVC 中可能吗?

回答by jottos

Have you considered having a bean that aggregates all of the controller URLs you need into a HashMap and then adding this controller/URL Map to any model that requires it? Each Spring controller has the ability to call an init() method, you could have each controller add it's name and URL to the controller/URL map in the init() methods so it would be ready to use when the controllers go live.

您是否考虑过使用一个 bean 将您需要的所有控制器 URL 聚合到一个 HashMap 中,然后将此控制器/URL 映射添加到任何需要它的模型中?每个 Spring 控制器都可以调用 init() 方法,您可以让每个控制器将其名称和 URL 添加到 init() 方法中的控制器/URL 映射中,以便在控制器上线时准备好使用。

回答by Mr.Desert Fox

Can solve with Java Reflection API. By Creating Custom Tag library. methods looks like this

可以用Java Reflection API 解决。通过创建自定义标签库。方法看起来像这样

Class c = Class.forName("Your Controller");

            for(Method m :c.getMethods()){
                if(m.getName()=="Your Method"){
                    Annotation cc = m.getAnnotation(RequestMapping.class);
                    RequestMapping rm = (RequestMapping)cc;
                    for(String s:rm.value()){
                        System.out.println(s);
                    }
                }
            }


Possible Problem You Can Face is

您可能面临的问题是

1.Path Variable > Like this /pet/show/{id} so set of path name & value should be support then replace this String.replace() before return url

1.Path Variable > 像这样 /pet/show/{id} 所以应该支持路径名和值的集合然后在返回 url 之前替换这个 String.replace()

2.Method Overriding > only one method is no problem. if Method override Need to give support sequence of Parameter Type That you really want like Method.getParametersType()

2.Method Overriding > 只有一种方法没问题。如果 Method override 需要提供您真正想要的参数类型的支持序列,例如 Method.getParametersType()

3.Multiple Url to Single Method> like @RequestMapping(value={"/", "welcome"}). so easy rule is pick first one.

3.Multiple Url to Single Method>如@RequestMapping(value={"/", "welcome"})。这么简单的规则就是选择第一个。

4.Ant Like Style Url > Like this *.doto solve this is use multiple url by placing ant like style in last eg. @RequestMapping(value={"/pet","/pet/*.do"})

4.Ant Like Style Url > 像这样*.do解决这个问题是通过在最后一个例子中放置ant like style来使用多个url。@RequestMapping(value={"/pet","/pet/*.do"})



So Possible link tag style is

所以可能的链接标签样式是

<my:link controller="com.sample.web.PetController" method="show" params="java.lang.Integer">
<my:path name="id" value="1" />
</my:link>

Where parmas attribute is optional if there is no method override.

如果没有方法覆盖,则 parmas 属性是可选的。



May be I left to think about some problem. :)

可能是我留下来思考一些问题。:)

回答by Chiwai Chan

You can get access to the request object in any JSP file without having to manually wire in or manage the object into the JSP. so that means you can get the url path off the request object, have a google into JSP implicit objects.

您可以访问任何 JSP 文件中的请求对象,而无需手动将对象连接或管理到 JSP 中。所以这意味着你可以从请求对象中获取 url 路径,让谷歌进入 JSP 隐式对象。

Here is a page to get you started http://www.exforsys.com/tutorials/jsp/jsp-implicit-and-session-objects.html

这是一个让您入门的页面http://www.exforsys.com/tutorials/jsp/jsp-implicit-and-session-objects.html

回答by ptomli

I would probably try to build a taglib which inspects the annotations you're using in order to find a suitable match:

我可能会尝试构建一个 taglib 来检查您正在使用的注释以找到合适的匹配:

<x:url controller="myController">
    <x:param name="action" value="myAction"/>
</x:url>

Taglib code might be something roughly like

Taglib 代码可能大致类似于

  1. Ask Spring for configured beans with the @Controller annotation
  2. Iterate in some suitable order looking for some suitable match on the controller class or bean name
  3. If the @RequestMapping includes params, then substitute them
  4. Return the string
  1. 使用 @Controller 批注向 Spring 请求配置的 bean
  2. 以某种合适的顺序进行迭代,在控制器类或 bean 名称上寻找合适的匹配
  3. 如果@RequestMapping 包含参数,则替换它们
  4. 返回字符串

That might work for your specific case (@RequestMapping style) but it'll likely get a bit hairy when you have multiple mappings. Perhaps a custom annotation would make it easier.

这可能适用于您的特定情况(@RequestMapping 样式),但是当您有多个映射时,它可能会有点麻烦。也许自定义注释会使其更容易。

Edit:

编辑:

AbstractUrlHandlerMapping::getHandlerMap, which is inherited by the DefaultAnnotationHandlerMapping you're most likely using, returns a Map of URL to Handler

AbstractUrlHandlerMapping::getHandlerMap 由您最有可能使用的 DefaultAnnotationHandlerMapping 继承,返回一个映射的 URL 给 Handler

Return the registered handlers as an unmodifiable Map, with the registered path as key and the handler object (or handler bean name in case of a lazy-init handler) as value.

将注册的处理程序作为不可修改的 Map 返回,注册路径作为键,处理程序对象(或延迟初始化处理程序的处理程序 bean 名称)作为值。

So you could iterate over that looking for a suitable match, where "suitable match" is whatever you want.

因此,您可以迭代寻找合适的匹配项,其中“合适的匹配项”是您想要的任何内容。

回答by ptomli

I submitted an enhancement request for this back in May. You can follow/vote/comment here: http://jira.springsource.org/browse/SPR-5779

我在 5 月份提交了对此的增强请求。你可以在这里关注/投票/评论:http: //jira.springsource.org/browse/SPR-5779

回答by Brian Clozel

The problem with this is that there's no central router in SpringMVC where all routes are registered and ordered. Then reverse routing is not a static process and route resolution in the view layer can be hard to integrate.

这样做的问题是 SpringMVC 中没有中央路由器来注册和排序所有路由。然后反向路由不是一个静态过程,视图层中的路由解析可能很难集成。

Check out this projectfor a centralized router (like rails) and reverse routing in the view layer.

在视图层中查看此项目以获取集中式路由器(如 rails)和反向路由。

回答by Adam Gent

Spring HATEOS library allows you to make links to Controllers.

Spring HATEOS 库允许您链接到控制器。

For a long time I have thought about implementing something like this using CGLib proxies but was too lazy. It appears Spring HATEOS librarywill allow you to do it the proxy way and variety of other ways.

很长一段时间以来,我一直在考虑使用 CGLib 代理来实现这样的东西,但太懒了。看来Spring HATEOS 库将允许您以代理方式和其他各种方式进行操作。