I am wondering how I could check the RequestParams to see if they are empty so I could forward to another html page, right now I am just working around this by checking if each parameter is empty. The problem is I want to forward to another page if the user tries to submit a compeletly empty form and if they do that my program will crash. It will crash because the program tries to convert the int Price to a string becasue that is what is submitted in the empty form. I know I could just make the Int Price a String but I was wondering if there was another soultion.
@Controller
public class HomeController {
@Autowired
private GlassesList glassesList;
@GetMapping("/")
public String goHome(Model model) {
return "index";
}
@GetMapping("/addGlasses")
public String addSunglasses(Model model) {
return "addGlasses";
}
@GetMapping("/searchGlasses")
public String searchSunglasses() {
return "searchGlasses";
}
@GetMapping("/displayGlasses")
public String displaySunglasses() {
return "displayGlasses";
}
@PostMapping("/formPost")public String processForm (
Model model,
@RequestParam String productName,
@RequestParam String brandName,
@RequestParam String frameType,
@RequestParam String color,
@RequestParam String size,
@RequestParam String lensType,
@RequestParam int price
) {
if (productName.equals("") && brandName.equals("") && frameType.equals("") && color.equals("") && size.equals("") && lensType.equals("") && price == 0) {
return "displayGlasses";
}
else {
Glasses glasses = new Glasses(productName, brandName,frameType,
color, size, lensType, price);
glassesList.getGlassesList().add(glasses);
model.addAttribute("glassesList", glassesList);
System.out.println(model.getAttribute(lensType));
System.out.print(glassesList.getGlassesList());
return "addGlasses";
}
}
CodePudding user response:
Instead of handling too many request params, you can use RequestBody and send those params in that request like below: Define a class representing all your request-params:
public class AllParams{
@NotNull
@NotEmpty
private String productName;
@NotNull
@NotEmpty
private String brandName;
@NotNull
@NotEmpty
private String frameType;
@NotNull
@NotEmpty
private String color;
@NotNull
@NotEmpty
private String size;
@NotNull
@NotEmpty
private String lensType;
@Min(1)
private int price;
//getters and setters
}
Now, use this in your method and bind the errors:
@PostMapping("/formPost")public String processForm (@Valid @RequestBody AllParams requestParam, BindingResult bindingResult,
Model model){
//check if there is any error[based on your annotations]
if(bindingResult.hasErrors()) {
return "displayGlasses";
}
//otherwise, write your usual code here
....
...
}
About annotations, please refer here: Difference Between @NotNull, @NotEmpty, and @NotBlank Constraints in Bean Validation