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

时间:2009-11-28 02:40:20

标签: java model-view-controller spring annotations

使用基于注释的控制器映射。

@Controller
public class AlertsController {

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

访问alerts/create时,收到消息Does your handler implement a supported interface like Controller?。这看起来很奇怪,与文档所说的相反。

所以,我在课程中添加RequestMapping

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

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

然后,这是有效的。我不应该@RequestMapping,但我确实需要@Controller @RequestMapping("/profile/alerts") public class AlertsController { @RequestMapping(value="create", method=RequestMethod.GET) public void create(HttpServletRequest request, Model model) { } } 。现在,事情变得奇怪了。我真的想把它映射到`/ profile / alerts',所以我把它改成了这个:

profile/alerts/create

我在转到/alerts/create时收到404,但由于某种原因仍然映射到@Controller @RequestMapping("foobar") public class AlertsController { @RequestMapping(value="create", method=RequestMethod.GET) public void create(HttpServletRequest request, Model model) { } } ?!?!?!

我将其更改为:

{{1}}

这很奇怪,非常不方便。任何人都有办法解决这个问题,甚至调试正在发生的事情?

2 个答案:

答案 0 :(得分: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) {
  }
}

此外,正在制作方法void,期望DispatcherServlet回退到默认视图名称“profile / alerts / create”。然后将它与合适的视图解析器结合使用。例如,

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
</bean>

你有404,可能是。

答案 1 :(得分:0)

您可以对类注释进行url匹配,也可以对方法进行更精细的匹配。类级别注释前置于方法级别注释

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

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

它非常接近您原来的第三个片段,除非您忘记了领先的/.

相关问题