如何将仅长数字作为字符串写入表单输入?

huangapple go评论72阅读模式
英文:

How can I write only long number as String on form input?

问题

我正在使用Spring Data JPA在Spring Boot中进行注册我在将长整型值放入表单字段时遇到了问题

**模型类** 我在`private long nsuID`之前使用了`@NotBlank`注解但是当表单重定向时,`nsuID`字段的值被填充为0

@Entity
@Table(name="alumnies",uniqueConstraints = @UniqueConstraint(columnNames = "email"))
public class Alumni {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    @Column(name="NSU_ID")
    @NotBlank
    private long nsuID;
    
    public long getNsuID() {
        return nsuID;
    }
    public void setNsuID(long nsuID) {
        this.nsuID = nsuID;
    }
}

**HTML文件**

<div class="form-group"
    th:classappend="${#fields.hasErrors('nsuID')}? 'has-error':''">
    <label for="nsuID" class="control-label">NSU ID</label> <input
       id="nsuID" class="form-control" th:field="*{nsuID}" />
       <p class="error-message"
       th:each="error : ${#fields.errors('nsuID')}"
       th:text="${error}">Validation error</p>
     </div>

**控制器类**

@Controller
public class RegistraionController {
    @Autowired
    private UserService us;
    
    @GetMapping("/")
    public String showRegistration(Model model) {
        Alumni alumni = new Alumni();
        model.addAttribute("alumni", alumni);
        return "registration";
    }
    
    @PostMapping("/registration")
    public String saveAlumni(@ModelAttribute("alumni") @Validated Alumni alumni, BindingResult bindingResult) {
        
        Alumni existing = us.findByEmail(alumni.getEmail());
        if (existing != null) {
            bindingResult.rejectValue("email", null, "There is already an account registered with that email");
        }
        
        if (bindingResult.hasErrors()) {
             return "registration";
        }
        us.saveAlumni(alumni);
        return "redirect:/";
    }
}
英文:

I am making a registration in Spring Boot using Spring Data JPA. I'm facing a problem in placing long values in a form field.

Model class: I have used @NotBlank annotation before private long nsuID, but when the form redirects the nsuID field has filled up by 0.

@Entity
@Table(name=&quot;alumnies&quot;,uniqueConstraints = @UniqueConstraint(columnNames = &quot;email&quot;) )
public class Alumni {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name=&quot;NSU_ID&quot;)
@NotBlank
private long nsuID;
public long getNsuID() {
return nsuID;
}
public void setNsuID(long nsuID) {
this.nsuID = nsuID;
}
}

HTML file:

&lt;div class=&quot;form-group&quot;
th:classappend=&quot;${#fields.hasErrors(&#39;nsuID&#39;)}? &#39;has-error&#39;:&#39;&#39;&quot;&gt;
&lt;label for=&quot;nsuID&quot; class=&quot;control-label&quot;&gt;NSU ID&lt;/label&gt; &lt;input
id=&quot;nsuID&quot; class=&quot;form-control&quot; th:field=&quot;*{nsuID}&quot; /&gt;
&lt;p class=&quot;error-message&quot;
th:each=&quot;error : ${#fields.errors(&#39;nsuID&#39;)}&quot;
th:text=&quot;${error}&quot;&gt;Validation error&lt;/p&gt;
&lt;/div&gt;

Controller class:

@Controller
public class RegistraionController {
@Autowired
private UserService us;
@GetMapping(&quot;/&quot;)
public String showRegistration(Model model) {
Alumni alumni = new Alumni();
model.addAttribute(&quot;alumni&quot;, alumni);
return &quot;registration&quot;;
}
@PostMapping(&quot;/registration&quot;)
public String saveAlumni(@ModelAttribute(&quot;alumni&quot;) @Validated Alumni alumni, BindingResult bindingResult) {
Alumni existing = us.findByEmail(alumni.getEmail());
if (existing != null) {
bindingResult.rejectValue(&quot;email&quot;, null, &quot;There is already an account registered with that email&quot;);
}
if (bindingResult.hasErrors()) {
return &quot;registration&quot;;
}
us.saveAlumni(alumni);
return &quot;redirect:/&quot;;
}
}

答案1

得分: 1

如@Dip Halani所说,long类型的变量不能保存null值,因为它是原始类型变量,而且long类型变量的默认值是0。

而您在nsuID上的@NotBlank约束是错误的,因为它检查字符序列的修剪长度不为空,通常用于验证给定的字符串值不得为null,并且修剪后的长度必须大于零。

如果您想要验证非null值,请使用@NotNull,并将long nsuID替换为Long nsuID

详见Bean验证中@NotNull、@NotEmpty和@NotBlank约束之间的区别

英文:

As @Dip Halani said, long type variable can't hold null value since it's primitive type variable and long type variable's default value is 0.

And your @NotBlank constraint on nsuID is wrong because it checks that a character sequence's trimmed length is not empty it's usually used for validate given string value must be not null and the trimmed length must be greater than zero.

If you want to validate for non-null value then use @NotNull and replace long nsuID to Long nsuID.

See Difference Between @NotNull, @NotEmpty, and @NotBlank Constraints in Bean Validation

答案2

得分: 0

long无法保存空值,因此可能会转换为0。尝试将其更改为Long(包装类)。

@NotBlank
private Long nsuID;
英文:

long can not hold null values so it might be converting to 0. try changing it to Long (wrapper class).

@NotBlank 
private Long nsuID;

huangapple
  • 本文由 发表于 2020年10月3日 16:32:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64182264.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定