java Spring:控制器@RequestMapping 到jsp

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12647605/
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-31 09:41:34  来源:igfitidea点击:

Spring: Controller @RequestMapping to jsp

javaspringspring-mvc

提问by Chris Irwin

Using Spring 3.1.2

使用 Spring 3.1.2

How do you reference the Annotated value of the CONTROLLER (not method) RequestMapping from a jsp so I can build URL's relative to the Controller. If the method level request mappings are referenced, it will cause my links to not work, so they cannot be part of the this in any way.

您如何从jsp 引用CONTROLLER(不是方法)RequestMapping 的Annotated 值,以便我可以构建相对于Controller 的URL。如果引用了方法级别的请求映射,则会导致我的链接不起作用,因此它们无论如何都不能成为 this 的一部分。

For example (Note that this controller's mapping is "/foo/test"):

例如(注意这个控制器的映射是“/foo/test”):

@Controller
@RequestMapping("/foo/test")
public class FooController {

    @RequestMapping(value="/this", method=RequestMethod.GET)
    public String getThis() {
        return "test/this";
    }

    @RequestMapping(value="/that", method=RequestMethod.GET)
    public String getThat() {
        return "test/that";
    }

    @RequestMapping(value="/other", method=RequestMethod.GET)
    public String getOther() {
        return "test/other";
    }
}

...and from my this.jsp:

...从我的this.jsp:

<%@ taglib uri="http://www.springframework.org/tags" prefix="s"%>
<s:url value="${controllerRequestMapping}" var="baseUrl"/>

<a href="${baseUrl}/that">That</a>
<a href="${baseUrl}/other">Other</a>

The reason I need to access the RequestMapping is because my views may be accessed from multiple Controllers. Note that this controller's mapping is "/bar/test"!

我需要访问 RequestMapping 的原因是我的视图可以从多个控制器访问。注意这个控制器的映射是“/bar/test”!

@Controller
@RequestMapping("/bar/test")
public class BarController {

    @RequestMapping(value="/this", method=RequestMethod.GET)
    public String getThis() {
        return "test/this";
    }

    @RequestMapping(value="/that", method=RequestMethod.GET)
    public String getThat() {
        return "test/that";
    }

    @RequestMapping(value="/other", method=RequestMethod.GET)
    public String getOther() {
        return "test/other";
    }
}

Some of my Controller level request mappings have path variables too, so getting just the string value of the request mapping will not work. It will have to be resolved:

我的一些控制器级别的请求映射也有路径变量,所以只获取请求映射的字符串值是行不通的。必须解决:

@Controller
@RequestMapping("/something/{anything}/test/")
public class SomethingController {
...
}

Update

更新

Maybe if there was a way to modify the context path by appending the Controller request mapping to it BEFORE the Spring URL tag, that would solve the problem.

也许如果有一种方法可以通过在 Spring URL 标记之前附加控制器请求映射来修改上下文路径,那将解决问题。

contextPath = contextPath/controllerRequestMapping

Then, I could do something like this because I believe Spring will automatically retrieve the current context path:

然后,我可以做这样的事情,因为我相信 Spring 会自动检索当前的上下文路径:

<%@ taglib uri="http://www.springframework.org/tags" prefix="s"%>

<a href="<s:url value="/that"/>">That</a>
<a href="<s:url value="/other"/>">Other</a>

This, of course, would be optimal! Ideas? Thoughts...?

这当然是最佳选择!想法?想法……?

Thanks in advance!

提前致谢!

回答by stephen.hanson

You could get the URI using the Servlet API. There is no "Spring" way to do this as far as I know.

您可以使用 Servlet API 获取 URI。据我所知,没有“春天”的方式来做到这一点。

@RequestMapping(value="/this", method=RequestMethod.GET)
public String getThis(HttpServletRequest request, Model m) {
    m.addAttribute("path", request.getRequestURI());
    return "test/this";
}

Then in your JSP:

然后在你的 JSP 中:

<a href="${path}">This</a>

For more information about HttpServletRequest, see the API here.

有关 HttpServletRequest 的更多信息,请参阅此处的 API

回答by Japan Trivedi

According to me there is no difference in putting @RequestMapping annotation at both class level and method level. Instead of that you can have the combined @RequestMapping annotation on top of the method only.

在我看来,在类级别和方法级别放置 @RequestMapping 注释没有区别。取而代之的是,您只能在方法之上使用组合的 @RequestMapping 注释。

So now your method level annotation will be something like this.

所以现在你的方法级别注释将是这样的。

@RequestMapping(value="("/foo/test/this", method=RequestMethod.GET)

or

或者

@RequestMapping(value="("/bar/test/this", method=RequestMethod.GET)

Now since both your methods return the same view you can have just one method for both of them. And in the annotation mapping value instead of foo and bar you can inroduce one path variable {from}. So finally your annotation and the method will be like this.

现在,由于您的两种方法都返回相同的视图,因此您只能为它们使用一种方法。并且在注释映射值而不是 foo 和 bar 中,您可以引入一个路径变量{from}。所以最后你的注释和方法将是这样的。

@RequestMapping(value="("/{from}/test/this", method=RequestMethod.GET)
public String getThis(@PathVariable("from") String from) {       
    return "test/this";       
}

And after doing this in your method you can perform different calculations or operations on based of the runtime value of path variable fromyou get. And in the JSP page you can simple get this value with ${from}.

而在你的方法,这样做后,你可以在基于路径变量的运行值执行不同的计算或操作你。在 JSP 页面中,您可以使用${from}.

Hope this helps you. Cheers.

希望这对你有帮助。干杯。

回答by FFL

See code below to access request mapping, if you are using Spring 3.1 and above. I'm not sure if this is what you require. This is just an attempt and of course i do not know of any straight forward way. Invoke getRequestMappings() from inside a method that has request mapping.

如果您使用的是 Spring 3.1 及更高版本,请参阅下面的代码以访问请求映射。我不确定这是否是您的要求。这只是一种尝试,当然我不知道任何直接的方法。从具有请求映射的方法内部调用 getRequestMappings()。

public class FooController{

    private RequestMappingHandlerMapping handlerMapping = null;

    @Autowired
    public FooController(RequestMappingHandlerMapping handlerMapping){
        this.handlerMapping = handlerMapping;
    }

    public Set<String> getRequestMappings(){
        Map<RequestMappingInfo, HandlerMethod> handlerMap = handlerMapping.getHandlerMethods();
        Iterator<RequestMappingInfo> itr = handlerMap.keySet().iterator();
        while(itr.hasNext()){
            RequestMappingInfo info = itr.next();
            PatternsRequestCondition condition = info.getPatternsCondition();
            Set<String> paths = condition.getPatterns();
            HandlerMethod method = handlerMap.get(info);
            if(method.getMethod().getName().equals(Thread.currentThread().getStackTrace()[2].getMethodName()))
            return paths;

            }
        return new HashSet<String>();
    }



}

回答by Ashok Korlakunta

As of 4.1 every @RequestMapping is assigned a default name based on the capital letters of the class and the full method name. For example, the method getFoo in class FooController is assigned the name "FC#getFoo". This naming strategy isenter code herepluggable by implementing HandlerMethodMappingNamingStrategy and configuring it on your RequestMappingHandlerMapping. Furthermore the @RequestMapping annotation includes a name attribute that can be used to override the default strategy. The Spring JSP tag library provides a function called mvcUrl that can be used to prepare links to controller methods based on this mechanism.

从 4.1 开始,每个 @RequestMapping 都根据类的大写字母和完整方法名称分配了一个默认名称。例如,FooController 类中的方法 getFoo 被分配了名称“FC#getFoo”。enter code here通过实现 HandlerMethodMappingNamingStrategy 并在您的 RequestMappingHandlerMapping 上配置它,这个命名策略是可插入的。此外,@RequestMapping 注释包括一个名称属性,可用于覆盖默认策略。Spring JSP 标记库提供了一个名为 mvcUrl 的函数,可用于准备基于此机制的控制器方法的链接。

For example given:

例如给出:

@RequestMapping("/people/{id}/addresses")
public class MyController {
@RequestMapping("/{country}")
public HttpEntity getAddress(@PathVariable String country) { ... }
}

The following JSP code can prepare a link:

下面的JSP代码可以准备一个链接:

<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
...
<a href="${s:mvcUrl('MC#getPerson').arg(0,'US').buildAndExpand('123')}">Get Address</a>

Make sure you have configured your MVC using either Java Config or XML way and not both the ways. You will get an exception as :more than one RequestMappingInfo HandlerMapping found.

确保您已使用 Java Config 或 XML 方式而不是两种方式配置您的 MVC。您将收到一个异常:发现多个 RequestMappingInfo HandlerMapping。

回答by matt b

There is no built-in way to access the @RequestMapping, but you can simply add the URL to the model and reference it from the view that way.

没有访问 的内置方法@RequestMapping,但您可以简单地将 URL 添加到模型并以这种方式从视图中引用它。