将参数从一个映射传递到另一个映射的正确方法是什么?

时间:2019-02-13 14:46:57

标签: java spring spring-boot controller

我正在写的是关于商店的应用程序。假设我有一个包含很少字段的表单。我的产品有:

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class ShopFormDto {
    private String name;

    private String addressName;
    private String addressStreet;
    private String addressCode;
    private String addressCity;

我允许用户添加所有字段,假设它们都不是可选字段,并且我不想在前端处理此问题(我使用百里香)。

@GetMapping("/add")
    public String getCreationForm(Model model,
                                  @RequestParam(name = "error_message", required = false) String error_message,
                                  @RequestParam(name = "message", required = false) String message) {

        model.addAttribute("supplierForm", new ShopFormDto());

        if (error_message != null) {
            model.addAttribute("error_message", error_message);
        }
        model.addAttribute("message", message);
        return "shop/supplierForm";
    }

我要做的是检查所有字段并提供正确的错误消息给用户。应该如何处理。我现在要做的是:

@PostMapping("/add")
    public String add(Model model, ShopFormDto dto) {
        boolean httpUrlAddress =
                dto.getUrl().matches("https://.*") ||
                        dto.getUrl().matches("http://.*");
        boolean wwwUrlAddress = dto.getUrl().matches("www[.].*");
        boolean emptyUrlAddress = dto.getUrl().isEmpty();

        model.addAttribute("error_message", "Unable to add shop");
        model.addAttribute("supplierForm", new ShopFormDto());
        model.addAttribute("supplierList", shopService.findAll());
        if (dto.getName().trim().isEmpty()) {
            return "redirect:/shop/add?error_message=" + "Shop name is empty";
        }
        if (dto.getAddressCity().trim().isEmpty()) {
            return "redirect:/shop/add?error_message=" + "City address is empty";
        }
        if (dto.getAddressCode().trim().isEmpty()) {
            return "redirect:/shop/add?error_message=" + "Code address is empty";
        }
        if (dto.getAddressName().trim().isEmpty()) {
            return "redirect:/shop/add?error_message=" + "Name address is empty";
        }
        if (dto.getAddressStreet().trim().isEmpty()) {
            return "redirect:/shop/add?error_message=" + "Street address is empty";
        }
        if (emptyUrlAddress || httpUrlAddress || wwwUrlAddress) {
            if (shopService.add(dto)) {
                if (!defaultApproved) {
                    return "redirect:/shop/list?message=" + "Newly added shop has to be approved by admin.";
                } else {
                    return "redirect:/shop/list?message=" + "Shop has been added.";
                }
            }
        } else {
            return "redirect:/shop/add?error_message=" + "Incorrect URL address. Started with http:// or https:// or www.";
        }
        return "shop/list";
    }

我应该怎么做才能使代码更简洁,更容易开发?我正在考虑可以帮助我专注于翻译(i18n)的解决方案。如您所见,现在-我只会讲英语。

我正在寻找一种更好的传递错误消息的方法,而不是将它们作为请求参数添加到我的url字符串中。有更好的方法吗?

0 个答案:

没有答案