Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,24 +1,8 @@
/*
* Copyright 2012-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.samples.petclinic.owner;

import jakarta.validation.Valid;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
Expand All @@ -33,18 +17,8 @@
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import jakarta.validation.Valid;

import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
* @author Juergen Hoeller
* @author Ken Krebs
* @author Arjen Poutsma
* @author Michael Isvy
* @author Wick Dynex
*/
@Controller
class OwnerController {

Expand All @@ -63,12 +37,11 @@ public void setAllowedFields(WebDataBinder dataBinder) {

@ModelAttribute("owner")
public Owner findOwner(@PathVariable(name = "ownerId", required = false) Integer ownerId) {
return ownerId == null ? new Owner()
: this.owners.findById(ownerId)
.orElseThrow(() -> new IllegalArgumentException("Owner not found with id: " + ownerId
+ ". Please ensure the ID is correct " + "and the owner exists in the database."));
return ownerId == null ? new Owner() : this.owners.findById(ownerId)
.orElseThrow(() -> new IllegalArgumentException("Owner not found with id: " + ownerId + "."));
}

// =================== CREACIÓN ===================
@GetMapping("/owners/new")
public String initCreationForm() {
return VIEWS_OWNER_CREATE_OR_UPDATE_FORM;
Expand All @@ -86,38 +59,67 @@ public String processCreationForm(@Valid Owner owner, BindingResult result, Redi
return "redirect:/owners/" + owner.getId();
}

// =================== BÚSQUEDA ===================
@GetMapping("/owners/find")
public String initFindForm() {
public String initFindForm(Model model) {
model.addAttribute("owner", new Owner());
return "owners/findOwners";
}

@GetMapping("/owners")
public String processFindForm(@RequestParam(defaultValue = "1") int page, Owner owner, BindingResult result,
public String processFindForm(Owner owner, BindingResult result, @RequestParam(defaultValue = "1") int page,
Model model) {
// allow parameterless GET request for /owners to return all records
String lastName = owner.getLastName();
if (lastName == null) {
lastName = ""; // empty string signifies broadest possible search
if (lastName == null)
lastName = "";

Page<Owner> ownersResults = findPaginatedForOwnersLastName(page, lastName);

if (ownersResults.isEmpty()) {
result.rejectValue("lastName", "notFound", "not found");
return "owners/findOwners";
}

// find owners by last name
if (ownersResults.getTotalElements() == 1) {
Owner singleOwner = ownersResults.iterator().next();
return "redirect:/owners/" + singleOwner.getId();
}

return addPaginationModel(page, model, ownersResults);
}

// Nuevo endpoint para buscar por apellido (parámetro opcional)
@GetMapping("/owners/searchByLastName")
public String searchByLastName(@RequestParam(name = "lastName", required = false) String lastName,
@RequestParam(defaultValue = "1") int page, Owner owner, BindingResult result, Model model) {
if (lastName == null)
lastName = "";
owner.setLastName(lastName);

Page<Owner> ownersResults = findPaginatedForOwnersLastName(page, lastName);

if (ownersResults.isEmpty()) {
// no owners found
result.rejectValue("lastName", "notFound", "not found");
return "owners/findOwners";
}

if (ownersResults.getTotalElements() == 1) {
// 1 owner found
owner = ownersResults.iterator().next();
return "redirect:/owners/" + owner.getId();
Owner singleOwner = ownersResults.iterator().next();
return "redirect:/owners/" + singleOwner.getId();
}

// multiple owners found
return addPaginationModel(page, model, ownersResults);
}

// Nuevo endpoint para mostrar todos los propietarios
@GetMapping("/owners/showAll")
public String showAllOwners(@RequestParam(defaultValue = "1") int page, Model model) {
Pageable pageable = PageRequest.of(page - 1, 5);
Page<Owner> ownersResults = owners.findAll(pageable);
return addPaginationModel(page, model, ownersResults);
}

// =================== UTILIDADES ===================
private String addPaginationModel(int page, Model model, Page<Owner> paginated) {
List<Owner> listOwners = paginated.getContent();
model.addAttribute("currentPage", page);
Expand All @@ -128,11 +130,11 @@ private String addPaginationModel(int page, Model model, Page<Owner> paginated)
}

private Page<Owner> findPaginatedForOwnersLastName(int page, String lastname) {
int pageSize = 5;
Pageable pageable = PageRequest.of(page - 1, pageSize);
Pageable pageable = PageRequest.of(page - 1, 5);
return owners.findByLastNameStartingWith(lastname, pageable);
}

// =================== EDICIÓN ===================
@GetMapping("/owners/{ownerId}/edit")
public String initUpdateOwnerForm() {
return VIEWS_OWNER_CREATE_OR_UPDATE_FORM;
Expand All @@ -158,17 +160,12 @@ public String processUpdateOwnerForm(@Valid Owner owner, BindingResult result, @
return "redirect:/owners/{ownerId}";
}

/**
* Custom handler for displaying an owner.
* @param ownerId the ID of the owner to display
* @return a ModelMap with the model attributes for the view
*/
// =================== DETALLE ===================
@GetMapping("/owners/{ownerId}")
public ModelAndView showOwner(@PathVariable("ownerId") int ownerId) {
ModelAndView mav = new ModelAndView("owners/ownerDetails");
Optional<Owner> optionalOwner = this.owners.findById(ownerId);
Owner owner = optionalOwner.orElseThrow(() -> new IllegalArgumentException(
"Owner not found with id: " + ownerId + ". Please ensure the ID is correct "));
Owner owner = this.owners.findById(ownerId)
.orElseThrow(() -> new IllegalArgumentException("Owner not found with id: " + ownerId));
mav.addObject(owner);
return mav;
}
Expand Down
3 changes: 2 additions & 1 deletion src/main/resources/messages/messages.properties
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ owners=Owners
addOwner=Add Owner
findOwner=Find Owner
findOwners=Find Owners
showAllOwners=Show All Owners
updateOwner=Update Owner
vets=Veterinarians
name=Name
Expand All @@ -38,7 +39,7 @@ type=Type
previousVisits=Previous Visits
date=Date
description=Description
new=New
new=New
addVisit=Add Visit
editPet=Edit Pet
ownerInformation=Owner Information
Expand Down
1 change: 1 addition & 0 deletions src/main/resources/messages/messages_de.properties
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ owners=Besitzer
addOwner=Besitzer hinzufügen
findOwner=Besitzer finden
findOwners=Besitzer suchen
showAllOwners=Alle anzeigen
updateOwner=Besitzer aktualisieren
vets=Tierärzte
name=Name
Expand Down
1 change: 1 addition & 0 deletions src/main/resources/messages/messages_es.properties
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ owners=Propietarios
addOwner=Añadir propietario
findOwner=Buscar propietario
findOwners=Buscar propietarios
showAllOwners=Mostrar Todos
updateOwner=Actualizar propietario
vets=Veterinarios
name=Nombre
Expand Down
1 change: 1 addition & 0 deletions src/main/resources/messages/messages_fa.properties
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ owners=مالکان
addOwner=افزودن مالک
findOwner=یافتن مالک
findOwners=یافتن مالکان
showAllOwners=نمایش همه
updateOwner=ویرایش مالک
vets=دامپزشکان
name=نام
Expand Down
1 change: 1 addition & 0 deletions src/main/resources/messages/messages_ko.properties
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ owners=소유자 목록
addOwner=소유자 추가
findOwner=소유자 찾기
findOwners=소유자들 찾기
showAllOwners=모두 보기
updateOwner=소유자 수정
vets=수의사
name=이름
Expand Down
1 change: 1 addition & 0 deletions src/main/resources/messages/messages_pt.properties
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ owners=Proprietários
addOwner=Adicionar proprietário
findOwner=Encontrar proprietário
findOwners=Encontrar proprietários
showAllOwners=Mostrar Todos
updateOwner=Atualizar proprietário
vets=Veterinários
name=Nome
Expand Down
1 change: 1 addition & 0 deletions src/main/resources/messages/messages_ru.properties
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ owners=Владельцы
addOwner=Добавить владельца
findOwner=Найти владельца
findOwners=Найти владельцев
showAllOwners=Показать всех
updateOwner=Обновить владельца
vets=Ветеринары
name=Имя
Expand Down
1 change: 1 addition & 0 deletions src/main/resources/messages/messages_tr.properties
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ owners=Sahipler
addOwner=Sahip Ekle
findOwner=Sahip Bul
findOwners=Sahipleri Bul
showAllOwners=Tümünü Göster
updateOwner=Sahip Güncelle
vets=Veterinerler
name=İsim
Expand Down
85 changes: 53 additions & 32 deletions src/main/resources/templates/owners/findOwners.html
Original file line number Diff line number Diff line change
@@ -1,35 +1,56 @@
<!DOCTYPE html>

<html xmlns:th="https://www.thymeleaf.org" th:replace="~{fragments/layout :: layout (~{::body},'owners')}">

<body>

<h2 th:text="#{findOwners}">Find Owners</h2>

<form th:object="${owner}" th:action="@{/owners}" method="get" class="form-horizontal" id="search-owner-form">
<div class="form-group">
<div class="control-group" id="lastNameGroup">
<label class="col-sm-2 control-label" th:text="#{lastName}">Last name </label>
<div class="col-sm-10">
<input class="form-control" th:field="*{lastName}" size="30" maxlength="80" />
<span class="help-inline">
<div th:if="${#fields.hasAnyErrors()}">
<p th:each="err : ${#fields.allErrors()}" th:text="${err}">Error</p>
</div>
</span>
<!doctype html>
<html
xmlns:th="https://www.thymeleaf.org"
th:replace="~{fragments/layout :: layout (~{::body},'owners')}"
>
<body>
<h2 th:text="#{findOwners}"></h2>

<form
th:object="${owner}"
th:action="@{/owners/searchByLastName}"
method="get"
class="form-horizontal"
id="search-owner-form"
>
<div class="form-group">
<div class="control-group" id="lastNameGroup">
<label class="col-sm-2 control-label" th:text="#{lastName}"></label>
<div class="col-sm-10">
<input
class="form-control"
th:field="*{lastName}"
size="30"
maxlength="80"
/>
<span class="help-inline">
<div th:if="${#fields.hasAnyErrors()}">
<p th:each="err : ${#fields.allErrors()}" th:text="${err}"></p>
</div>
</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary" th:text="#{findOwner}">Find Owner</button>
</div>
</div>

<a class="btn btn-primary" th:href="@{/owners/new}" th:text="#{addOwner}">Add Owner</a>

</form>

</body>

</html>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button
type="submit"
class="btn btn-primary"
th:text="#{findOwner}"
></button>
<a
class="btn btn-secondary"
th:href="@{/owners/showAll}"
th:text="#{showAllOwners}"
></a>
<a
class="btn btn-primary"
th:href="@{/owners/new}"
th:text="#{addOwner}"
></a>
</div>
</div>
</form>
</body>
</html>
Loading