Skip to content

Commit 5aa7a8e

Browse files
committed
Fixed controller
1 parent 30aab0a commit 5aa7a8e

File tree

2 files changed

+29
-55
lines changed

2 files changed

+29
-55
lines changed

pom.xml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,11 @@
7070
<artifactId>spring-boot-starter-test</artifactId>
7171
<scope>test</scope>
7272
</dependency>
73+
<dependency>
74+
<groupId>org.springframework.boot</groupId>
75+
<artifactId>spring-boot-starter</artifactId>
76+
</dependency>
77+
7378

7479
<!-- Databases - Uses H2 by default -->
7580
<dependency>
Lines changed: 24 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,6 @@
1-
/*
2-
* Copyright 2012-2025 the original author or authors.
3-
*
4-
* Licensed under the Apache License, Version 2.0 (the "License");
5-
* you may not use this file except in compliance with the License.
6-
* You may obtain a copy of the License at
7-
*
8-
* https://www.apache.org/licenses/LICENSE-2.0
9-
*
10-
* Unless required by applicable law or agreed to in writing, software
11-
* distributed under the License is distributed on an "AS IS" BASIS,
12-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-
* See the License for the specific language governing permissions and
14-
* limitations under the License.
15-
*/
161
package org.springframework.samples.petclinic.owner;
172

183
import java.util.List;
19-
import java.util.Optional;
204

215
import org.springframework.data.domain.Page;
226
import org.springframework.data.domain.PageRequest;
@@ -32,17 +16,10 @@
3216
import org.springframework.web.bind.annotation.PostMapping;
3317
import org.springframework.web.bind.annotation.RequestParam;
3418
import org.springframework.web.servlet.ModelAndView;
19+
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
3520

3621
import jakarta.validation.Valid;
37-
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
3822

39-
/**
40-
* @author Juergen Hoeller
41-
* @author Ken Krebs
42-
* @author Arjen Poutsma
43-
* @author Michael Isvy
44-
* @author Wick Dynex
45-
*/
4623
@Controller
4724
class OwnerController {
4825

@@ -60,15 +37,13 @@ public void setAllowedFields(WebDataBinder dataBinder) {
6037
}
6138

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

7044
@GetMapping("/owners/new")
71-
public String initCreationForm() {
45+
public String initCreationForm(Model model) {
46+
model.addAttribute("owner", new Owner());
7247
return VIEWS_OWNER_CREATE_OR_UPDATE_FORM;
7348
}
7449

@@ -91,27 +66,22 @@ public String initFindForm() {
9166

9267
@GetMapping("/owners")
9368
public String processFindForm(@RequestParam(defaultValue = "1") int page, Owner owner, BindingResult result,
94-
Model model) {
95-
// allow parameterless GET request for /owners to return all records
69+
Model model) {
9670
if (owner.getLastName() == null) {
97-
owner.setLastName(""); // empty string signifies broadest possible search
71+
owner.setLastName(""); // broadest possible search
9872
}
9973

100-
// find owners by last name
10174
Page<Owner> ownersResults = findPaginatedForOwnersLastName(page, owner.getLastName());
10275
if (ownersResults.isEmpty()) {
103-
// no owners found
10476
result.rejectValue("lastName", "notFound", "not found");
10577
return "owners/findOwners";
10678
}
10779

10880
if (ownersResults.getTotalElements() == 1) {
109-
// 1 owner found
110-
owner = ownersResults.iterator().next();
111-
return "redirect:/owners/" + owner.getId();
81+
Owner singleOwner = ownersResults.iterator().next();
82+
return "redirect:/owners/" + singleOwner.getId();
11283
}
11384

114-
// multiple owners found
11585
return addPaginationModel(page, model, ownersResults);
11686
}
11787

@@ -130,44 +100,43 @@ private Page<Owner> findPaginatedForOwnersLastName(int page, String lastname) {
130100
return owners.findByLastNameStartingWith(lastname, pageable);
131101
}
132102

103+
133104
@GetMapping("/owners/{ownerId}/edit")
134-
public String initUpdateOwnerForm() {
105+
public String initUpdateOwnerForm(@PathVariable("ownerId") Integer ownerId, Model model) {
106+
Owner owner = owners.findById(ownerId)
107+
.orElseThrow(() -> new IllegalArgumentException("Owner not found with id: " + ownerId));
108+
model.addAttribute("owner", owner);
135109
return VIEWS_OWNER_CREATE_OR_UPDATE_FORM;
136110
}
137111

138112
@PostMapping("/owners/{ownerId}/edit")
139-
public String processUpdateOwnerForm(@Valid Owner owner, BindingResult result, @PathVariable("ownerId") int ownerId,
140-
RedirectAttributes redirectAttributes) {
113+
public String processUpdateOwnerForm(@Valid Owner owner, BindingResult result,
114+
@PathVariable("ownerId") Integer ownerId,
115+
RedirectAttributes redirectAttributes) {
141116
if (result.hasErrors()) {
142117
redirectAttributes.addFlashAttribute("error", "There was an error in updating the owner.");
143118
return VIEWS_OWNER_CREATE_OR_UPDATE_FORM;
144119
}
145120

146-
if (owner.getId() != ownerId) {
121+
if (owner.getId() == null || !ownerId.equals(owner.getId())) {
147122
result.rejectValue("id", "mismatch", "The owner ID in the form does not match the URL.");
148-
redirectAttributes.addFlashAttribute("error", "Owner ID mismatch. Please try again.");
123+
redirectAttributes.addAttribute("ownerId", ownerId);
149124
return "redirect:/owners/{ownerId}/edit";
150125
}
151126

152127
owner.setId(ownerId);
153128
this.owners.save(owner);
154129
redirectAttributes.addFlashAttribute("message", "Owner Values Updated");
130+
redirectAttributes.addAttribute("ownerId", ownerId);
155131
return "redirect:/owners/{ownerId}";
156132
}
157133

158-
/**
159-
* Custom handler for displaying an owner.
160-
* @param ownerId the ID of the owner to display
161-
* @return a ModelMap with the model attributes for the view
162-
*/
163134
@GetMapping("/owners/{ownerId}")
164-
public ModelAndView showOwner(@PathVariable("ownerId") int ownerId) {
135+
public ModelAndView showOwner(@PathVariable("ownerId") Integer ownerId) {
136+
Owner owner = this.owners.findById(ownerId)
137+
.orElseThrow(() -> new IllegalArgumentException("Owner not found with id: " + ownerId));
165138
ModelAndView mav = new ModelAndView("owners/ownerDetails");
166-
Optional<Owner> optionalOwner = this.owners.findById(ownerId);
167-
Owner owner = optionalOwner.orElseThrow(() -> new IllegalArgumentException(
168-
"Owner not found with id: " + ownerId + ". Please ensure the ID is correct "));
169-
mav.addObject(owner);
139+
mav.addObject("owner", owner);
170140
return mav;
171141
}
172-
173142
}

0 commit comments

Comments
 (0)