防止同一用户ID在编辑表单时重复注册

时间:2019-05-16 01:49:17

标签: java html thymeleaf

我想防止用户在注册时重复使用用户ID,并且我编写的代码可以正常工作,但是当我尝试将用户ID与另一个已经存在的用户ID相同时,会出现一个问题并可以注册。

@PostMapping("/create/")
public ModelAndView createNewUser(@ModelAttribute UserForm form) {
    user = null;
    if (form.getSubmitType().equalsIgnoreCase("delete")) {
        // delete
        user = repo.findById(form.getId()).get();
        user.setEnabled(false);
    } else if (form.getSubmitType().equalsIgnoreCase("update")) {
        // update
        user = repo.findById(form.getId()).get();
        if (form.getPassword() != null && !form.getPassword().isEmpty()) {
            user.setPassword(pe.encode(form.getPassword()));
        }
        // Create
    } else {
        user = new MsUser();
        user.setEnabled(true);
        user.setPassword(pe.encode(form.getPassword()));
        MsUserPointHistory lastPointUsage = new MsUserPointHistory();
        lastPointUsage.setLastPoints(lastPointUsage.getPoints());
    }

    if (form.getSubmitType().equalsIgnoreCase("update") || (form.getSubmitType().equalsIgnoreCase("create"))) {
        user.setUsername(form.getUsername());
        user.setRole(form.getRole());
        user.setShareownerNum(form.getShareownerNum());
        user.setName(form.getName());
        user.setNameKana(form.getNameKana());
        user.setPostalCode(form.getPostalCode());
        user.setAddress(form.getAddress());
        user.setMailaddress(form.getMailaddress());
        user.setShares(form.getShares());
        user.setPoints(form.getPoints());
        user.setBonusPoints(form.getBonusPoints());
        user.setStadiumUsage(form.getStadiumUsage());
        user.setRemarks(form.getRemarks());
    }
    // Validasi
    if (!form.getSubmitType().equalsIgnoreCase("delete")) {
        if (form.getUsername().matches("[0-9]{5,10}")) {
            System.out.println("valid");
        } else {
            return new ModelAndView("redirect:/admin/user?error=1");
        }
        if (form.getShareownerNum().matches("[0-9]{5}")) {
            System.out.println("valid");
        } else {
            return new ModelAndView("redirect:/admin/user?error=2");
        }
        if (form.getPostalCode().matches("[0-9]{7}")) {
            System.out.println("valid");
        } else {
            return new ModelAndView("redirect:/admin/user?error=3");
        }
        if (form.getSubmitType().equalsIgnoreCase("update")) {
            user = repo.findById(form.getId()).get();       
        } else if (repo.findByUsername(form.getUsername()).size() > 0) {
            return new ModelAndView("redirect:/admin/user?error=4");
        }
    }

我想要当我将用户ID(仅用户ID)编辑为另一个用户ID时,将出现错误消息。 而且我可以编辑除用户ID以外的其他数据。

0 个答案:

没有答案