【问题标题】:Spring MVC very confused about controller mappingsSpring MVC 对控制器映射非常困惑
【发布时间】:2010-12-21 03:32:44
【问题描述】:

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

@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,但我需要。现在,事情变得很奇怪。我真的很想把它映射到`/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) {
  }
}

这很奇怪,而且非常不方便。任何人都有办法解决这个问题,甚至调试发生了什么?

【问题讨论】:

    标签: java model-view-controller spring annotations


    【解决方案1】:

    在您的第一个 sn-p 中,您错过了领先的 /。它应该类似于@RequestMapping(value="/create", method=RequestMethod.GET)

    现在你应该把你的第三个 sn-p 改成这个,

    @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,可能是。

    【讨论】:

    • 我有视图解析器,这确实有效。奇怪的是,我认为方法上的@RequestMapping 注释是对类级别注释的改进;好像没有。
    【解决方案2】:

    您可以在类注解上进行 url 匹配,也可以对方法进行更细粒度的匹配。类级别注释被附加到方法级别注释

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

    它非常接近你原来的第三个 sn-p,除了你忘记了一个前导 /。

    【讨论】:

      猜你喜欢
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-27
      • 2018-04-07
      • 2012-05-30
      • 1970-01-01
      • 2020-01-22
      相关资源
      最近更新 更多