当前位置: 首页 > 知识库问答 >
问题:

REST API用于CRUD操作抛出404未找到错误的演示Spring Boot应用程序

房育
2023-03-14

我试图用rest API编写一个与postgres数据库连接的基本应用程序,以执行两个crud操作。当我运行应用程序时,它会成功启动。但是,当我转到url“http://localhost:8080/employees”或http://localhost:8080“时,它显示”无法找到此localhost:8080“。找不到网址为http://localhost:8080/employees的网页。HTTP错误404“。

下面是我的TestApplication.java

package com.ranjana.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.http.HttpStatus;

@SpringBootApplication
@EntityScan(basePackages = {"com.ranjana.test.model"})
@ComponentScan(basePackageClasses = EmployeeController.class)
public class TestApplication implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
    @Override
    public void customize(ConfigurableServletWebServerFactory factory) {
        factory.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN, "/errors/403.html"));
        factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/errors/404.html"));
        factory.addErrorPages(new ErrorPage("/errors/500.html"));
    }

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

}

控制器类-EmployeeController.java:

package com.ranjana.test.controller;

import com.ranjana.test.repositoy.EmployeeRepo;
import com.ranjana.test.exception.ResourceNotFoundException;
import com.ranjana.test.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1")
public class EmployeeController {
    @Autowired
    private EmployeeRepo empRepo;

    @GetMapping("/employees")
    public List<Employee> getAllEmployees(){
        System.out.printf(empRepo.findAll().toString());
        return empRepo.findAll();
    }

    @GetMapping("/employee/{id}")
    public ResponseEntity<Employee> getUsersById(@PathVariable(value = "id") Long emplId)
        throws ResourceNotFoundException {
        Employee employee = empRepo.findById(emplId).orElseThrow(() -> new ResourceNotFoundException("Employee not found for id: " + emplId));
        return ResponseEntity.ok().body(employee);
    }

    @PostMapping("/employees")
    public Employee createEmployee(@Valid @RequestBody Employee employee){
        System.out.println(employee.toString());
        return empRepo.save(employee);
    }

    @PutMapping("/employee/{id}")
    public ResponseEntity<Employee> updateEmployee(@PathVariable(value = "id") Long emplId, @Valid @RequestBody Employee empDetails)
        throws ResourceNotFoundException{
        Employee employee = empRepo.findById(emplId).orElseThrow(() -> new ResourceNotFoundException("Employee not found for id: " + emplId ));
        employee.setFirstName(empDetails.getFirstName());
        employee.setLastName(empDetails.getLastName());
        employee.setEmailId(empDetails.getEmailId());
        employee.setContactNumber(empDetails.getContactNumber());
        employee.setUpdateDateTime(new Date());

        final Employee updatedEmployee = empRepo.save(employee);

        return ResponseEntity.ok(updatedEmployee);
    }

    @DeleteMapping("/employee/{id}")
    public Map<String, Boolean> deleteEmployee(@PathVariable(value = "id") Long emplId)
        throws Exception{
        Employee employee = empRepo.findById(emplId).orElseThrow(() -> new ResourceNotFoundException("Employee not found for id: " + emplId));
        empRepo.delete(employee);
        Map <String, Boolean> response= new HashMap<>();
        response.put("Deleted", Boolean.TRUE);
        return response;
    }

}

模型-employee.java:

package com.ranjana.test.model;

import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import javax.persistence.*;
import java.util.Date;

@Entity
@Table(name = "employee")
public class Employee {
    //Employee Id
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    //Employee First Name
    @Column(name = "first_name", nullable = false)
    private String firstName;

    //Employee Last Name
    @Column(name = "last_name", nullable = false)
    private String lastName;

    //Employee Email Address
    @Column(name = "email", nullable = true)
    private String emailId;

    //Employee Contact Number
    @Column(name = "contact_number", nullable = true)
    private String contactNumber;

