gpt4 book ai didi

java - Spring MVC Controller 配置 - 混合注释和 XML @PathVariable

转载 作者:行者123 更新时间:2023-11-29 03:54:50 25 4
gpt4 key购买 nike

我正在使用 Spring MVC 框架 (v3) 开发网络应用程序。

目前我定义了几个 Controller 类——我通过扩展 MultiActionController 创建了它们,然后在我的 web mvc XML 配置中定义了 bean 和 URL 映射:

问题 Controller .java:

public class QuestionController extends MultiActionController implements InitializingBean 
{

webmvc-config.XML

<bean id="questionController" class="com.tmm.enterprise.microblog.controller.QuestionController"></bean>
...
<bean id="fullHandlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="alwaysUseFullPath" value="true" />
<property name="mappings">
<props>
<prop key="/question/**">questionController</prop>
</props>
</property>
</bean>

这很好用,我在我的 Controller 中定义了与被调用的 URL 相匹配的方法,并且一切正常(例如,我有一个 list(..) 方法,当我浏览时它被正确执行到 /question/list)。

但是,对于这个特定的 Controller ,我想在 Spring 中使用 @PathVariable 选项来允许变量 URL(例如,我想要一个 details(..)方法,当我调用 /question/detail/9999 - 其中 9999 是执行方法的问题 ID)。我尝试按如下方式使用它:

问题 Controller .java:

@RequestMapping("/detail/{questionId}")
public ModelAndView detail(@PathVariable("questionId") long questionId, HttpServletRequest request, HttpServletResponse response) throws Exception{

但是,当我运行上面的命令并得到:

Could not find @PathVariable [questionId] in @RequestMapping

有没有人遇到过这个?可以将 RequestMapping 注释与现有的 XML 配置的 URL 映射混合使用吗?

最佳答案

这是来自 DefaultAnnotationHandlerMapping 类的评论,如果我没看错评论,如果您在 QuestionController.java 的顶部添加 @RequestMapping,它可能会解决您的问题

带注释的 Controller 通常标有 {@link Controller} 构造型在类型级别。当 {@link RequestMapping} 是时,这不是绝对必要的在类型级别应用(因为这样的处理程序通常实现 {@link org.springframework.web.servlet.mvc.Controller} 接口(interface))。然而, {@link Controller} 是检测 {@link RequestMapping} 注释所必需的 如果 {@link RequestMapping} 不存在于类型级别,则在方法级别

编辑

你可以做这样的事情,将 uri 的 /question 部分移到顶部并保留方法级别的细节部分

@RequestMapping("/question")
public class QuestionController
{
@RequestMapping("/detail/{questionId}")
public ModelAndView detail(@PathVariable("questionId") long questionId, HttpServletRequest request, HttpServletResponse response) throws Exception{

}

关于java - Spring MVC Controller 配置 - 混合注释和 XML @PathVariable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6953989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com