Spring MVC对控制器映射非常困惑

4
使用基于注解的控制器映射。
@Controller
public class AlertsController {

  @RequestMapping(value="create", method=RequestMethod.GET)
  public void create(HttpServletRequest request, Model model) {
  }
}

当访问 alerts/create 时,我收到消息 你的处理程序是否实现了像控制器这样的受支持接口? 这似乎很奇怪,并且与文档所说的相反。
因此,我在类中添加了一个 RequestMapping:
@Controller
@RequestMapping("/alerts")
public class AlertsController {

  @RequestMapping(value="create", method=RequestMethod.GET)
  public void create(HttpServletRequest request, Model model) {
  }
}

这样做是可以的。虽然我不应该需要使用@RequestMapping,但我确实需要它。现在,情况变得有些奇怪。我真正想要将其映射到“/profile/alerts”,所以我将其更改为:

@Controller
@RequestMapping("/profile/alerts")
public class AlertsController {

  @RequestMapping(value="create", method=RequestMethod.GET)
  public void create(HttpServletRequest request, Model model) {
  }
}

当我访问profile/alerts/create时,出现了404错误,但是由于某种原因它仍然被映射到/alerts/create!?!?!

我将其更改为:

@Controller
@RequestMapping("foobar")
public class AlertsController {

  @RequestMapping(value="create", method=RequestMethod.GET)
  public void create(HttpServletRequest request, Model model) {
  }
}

这很奇怪,也非常不方便。有没有办法来解决这个问题,或者甚至调试一下是怎么回事?

2个回答

4
在你的第一个片段中,你忽略了前导的/。应该是这样的:@RequestMapping(value="/create", method=RequestMethod.GET) 现在你需要将第三个片段更改为:
@Controller
public class AlertsController {

  @RequestMapping(value="/profile/alerts/create", method=RequestMethod.GET)
  public void create(HttpServletRequest request, Model model) {
  }
}

此外,由于您正在创建一个期望DispatcherServlet回退到默认视图名称“profile/alerts/create”的void方法,因此它将与适当的视图解析器结合使用。例如,
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
</bean>

可能出现了404错误。


我有视图解析器,它确实起作用。奇怪的是,我认为方法上的@RequestMapping注释是类级别注释的细化;但事实似乎并非如此。 - davetron5000

0

您可以在类注释和更细粒度的方法上进行URL匹配。类级别的注释会被添加到方法级别的注释之前。

@Controller
@RequestMapping(value = "/admin")
public class AdminController {

  @RequestMapping(value = "/users", method = RequestMethod.GET)
  /* matches on /admin/users */
  public string users() {  ...  }
}

它非常接近您的原始第三个片段,只是您忘记了一个前导的 /。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接