簡體   English   中英

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

[英]Spring MVC - no mapping found for HTTP request in DispatcherServlet

我正在將Node.js的API后端重寫為Spring。 這是我有史以來第一個Spring REST API后端應用程序。 我想通過遵循Spring文檔使其盡可能簡單,以避免使用.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'

每種研究都將我引向為何Spring MVC為什么會以404響應並報告“在DispatcherServlet中未找到具有URI的HTTP請求的映射”的問題? -但是-有點冗長,...幾乎所有編寫的概念都基於我已經遵循的Spring文檔,因為我不了解Spring :)

我確信我的問題有一個更簡單的解決方案。 我缺少什么?

您在控制器定義上犯了一個小錯誤。 你寫了:

@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回答所有請求; 其中的每個方法都會根據調用路徑進行調用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM