繁体   English   中英

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

[英]Demo Spring Boot application for REST apis for CRUD operation throws 404 not found error

我正在尝试编写一个带有rest api与postgres数据库连接的基本应用程序,以执行几个crud操作。 当我运行该应用程序时,它将成功启动。 但是,当我转到URL“ http:// localhost:8080 / employees ”或http:// localhost:8080时 ,它显示“找不到此localhost页面。 找不到该网址的网页: 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 not found错误。 提前致谢。

您应该像http:// localhost:8080 / api / v1 / employees这样打电话

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM