我可以在视图层中找到spring mvc控制器的URL吗? [英] Can I find the URL for a spring mvc controller in the view layer?

查看:127
本文介绍了我可以在视图层中找到spring mvc控制器的URL吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我需要的是在Django中称为反向URL解析。假设我有一个类似这样的AddUserController:

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

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

我想要的是一些方法动态查找此控制器的URL或从视图(JSP)形成带有参数的url,因此我不必将url硬编码到控制器到处。这是否可以在Spring MVC中使用?

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?

推荐答案

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

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

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>喜欢这个/ pet / show / {id}所以这套路径名称& value应该是支持然后在返回url之前替换此String.replace()

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

2.Method Overriding>只有一个方法没问题。 if Method覆盖需要提供参数类型的支持序列你真正想要的是Method.getParametersType()

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()

3.多个Url到单个方法>像@RequestMapping(value = {/,welcome})。如此简单的规则是第一个选择。

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

4.Ant Like Style Url>像这样 *。做来解决这是使用多个url通过在最后放置类似样式的ant。 @RequestMapping(value = {/ pet,/ pet / * .do})

4.Ant Like Style Url > Like this *.do to solve this is use multiple url by placing ant like style in last eg. @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>

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

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

我可能会想到一些问题。 :)

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

这篇关于我可以在视图层中找到spring mvc控制器的URL吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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