Spring Boot - 当我调用API时,它会给出404错误

时间:2018-03-22 04:13:01

标签: java spring hibernate rest spring-boot

我创建了一个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

POSTMAN回复

    {
    "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错误

7 个答案:

答案 0 :(得分:1)

您应该将控制器更改为:

@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

答案 1 :(得分:1)

您的邮递员要求路径--- "path": "/telematics-fleet/app/test",但您的控制器路径应为"path": "/app/test"。所以有一个错配。

答案 2 :(得分:1)

尝试删除上下文

 http://localhost:8080/app/test

如果使用spring boot插件运行它,并且尚未在元文件中配置上下文,则Spring引导在默认上下文中运行

答案 3 :(得分:1)

项目名称不会自动添加到Spring Boot的上下文路径中,默认情况下为/。如果您确实想要添加它,请在.properties文件中设置以下内容:

server.servlet.contextPath=/telematics-fleet

或者对于2.0之前版本的Spring Boot:

server.contextPath=/telematics-fleet

如果没有,则只需从请求中删除该部分,直接点击/app/test

答案 4 :(得分:1)

将SpringBoot应用程序部署到容器时,需要记住两点:

1. 应用程序的起点:如果要将SprinBoot应用程序部署到任何servlet container(例如Tomcat),您的入门级必须扩展 SpringBootServletInitializer,以便容器可以找到应用程序的起点

@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);
    }

}
  1. Tomcat上成功部署后,您应该在所有资源URL之前添加应用程序名称前缀。
  2. 示例:localhost:8080/Application_Name/app/test

    额外提示:在Spring 4.3之后,您可以@GetMapping替换@RequestMapping(method = RequestMethod.GET)

    示例:@Getmapping("/test")

答案 5 :(得分:0)

在我的项目中,这是因为pom中缺少依赖项。

  

spring-boot-starter-web

在日志中查找Servlet dispatcherServlet mapped to [/],如果它不存在,则意味着缺少必需的依赖项

答案 6 :(得分:0)

有类似的问题。对我来说,Eclipse中的项目名称与application.properties中提到的名称不同。

将eclipse项目重新命名为与application.properties中的项目相同的名称