RestTemplate – podstawy

RestTemplate – podstawy

Było kilka przykładów z JdbcTemplate to teraz czas na kilka przykładów z RestTemplate! Utworzymy w tym artykule aplikacje typu CRUD z wykorzystaniem architektury Rest – tworzymy nowy projekt Spring Boota – plik pom.xml – niezbędne zależności:

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter</artifactId>
	</dependency>
 
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-validation</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-data-jpa</artifactId>
	</dependency>
 
	<dependency>
		<groupId>org.projectlombok</groupId>
		<artifactId>lombok</artifactId>
		<version>1.18.20</version>
		<scope>provided</scope>
	</dependency>
 
	<dependency>
		<groupId>com.h2database</groupId>
		<artifactId>h2</artifactId>
		<scope>runtime</scope>
	</dependency>
 
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>
</dependencies>

Definicja modelu – klasa Person:

@Entity
@ToString
@Getter
@Setter
public class Person {
 
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
 
    private String name;
    private String surname;
    private int age;
 
    public Person() {
    }
 
    public Person(String name, String surname, int age) {
        this.name = name;
        this.surname = surname;
        this.age = age;
    }
}

Definicja repozytorium:

@Repository
public interface PersonRepository extends JpaRepository<Person, Long> {
}

Wyjątek kiedy zasób nie zostanie znaleziony:

@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends Exception{
    private static final long serialVersionUID = 1L;
    public ResourceNotFoundException(String message){
        super(message);
    }
}

Definicja RestAPI:

@RestController
@RequestMapping("/api")
public class PersonController {
 
    @Autowired
    private PersonRepository personRepository;
 
    @PostMapping("/persons")
    public Person createNewPerson(@Valid @RequestBody Person person) {
        return personRepository.save(person);
    }
 
    @GetMapping("/persons/{id}")
    public ResponseEntity<Person> getEmployeeById(@PathVariable(value = "id") Long personId)
            throws ResourceNotFoundException {
        Person person = personRepository.findById(personId)
                .orElseThrow(() -> new ResourceNotFoundException("Person not found for id : " + personId));
        return ResponseEntity.ok().body(person);
    }
 
    @GetMapping("/persons")
    public List<Person> getAllPersons() {
        return personRepository.findAll();
    }
 
    @PutMapping("/persons/{id}")
    public ResponseEntity<Person> updatePerson(@PathVariable(value = "id") Long personId, @Valid @RequestBody Person personData) throws ResourceNotFoundException {
        Person person = findPersonById(personId);
        person.setName(personData.getName());
        person.setSurname(personData.getSurname());
        person.setAge(personData.getAge());
        return ResponseEntity.ok(personRepository.save(person));
    }
 
 
    @DeleteMapping("/persons/{id}")
    public Map<String, Boolean> deletePerson(@PathVariable(value = "id") Long personId)
            throws ResourceNotFoundException {
        Person person = findPersonById(personId);
        personRepository.delete(person);
        Map<String, Boolean> response = new HashMap<>();
        response.put("deleted", Boolean.TRUE);
        return response;
    }
 
    private Person findPersonById(Long personId) throws ResourceNotFoundException {
        return personRepository.findById(personId).orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + personId));
    }
}

Klasa startowa wykorzystująca utworzone powyżej RestApi – klasa ta wykorzystuje interfejs ComandLineRunner celem uproszczenia przykładu:

@SpringBootApplication
public class RestTemplateApplication  implements CommandLineRunner {
 
	@Autowired
	private RestTemplate restTemplate;
 
	private static final String GET_PERSON_URL    = "http://localhost:8080/api/persons";
	private static final String GET_PERSON_ID_URL = "http://localhost:8080/api/persons/{id}";
	private static final String CREATE_PERSON_URL = "http://localhost:8080/api/persons";
	private static final String UPDATE_PERSON_URL = "http://localhost:8080/api/persons/{id}";
	private static final String DELETE_PERSON_URL = "http://localhost:8080/api/persons/{id}";
 
	public static void main(String[] args) {
		SpringApplication.run(RestTemplateApplication.class, args);
	}
 
	@Override
	public void run(String... strings) throws Exception {
		createNewPerson();
		getPersonById();
		getAllPersons();
		updatePerson();
		getAllPersons();
		deleteEmployee();
		getAllPersons();
	}
 
	private void createNewPerson() {
		Person person = new Person("Java", "Leader", 30);
		RestTemplate restTemplate = new RestTemplate();
		Person result = restTemplate.postForObject(CREATE_PERSON_URL, person, Person.class);
		System.out.println(result);
	}
 
	private void getPersonById() {
		Map< String, String > params = new HashMap< String, String >();
		params.put("id", "1");
		Person result = restTemplate.getForObject(GET_PERSON_ID_URL, Person.class, params);
		System.out.println(result);
	}
 
	private void getAllPersons() {
		HttpHeaders headers = new HttpHeaders();
		headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
		HttpEntity<String> httpEntity = new HttpEntity ("parameters", headers);
		ResponseEntity< String > result = restTemplate.exchange(GET_PERSON_URL, HttpMethod.GET, httpEntity, String.class);
		System.out.println(result);
	}
 
	private void updatePerson() {
		Map < String, String > params = new HashMap < String, String > ();
		params.put("id", "1");
		Person updatePerson = new Person("Leader", "Java", 30);
		RestTemplate restTemplate = new RestTemplate();
		restTemplate.put(UPDATE_PERSON_URL, updatePerson, params);
	}
 
	private void deleteEmployee() {
		Map < String, String > params = new HashMap();
		params.put("id", "1");
		RestTemplate restTemplate = new RestTemplate();
		restTemplate.delete(DELETE_PERSON_URL, params);
	}
}

wynik:

Person(id=1, name=Java, surname=Leader, age=30)
Person(id=1, name=Java, surname=Leader, age=30)
<200,[{"id":1,"name":"Java","surname":"Leader","age":30}],[Content-Type:"application/json", Transfer-Encoding:"chunked", Date:"Sat, 01 May 2021 14:47:21 GMT", Keep-Alive:"timeout=60", Connection:"keep-alive"]>
<200,[{"id":1,"name":"Leader","surname":"Java","age":30}],[Content-Type:"application/json", Transfer-Encoding:"chunked", Date:"Sat, 01 May 2021 14:47:21 GMT", Keep-Alive:"timeout=60", Connection:"keep-alive"]>
<200,[],[Content-Type:"application/json", Transfer-Encoding:"chunked", Date:"Sat, 01 May 2021 14:47:21 GMT", Keep-Alive:"timeout=60", Connection:"keep-alive"]>

Zobacz kod na GitHubie i zapisz się na bezpłatny newsletter!

.

Leave a comment

Your email address will not be published.


*