gpt4 book ai didi

java - 在 Spring MVC 中,如何让 @RequestMapping 工作?

转载 作者:行者123 更新时间:2023-12-02 08:14:16 25 4
gpt4 key购买 nike

在 Spring 3 MVC 中,我有一个称为 RolesController 的 Controller ,它具有用于显示角色列表的 displayRoles()、saveRole() 和 deleteRole() 等方法。

目前,我已成功使用@RequestMapping注解路由/settings/roles/来调用displayRoles()方法,/settings/roles/save/来调用saveRole()方法,等等。

我的代码如下,它可以工作。

@Controller
public class RolesController {

@Transactional
@RequestMapping(value = {"settings/roles/save"}, method = {RequestMethod.POST})
public ModelAndView saveRole(details removed){
//details removed
}

@RequestMapping(value = {"settings/roles/delete"}, method = {RequestMethod.POST})
public ModelAndView deleteRole(details removed){
//details removed
}

@RequestMapping(value = {"settings/roles"}, method = RequestMethod.GET)
public ModelAndView displayRoles(details removed){
//details removed
}

}

但是有两个问题我无法解决:

  1. 我无法映射父目录 /settings/ 来调用 displayRoles() 方法。如果我将 displayRoles 方法的映射更改为 @RequestMapping(value = {"settings","settings/","settings/roles"}, method = RequestMethod.GET) 然后重建并浏览到 URL 中的/settings,我收到 404 错误。为什么我无法映射到“设置”父文件夹?
  2. URL 中的尾部斜杠似乎是必需的。例如,转到 settings/roles/可以,但访问 settings/roles 会导致 404 Page Not Found 错误。

我做错了什么?谢谢! -瑞安

<小时/>附:这里有一些额外的信息...以防有帮助:

在我的 applicationContext-mvc.xml 文件中,我有(以及其他代码):

<!-- Maps request paths to @Controller classes; e.g. a path of /login looks for a controller named LoginController -->
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<property name="order" value="1" />
</bean>
<!-- If no @Controller match, look for @RequestMapping match-->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="order" value="2" />
<property name="defaultHandler">
<!-- If no @RequestMapping match, map path to a view to render; e.g. the "/intro" path would map to the view named "intro" -->
<bean class="org.springframework.web.servlet.mvc.UrlFilenameViewController" />
</property>
</bean>

最佳答案

对于尾部斜杠问题,这可能是版本详细信息:有许多尾部斜杠错误(请参阅 http://jira.springframework.org/browse/SPR-7064https://issues.springsource.org/browse/SPR-5636 ),在 Spring 3.0.3 及更高版本中标记为已修复。

对于 /settings 映射问题,您可能需要执行 @Bill 所做的操作:

@Controller
@RequestMapping(value = {"/settings"})
public class RolesController {

@Transactional
@RequestMapping(value = {"/roles/save"}, method = {RequestMethod.POST})
public ModelAndView saveRole(details removed){
//details removed
}

@RequestMapping(value = {"/roles/delete"}, method = {RequestMethod.POST})
public ModelAndView deleteRole(details removed){
//details removed
}

@RequestMapping(value = {"/","/roles"}, method = RequestMethod.GET)
public ModelAndView displayRoles(details removed){
//details removed
}
}

关于java - 在 Spring MVC 中,如何让 @RequestMapping 工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6740772/

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