Today we will see how to return a single resource when requester sends a request so. Again it's pretty simple. You just need to follow all the steps explained below-
Note: This time we made few changes to the project. We added a service layer and modified controller class. We will see all the changes in details below.
Step-1: We need to add a service layer - that is basically ReturnObjectService class in our project. Copy the below code -
package com.ncteam.thirdtutorial;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Service;
@Service
public class ReturnObjectService {
public List<ListPojo> listEmployee = Arrays.asList( new ListPojo("Emp1","Kennith", "NJ"),
new ListPojo("Emp2","Jorge", "NC"),
new ListPojo("Emp1","Melanie", "India"));
public List<ListPojo> getEmployeeList(){
return listEmployee;
}
public ListPojo getEmployee(String emplId) {
return listEmployee.stream().filter(t->t.getEmplId().equals(emplId)).findFirst().get();
}
}
N.B. Please donate us -> https://imjo.in/t9cEFy
Note: This time we made few changes to the project. We added a service layer and modified controller class. We will see all the changes in details below.
Step-1: We need to add a service layer - that is basically ReturnObjectService class in our project. Copy the below code -
package com.ncteam.thirdtutorial;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Service;
@Service
public class ReturnObjectService {
public List<ListPojo> listEmployee = Arrays.asList( new ListPojo("Emp1","Kennith", "NJ"),
new ListPojo("Emp2","Jorge", "NC"),
new ListPojo("Emp1","Melanie", "India"));
public List<ListPojo> getEmployeeList(){
return listEmployee;
}
public ListPojo getEmployee(String emplId) {
return listEmployee.stream().filter(t->t.getEmplId().equals(emplId)).findFirst().get();
}
}
Project structure should look like below image -
Step-2: Now we need to modify controller class. Use the below code to do so.
package com.ncteam.thirdtutorial;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ReturnObjectFromController {
@Autowired
private ReturnObjectService service ;
@RequestMapping("/listofpojo")
public List<ListPojo> listAllEmployee() {
return service.getEmployeeList();
}
@RequestMapping("/listofpojo/{id}")
public ListPojo listEmployee(@PathVariable String id) {
return service.getEmployee(id);
}
}
Project should be looking like below image -
Step-3: Execute the project and hit URL : http://localhost:8080/listofpojo/Emp2
You should be able to get the below screen as output-
N.B. Please donate us -> https://imjo.in/t9cEFy
No comments:
Post a Comment