Spring boot 学习记录(表单验证)

2018-07-24  本文已影响12人  CodeRambler

register.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="author" content="heoclark">
    <meta charset="UTF-8">
    <title>注册</title>
</head>
<body>
<!-- 注册表单 -->
<div id="register">
    <form id="register_form" action="/user/doRegister" method="post">
        <input type="text" name="input_username" placeholder="用户名" maxlength="50"/>
        <input type="password" name="input_username" placeholder="密码" maxlength="20" />
        <input type="submit" name="submit" value="submit" />
    </form>
</div>
</body>
</html>

User.java

package com.heoclark.webapp.entity;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class User {
    /**
     * 需要注意的是,数据库中的列名与实体类的变量名应该保持一致,否则查找出来的值可能为NULL
     */
    private Integer id;

    @NotNull (message = "用户名不能为空")
    private String username;

    @NotNull (message = "密码不能为空")
    @Size (min = 6, max = 20, message = "密码长度至少为6,最长不超过20")
    private String password;

    @Email (message = "邮箱格式不正确")
    private String email;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

}

WebController.java

package com.heoclark.webapp.controller;

import com.heoclark.webapp.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping(value = "/user")
public class WebController {

    @GetMapping(value = "/register")
    public String register() {
        return "register";
    }

    @PostMapping(value = "/doRegister")
    public @ResponseBody User doRegister(@Valid User user, BindingResult result, Model model) {
        if (result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error:list) {
                System.out.println(error.getDefaultMessage());
            }
            return null;
        }
        System.out.println("注册");
        return user;
    }
}
上一篇下一篇

猜你喜欢

热点阅读