Reputation: 149
I'm trying to write a basic application with rest api's connecting with a postgres database to perform couple of crud operations. When I run the application it starts successfully. But when I go to the url "http://localhost:8080/employees" or http://localhost:8080", it shows "This localhost page can’t be found. No webpage was found for the web address: http://localhost:8080/employees. HTTP ERROR 404".
Here is my 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);
}
}
The controller class - 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;
}
}
The model - 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 + '\''
+ "}";
}
}
The console looks like following:
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
I'm new to spring boot. Please help me figure out what I'm missing.
Also the table got created. And I checked with manually putting data in the table, still the 404 not found error is showing. Thanks in advance.
Upvotes: 0
Views: 1126
Reputation: 628
You should call like http://localhost:8080/api/v1/employees
Because you have created requestmapping("API/v1")
Upvotes: 1