Spring MVC-在DispatcherServlet中找不到HTTP请求的映射

时间:2018-12-31 10:22:50

标签: java spring rest spring-mvc

我正在将Node.js的API后端重写为Spring。这是我有史以来第一个Spring REST API后端应用程序。我想使其尽可能简单,以避免遵循the Spring documentation

来使用.xml(s)

此后端至今仅具有一个控制器和一项服务。整个应用程序并不旨在提供任何网页,而仅用于REST API。

我首先根据AbstractAnnotationConfigDispatcherServletInitializerWebMvcConfigurerAdapter编写了一个简单的配置:

@Configuration
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{MvcConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

//---------------------------------------------------------------

@Configuration
@EnableWebMvc
@ComponentScan("com.root.package")
@EnableAspectJAutoProxy
public class MvcConfig extends WebMvcConfigurerAdapter {
   //I think I may not need anything inside here, right?
}

...以及控制器...

@Controller("/locale")
public class LocaleController {

    @Autowired
    private LocaleService localeService;

    @RequestMapping(value = "/labels", method = RequestMethod.GET)
    public @ResponseBody List<Label> getAll() {
        return localeService.getAll();
    }
}

它在Tomcat上启动,我可以对其进行调试。日志显示Mapped "{[/labels],methods=[GET]}"Mapped URL path [/locale] onto handler '/locale',但一旦我由邮递员致电,我就会看到No mapping found for HTTP request with URI [/myapp/locale/labels] in DispatcherServlet with name 'dispatcher'

每项研究都使我进入Why does Spring MVC respond with a 404 and report "No mapping found for HTTP request with URI [...] in DispatcherServlet"?-但是-有点冗长,并且...几乎每个书面概念都基于我已经关注的Spring文档,因为我不了解Spring:)< / p>

我确信我的问题有一个更简单的解决方案。我想念的是什么?

1 个答案:

答案 0 :(得分:2)

您在控制器定义上犯了一个小错误。 您写道:

@Controller("/locale")
public class LocaleController {

    @Autowired
    private LocaleService localeService;

    @RequestMapping(value = "/labels", method = RequestMethod.GET)
    public @ResponseBody List<Label> getAll() {
        return localeService.getAll();
    }
}

这意味着spring将创建的bean的名称为“ / locale”;如果您希望控制器“回答”路径/ locale / labels,则必须以这种方式编写控制器:

@Controller
@RequestMapping("/locale")
public class LocaleController {

    @Autowired
    private LocaleService localeService;

    @RequestMapping(value = "/labels", method = RequestMethod.GET)
    public @ResponseBody List<Label> getAll() {
        return localeService.getAll();
    }
}

通过这种方式,您告诉spring控制器LocaleController将回答所有前缀为/locale的请求;其中的每个方法都会根据调用路径被调用