无论我做什么,Java控制器始终会返回404

如何解决无论我做什么,Java控制器始终会返回404

我遵循的是Spring Boot文档中的一个示例,由于某种原因,java控制器总是返回404

这是我尝试过的

package com.example.accessingdatamysql;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller // This means that this class is a Controller
@RequestMapping(path="/demo") // This means URL's start with /demo (after Application path)
public class MainController {
  @Autowired // This means to get the bean called userRepository
         // Which is auto-generated by Spring,we will use it to handle the data
  private UserRepository userRepository;

  @PostMapping(path="/add") // Map ONLY POST Requests
  public @ResponseBody String addNewUser (@RequestParam String name,@RequestParam String email) {
    // @ResponseBody means the returned String is the response,not a view name
    // @RequestParam means it is a parameter from the GET or POST request

    User n = new User();
    n.setName(name);
    n.setEmail(email);
    userRepository.save(n);
    return "Saved";
  }

  @GetMapping(path="/all")
  public @ResponseBody Iterable<User> getAllUsers() {
    // This returns a JSON or XML with the users
    return userRepository.findAll();
  }
}

这是spring boot https://spring.io/guides/gs/accessing-data-mysql/

给出的示例

然后我也尝试过

@RestController
@RequestMapping("/demo")
public class GreetingClass {

    @GetMapping("/greeting")
    public String getGreeting() {
        return "hello";
    }
}

.pom文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.braintobytes</groupId>
    <artifactId>Finance_microservice</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Finance_microservice</name>
    <description>Finance service</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.persistence/javax.persistence-api -->
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>javax.persistence-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

我知道这很奇怪,我按照页面上的指示进行了所有设置,但显然没有任何效果,并且我还检查了类似的其他问题,但没有一个回答我的问题。

tomcat服务器似乎被命中了,因为它表示我拨打电话时

o.s.web.servlet.DispatcherServlet        : Completed initialization in 9 ms

但是随后我得到这个调用curl'http:// localhost:8080 / demo / greeting'和'http:// localhost:8080 / demo / all'

curl:远程服务器返回错误:(404)找不到。

日志(在第一行中删除了文件路径):

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__,| / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.2.RELEASE)

2020-08-31 08:19:16.508  INFO 20708 --- [           main] c.b.f.FinanceMicroserviceApplication     : Starting FinanceMicroserviceApplication on DESKTOP-A65224I with PID 20708 ()
2020-08-31 08:19:16.510  INFO 20708 --- [           main] c.b.f.FinanceMicroserviceApplication     : No active profile set,falling back to default profiles: default
2020-08-31 08:19:17.096  INFO 20708 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-08-31 08:19:17.101  INFO 20708 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-08-31 08:19:17.101  INFO 20708 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-08-31 08:19:17.150  INFO 20708 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-08-31 08:19:17.150  INFO 20708 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 618 ms
2020-08-31 08:19:17.465  INFO 20708 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-08-31 08:19:17.675  INFO 20708 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-08-31 08:19:17.681  INFO 20708 --- [           main] c.b.f.FinanceMicroserviceApplication     : Started FinanceMicroserviceApplication in 1.328 seconds (JVM running for 1.835)
2020-08-31 08:20:21.893  INFO 20708 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-08-31 08:20:21.893  INFO 20708 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-08-31 08:20:21.905  INFO 20708 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 12 ms

响应:

{
    "timestamp": "2020-08-31T13:20:21.930+00:00","status": 404,"error": "Not Found","message": "","path": "/demo/greeting"
}

如果我这样做,这会起作用:

https://github.com/BraintoByte/Test_App_Stack/tree/master/demo

不同的示例:

我附上了一个不同的示例,其中的层次结构完全相同,但是省略了业务逻辑:

控制器中的代码

package com.braintobytes.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.braintobytes.data.Currency;
import com.braintobytes.data.repository.CurrencyRepository;

@RestController
@RequestMapping("/demo")
public class CurrencyController {
    @Autowired
    private CurrencyRepository currencyRepository;
    
    @GetMapping("/currency")
    public String getCurrency() {
        return "currency";
    }
}

项目层次结构:

enter image description here

与pom相同,并且在application.properties中:

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mydatabase
spring.datasource.username=myusername
spring.datasource.password=mypassword

解决方法

您的控制器在软件包中-com.example.accessingdatamysql

Spring启动启动日志显示您的主要应用程序类c.b.f.FinanceMicroserviceApplication在另一个不相关的程序包层次结构中。

Spring boot建议将主应用程序类放在其他类之上的根包中,以便组件扫描可以立即使用。

如果将com.example软件包保留为根软件包,并将主应用程序类FinanceMicroserviceApplication移至该软件包,那么一切都会按预期进行。

如果您不遵循Spring推荐的软件包层次结构建议,则需要显式指定要使用@SpringBootApplication批注进行扫描的软件包。

,

好的,因此以上建议均无用,尽管我们走在正确的道路上。

按如下方式更改结构:

enter image description here

application.properties中也存在路径问题,因此我进行了如下更改:

spring.datasource.url = jdbc:mysql:// $ {MYSQL_HOST:localhost}

收件人:

jdbc:mysql:// localhost

最后:

package com.braintobytes.finance.data.repository;

import org.springframework.data.repository.CrudRepository;

import com.braintobytes.finance.data.Currency;

public interface CurrencyRepository extends CrudRepository<Currency,Integer> {

}

哇!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-