Spring Boot - 当我调用 API 时,它给出 404 错误
Posted
技术标签:
【中文标题】Spring Boot - 当我调用 API 时,它给出 404 错误【英文标题】:Spring Boot - When I call API, its gives 404 error 【发布时间】:2018-08-31 09:43:00 【问题描述】:我创建了一个 Spring Boot 应用程序。当我在嵌入式 tomcat 中部署 jar 文件并调用测试 API 时,它会出现 404 错误。我可以知道为什么它会给出错误吗?
主类
package com.telematics.fleet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages="com.telematics.fleet.controller", "com.telematics.fleet.repository",
"com.telematics.fleet.service","com.telematics.fleet.utility")
public class TelematicsFleetApplication
public static void main(String[] args)
SpringApplication.run(TelematicsFleetApplication.class, args);
控制器类
package com.telematics.fleet.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/app")
public class FleetAppController
@RequestMapping(value="/test", method=RequestMethod.GET)
public String test()
System.out.println("Called test API");
return "Success";
控制台
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/Users/dell/.m2/repository/ch/qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/Users/dell/.m2/repository/org/slf4j/slf4j-log4j12/1.7.25/slf4j-log4j12-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
The Class-Path manifest attribute in C:\Users\dell\.m2\repository\com\mchange\c3p0\0.9.5.2\c3p0-0.9.5.2.jar referenced one or more files that do not exist: file:/C:/Users/dell/.m2/repository/com/mchange/c3p0/0.9.5.2/mchange-commons-java-0.2.11.jar
08:22:29.726 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
08:22:29.738 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot/target/classes/, /spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/]
08:22:29.739 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/C:/Malya/Git_Homes/telematics-fleet/target/classes/]
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.0.RELEASE)
2018-03-22 08:22:31.881 INFO 252 --- [ restartedMain] c.t.fleet.TelematicsFleetApplication : Starting TelematicsFleetApplication on admin with PID 252 (C:\Malya\Git_Homes\telematics-fleet\target\classes started by dell in C:\Malya\Git_Homes\telematics-fleet)
2018-03-22 08:22:31.889 INFO 252 --- [ restartedMain] c.t.fleet.TelematicsFleetApplication : No active profile set, falling back to default profiles: default
2018-03-22 08:22:32.280 INFO 252 --- [ restartedMain] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@795b4bba: startup date [Thu Mar 22 08:22:32 IST 2018]; root of context hierarchy
2018-03-22 08:22:47.336 INFO 252 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$8c439cf8] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-03-22 08:22:51.865 INFO 252 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-03-22 08:22:52.015 INFO 252 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-03-22 08:22:52.016 INFO 252 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.28
2018-03-22 08:22:52.076 INFO 252 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_162\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre1.8.0_162/bin/server;C:/Program Files/Java/jre1.8.0_162/bin;C:/Program Files/Java/jre1.8.0_162/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;c:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\Git\cmd;C:\Program Files (x86)\Skype\Phone\;C:\Program Files (x86)\Cypress\EZ-USB FX3 SDK\1.3\ARM GCC\bin\;C:\Program Files (x86)\Cypress\EZ-USB FX3 SDK\1.3\eclipse\jre\bin\;C:\Program Files (x86)\sbt\bin;C:\modeltech64_10.2c\win64;C:\Program Files (x86)\CodeBlocks\MinGW\bin;C:\Program Files (x86)\CodeBlocks\MinGW;C:\myrWork\ztex-160513\sp3anTest\aes220_win_files_160502-1\aes220_win_files\DLL;C:\myrWork\ztex-160513\sp3anTest\aes220_win_files_160502-1\aes220_win_files\libs\MS32;C:\myrWork\eMMCModel\ss_emmc\eMMC_vip\sdio\rlm\win_64;C:\workspace\eMMCModel\ss_emmc\eMMC_vip\sdio\sv\examples\sim;C:\Malya\tool\sts-bundle\sts-3.9.2.RELEASE;;.]
2018-03-22 08:22:52.790 INFO 252 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-03-22 08:22:52.791 INFO 252 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 20525 ms
2018-03-22 08:23:00.377 INFO 252 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-03-22 08:23:00.407 INFO 252 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-03-22 08:23:00.408 INFO 252 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-03-22 08:23:00.409 INFO 252 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-03-22 08:23:00.410 INFO 252 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-03-22 08:23:00.411 INFO 252 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpTraceFilter' to: [/*]
2018-03-22 08:23:00.412 INFO 252 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'webMvcMetricsFilter' to: [/*]
2018-03-22 08:23:01.619 INFO 252 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2018-03-22 08:23:03.674 INFO 252 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2018-03-22 08:23:04.327 INFO 252 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2018-03-22 08:23:04.469 INFO 252 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2018-03-22 08:23:05.269 INFO 252 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate Core 5.2.14.Final
2018-03-22 08:23:05.284 INFO 252 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2018-03-22 08:23:05.721 INFO 252 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations 5.0.1.Final
2018-03-22 08:23:08.342 INFO 252 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.mysql5Dialect
2018-03-22 08:23:16.185 INFO 252 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-03-22 08:23:34.747 INFO 252 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@795b4bba: startup date [Thu Mar 22 08:22:32 IST 2018]; root of context hierarchy
2018-03-22 08:23:36.160 WARN 252 --- [ restartedMain] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2018-03-22 08:23:37.239 INFO 252 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "[/app/test],methods=[GET]" onto public java.lang.String com.telematics.fleet.controller.FleetAppController.test()
2018-03-22 08:23:37.380 INFO 252 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "[/error]" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-03-22 08:23:37.383 INFO 252 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "[/error],produces=[text/html]" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-03-22 08:23:38.325 INFO 252 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-22 08:23:38.326 INFO 252 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-22 08:23:39.279 INFO 252 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-22 08:23:40.156 WARN 252 --- [ restartedMain] ion$DefaultTemplateResolverConfiguration : Cannot find template location: classpath:/templates/ (please add some templates or check your Thymeleaf configuration)
2018-03-22 08:23:46.453 INFO 252 --- [ restartedMain] org.quartz.impl.StdSchedulerFactory : Using default implementation for ThreadExecutor
2018-03-22 08:23:46.581 INFO 252 --- [ restartedMain] org.quartz.core.SchedulerSignalerImpl : Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
2018-03-22 08:23:46.582 INFO 252 --- [ restartedMain] org.quartz.core.QuartzScheduler : Quartz Scheduler v.2.3.0 created.
2018-03-22 08:23:46.588 INFO 252 --- [ restartedMain] org.quartz.simpl.RAMJobStore : RAMJobStore initialized.
2018-03-22 08:23:46.593 INFO 252 --- [ restartedMain] org.quartz.core.QuartzScheduler : Scheduler meta-data: Quartz Scheduler (v2.3.0) 'quartzScheduler' with instanceId 'NON_CLUSTERED'
Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
NOT STARTED.
Currently in standby mode.
Number of jobs executed: 0
Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 10 threads.
Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.
2018-03-22 08:23:46.595 INFO 252 --- [ restartedMain] org.quartz.impl.StdSchedulerFactory : Quartz scheduler 'quartzScheduler' initialized from an externally provided properties instance.
2018-03-22 08:23:46.595 INFO 252 --- [ restartedMain] org.quartz.impl.StdSchedulerFactory : Quartz scheduler version: 2.3.0
2018-03-22 08:23:46.596 INFO 252 --- [ restartedMain] org.quartz.core.QuartzScheduler : JobFactory set to: org.springframework.boot.autoconfigure.quartz.AutowireCapableBeanJobFactory@629a27c7
2018-03-22 08:23:47.067 INFO 252 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2018-03-22 08:23:47.271 INFO 252 --- [ restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "[/actuator/health],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-03-22 08:23:47.274 INFO 252 --- [ restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "[/actuator/info],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-03-22 08:23:47.279 INFO 252 --- [ restartedMain] s.b.a.e.w.s.WebMvcEndpointHandlerMapping : Mapped "[/actuator],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]" onto protected java.util.Map<java.lang.String, java.util.Map<java.lang.String, org.springframework.boot.actuate.endpoint.web.Link>> org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping.links(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-03-22 08:23:48.079 INFO 252 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-03-22 08:23:48.086 INFO 252 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'dataSource' has been autodetected for JMX exposure
2018-03-22 08:23:48.130 INFO 252 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2018-03-22 08:23:48.207 INFO 252 --- [ restartedMain] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147483647
2018-03-22 08:23:48.208 INFO 252 --- [ restartedMain] o.s.s.quartz.SchedulerFactoryBean : Starting Quartz Scheduler now
2018-03-22 08:23:48.209 INFO 252 --- [ restartedMain] org.quartz.core.QuartzScheduler : Scheduler quartzScheduler_$_NON_CLUSTERED started.
2018-03-22 08:23:48.464 INFO 252 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2018-03-22 08:23:48.488 INFO 252 --- [ restartedMain] c.t.fleet.TelematicsFleetApplication : Started TelematicsFleetApplication in 78.687 seconds (JVM running for 81.635)
2018-03-22 08:24:55.653 INFO 252 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-03-22 08:24:55.654 INFO 252 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2018-03-22 08:24:55.755 INFO 252 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 101 ms
邮递员回复
"timestamp": "2018-03-22T03:06:40.138+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/telematics-fleet/app/test"
属性文件
spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=true
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword
在控制台服务器运行正常,但尝试访问 api 时出现 404 错误
【问题讨论】:
你使用的端口是什么? 我在您的资源映射中没有看到/telematics-fleet
?
您尝试访问的完整 URL 是什么?
+1 这个问题仅用于格式和代码/输出示例。格式和详细。干杯!
起初,我是 Spring Boot 应用程序的新手。项目名称 - telematics-fleet,我假设默认端口是 8080。这是邮递员访问的 URL -localhost:8080/telematics-fleet/app/test@PrabinPaudel
【参考方案1】:
有类似的问题。对我来说,Eclipse 中的项目名称与 application.properties 中提到的项目名称不同。
将 eclipse 项目重命名为与 application.properties 中相同的项目解决了该问题
【讨论】:
你的意思是spring.application.name
property 吗?【参考方案2】:
在我的项目中,是因为pom中缺少依赖。
spring-boot-starter-web
在日志中查找Servlet dispatcherServlet mapped to [/]
,如果不存在,则表示缺少所需的依赖项
【讨论】:
【参考方案3】:项目名在Spring Boot中不会自动添加到上下文路径中,默认为/
。如果您确实想添加它,请在 .properties 文件中设置以下内容:
server.servlet.contextPath=/telematics-fleet
或者对于 Spring Boot 2.0 之前的版本:
server.contextPath=/telematics-fleet
如果没有,那么只需从您的请求中删除该部分,直接点击/app/test
。
【讨论】:
server.contextPath 现已弃用,使用 server.servlet.contextPath【参考方案4】:在将 SpringBoot 应用程序部署到容器时需要牢记两点:
1.应用程序的起点:如果您将SprinBoot
应用程序部署到任何servlet container
(如Tomcat
),您的入门类必须扩展 @ 987654321@,这样容器就可以找到你应用的起点
@SpringBootApplication
public class TelematicsFleetApplication extends SpringBootServletInitializer
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application)
return application.sources(TelematicsFleetApplication .class);
public static void main(String[] args) throws Exception
SpringApplication.run(TelematicsFleetApplication .class, args);
-
在
Tomcat
上成功部署后,您应该在所有资源 URL 之前添加应用程序名称前缀。
例如:localhost:8080/Application_Name/app/test
额外提示:在Spring 4.3
之后,您可以将@RequestMapping(method = RequestMethod.GET)
替换为@GetMapping
例如:@Getmapping("/test")
【讨论】:
主啊!接受我诚挚的问候。你用你的仁慈知识拯救了我们的生命.. 乐于助人:)【参考方案5】:尝试删除上下文
http://localhost:8080/app/test
如果你使用 spring boot 插件运行它,并且没有在 meta 文件中配置上下文,spring boot 在默认上下文上运行
【讨论】:
【参考方案6】:您的邮递员请求路径--- "path": "/telematics-fleet/app/test"
但您的控制器路径应该是 "path": "/app/test"
。所以有一个错配。
【讨论】:
【参考方案7】:您应该将控制器更改为:
@RestController
@RequestMapping("/telematics-fleet/app")
public class FleetAppController
@RequestMapping(value="/test", method=RequestMethod.GET)
public String test()
System.out.println("Called test API");
return "Success";
当前调用没有指向正确的资源。
请注意日志指出您的服务器已启动并以 root 身份指向 /
而不是 /telematics-fleet
。
您可以做的另一件事是保持控制器不变,并在application.properties
中添加一个新属性:
server.contextPath=/telematics-fleet
【讨论】:
以上是关于Spring Boot - 当我调用 API 时,它给出 404 错误的主要内容,如果未能解决你的问题,请参考以下文章
从 Ajax 调用 Spring Boot Rest API 时出现 CORS 错误
Spring boot 3问题:为什么不能使用Postman和Frontend调用API调用API,然后得到空数组?
如何在外部 tomcat 中部署 Spring-boot REST API
在spring boot应用程序中从自己的rest api调用另一个rest api