    //Creation Timestamp
    @CreationTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "create_date_time", nullable = false)
    private Date createDateTime;

    //Update Timestamp
    @UpdateTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "update_date_time", nullable = true)
    private Date updateDateTime;

    //Getters and Setters

    @Override
    public String toString(){
        return  "Employee{"
                + "id = " + id + '\''
                + "firstName" + firstName + '\''
                + "lastName" + lastName + '\''
                + "email" + emailId + '\''
                + "phone" + contactNumber + '\''
                + "createDateTime" + createDateTime + '\''
                + "updateDateTime" + updateDateTime + '\''
                + "}";
    }
}

控制台如下所示:

2019-08-05 13:27:18.327  INFO 9943 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-08-05 13:27:18.332  INFO 9943 --- [  restartedMain] com.ranjana.test.TestApplication            : Started TestApplication in 3.678 seconds (JVM running for 9.357)
2019-08-05 13:27:18.340 DEBUG 9943 --- [  restartedMain] o.s.boot.devtools.restart.Restarter      : Creating new Restarter for thread Thread[main,5,main]
2019-08-05 13:27:18.340 DEBUG 9943 --- [  restartedMain] o.s.boot.devtools.restart.Restarter      : Immediately restarting application
2019-08-05 13:27:18.340 DEBUG 9943 --- [  restartedMain] o.s.boot.devtools.restart.Restarter      : Created RestartClassLoader org.springframework.boot.devtools.restart.classloader.RestartClassLoader@51171eea
2019-08-05 13:27:18.340 DEBUG 9943 --- [  restartedMain] o.s.boot.devtools.restart.Restarter      : Starting application com.ranjana.test.TestApplication with URLs [file:/Users/ranjanasinha/ransinha/test/target/classes/]
2019-08-05 13:27:18.714 DEBUG 9943 --- [2)-10.36.30.147] o.s.jdbc.core.JdbcTemplate               : Executing SQL query [SELECT 1]
2019-08-05 13:27:18.714  INFO 9943 --- [3)-10.36.30.147] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-08-05 13:27:18.714  INFO 9943 --- [3)-10.36.30.147] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-08-05 13:27:18.715 DEBUG 9943 --- [3)-10.36.30.147] o.s.web.servlet.DispatcherServlet        : Detected StandardServletMultipartResolver
2019-08-05 13:27:18.724 DEBUG 9943 --- [3)-10.36.30.147] o.s.web.servlet.DispatcherServlet        : enableLoggingRequestDetails='false': request parameters and headers will be masked to prevent unsafe logging of potentially sensitive data
2019-08-05 13:27:18.724  INFO 9943 --- [3)-10.36.30.147] o.s.web.servlet.DispatcherServlet        : Completed initialization in 9 ms
2019-08-05 13:27:31.581 DEBUG 9943 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : GET "/employees", parameters={}
2019-08-05 13:27:31.587 DEBUG 9943 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2019-08-05 13:27:31.591 DEBUG 9943 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler     : Resource not found
2019-08-05 13:27:31.591 DEBUG 9943 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed 404 NOT_FOUND
2019-08-05 13:27:31.599 DEBUG 9943 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : "ERROR" dispatch for GET "/errors/404.html", parameters={}
2019-08-05 13:27:31.601 DEBUG 9943 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2019-08-05 13:27:31.602 DEBUG 9943 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler     : Resource not found
2019-08-05 13:27:31.602 DEBUG 9943 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Exiting from "ERROR" dispatch, status 404
2019-08-05 13:27:35.827 DEBUG 9943 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : GET "/", parameters={}
2019-08-05 13:27:35.830 DEBUG 9943 --- [nio-8080-exec-2] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2019-08-05 13:27:35.830 DEBUG 9943 --- [nio-8080-exec-2] o.s.w.s.r.ResourceHttpRequestHandler     : Resource not found
2019-08-05 13:27:35.830 DEBUG 9943 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : Completed 404 NOT_FOUND
2019-08-05 13:27:35.831 DEBUG 9943 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : "ERROR" dispatch for GET "/errors/404.html", parameters={}
2019-08-05 13:27:35.833 DEBUG 9943 --- [nio-8080-exec-2] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2019-08-05 13:27:35.834 DEBUG 9943 --- [nio-8080-exec-2] o.s.w.s.r.ResourceHttpRequestHandler     : Resource not found
2019-08-05 13:27:35.834 DEBUG 9943 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : Exiting from "ERROR" dispatch, status 404
2019-08-05 13:27:38.056 DEBUG 9943 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : GET "/", parameters={}
2019-08-05 13:27:38.058 DEBUG 9943 --- [nio-8080-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2019-08-05 13:27:38.058 DEBUG 9943 --- [nio-8080-exec-3] o.s.w.s.r.ResourceHttpRequestHandler     : Resource not found
2019-08-05 13:27:38.058 DEBUG 9943 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : Completed 404 NOT_FOUND
2019-08-05 13:27:38.059 DEBUG 9943 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : "ERROR" dispatch for GET "/errors/404.html", parameters={}
2019-08-05 13:27:38.060 DEBUG 9943 --- [nio-8080-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2019-08-05 13:27:38.062 DEBUG 9943 --- [nio-8080-exec-3] o.s.w.s.r.ResourceHttpRequestHandler     : Resource not found
2019-08-05 13:27:38.062 DEBUG 9943 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : Exiting from "ERROR" dispatch, status 404

我是春靴新手。请帮我弄清楚我遗漏了什么。

此外,创建了表。我用手动把数据放入表中检查,仍然显示404未找到错误。提前谢了。

共有1个答案

江瀚昂
2023-03-14

您应该调用http://localhost:8080/api/v1/employees

因为您已经创建了requestmapping(“API/V1”)

 类似资料:
  • 你好,我试图学习野蝇和springboose一个非常简单的应用程序使用eclipse。项目名称是springboo-test。包括主方法类在内的所有类都在同一个包中。 主方法类称为'App',其代码如下: 以下是服务器日志: 11:36:57281信息[org.wildfly.extension.undertow](服务器服务线程池--68)WFLYUT0021:注册的web上下文:'/sprin

  • 这是一个启动应用程序。它运行完美,但没有得到输出(它显示我的HTTP状态404错误在浏览器) 波姆。xml 启动类Main方法 控制器在主类后加载 网址:http://localhost:8080/hello输出

  • 我已经完成了以下配置并尝试了几乎所有找到的解决方案,但没有任何帮助。当我在战争包中部署Spring启动应用程序时。没有错误记录在weblogic日志中,但应用程序抛出404错误。 web.xml weblogic.xml 应用程序属性 root-context.xml 它包含应用程序特定的配置。 应用程序开始.java 无法从pom.xml中排除tomcat服务器,因为它编译失败。在使用sprin

  • 我试图使一个API工作在springstart但是当我输入请求:http://localhost:8080/employee/all我得到这个结果: 它是一个经典的服务,包含一个模型、一个服务、一个存储库、一个映射器和一个异常(如果没有员工),使用的数据库是sql中的实体,如下所示 服务: 仓库 模型 制图员 例外 波姆。xml

  • 我尝试按照stackoverflow上的这个过程集成引导程序(我的rails版本是3.2.17,这是一个区别),所以没有gem,只是将引导文件包含在相关的项目目录中。 然后创建了一个HTML页面,并将其放在project public目录中。 这是代码: 但是,当我加载页面并检查它(它加载)时,我可以看到GETs产生以下错误:

  • 我使用springboot和maryadb数据库进行训练。当我测试数据恢复时,我在邮递员中收到这样一条消息: 。我在复制粘贴中尝试了几个教程,我总是有相同的消息。我也会把控制台中的消息。提前谢谢你的帮助。 控制器 服务 回应的 模型 应用属性 安慰