1. 程式人生 > >Springboot之表單驗證

Springboot之表單驗證

實體類

@TableName("lh_admin")
public class Admin extends Model<Admin> {

    private static final long serialVersionUID = 1L;

    /**
     * 管理員ID
     */
	@TableId(value="admin_id", type= IdType.AUTO)
	private Integer adminId;
    /**
     * 使用者名稱
     */
    @NotEmpty(message="使用者姓名不能為空")
    @Size
(min = 2, max = 4, message = "使用者長度要大於2,小於4") @TableField("admin_user") private String adminUser; /** * 密碼 */ @NotNull(message = "密碼不能為空") @TableField("admin_password") private String adminPassword; /** * 建立時間 */ @TableField("admin_create_time") private Date adminCreateTime;
/** * 是否被鎖定 0 未鎖定 1 鎖定 */ @TableField("admin_locked") private String adminLocked; /** * 最新登入時間 */ @TableField("admin_update_time") private Date adminUpdateTime; /** * 建立者ID */ @TableField("admin_create_user_id") private Integer adminCreateUserId; /** * 手機號 */
@Size(min = 11, max = 11, message = "手機號格式不對") @TableField("admin_phone") private String adminPhone; /** * 郵箱 */ @TableField("admin_email") private String adminEmail; /** * 加密鹽值 */ @TableField("admin_salt") private String adminSalt; /* 省略get、set方法和建構函式(預設構造、所有屬性的建構函式) */ }

Mapper層方法

@Mapper
public interface AdminMapper extends BaseMapper<Admin> {

}

Servcie層

public interface AdminService extends IService<Admin> {
	
}

Service實現類

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {
    
}

控制器層

@Controller
@RequestMapping("/admin")
public class UserController {
    
    private final static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private AdminService adminService;
    
    @PostMapping("/author/user/submit_add")
    @ResponseBody
    public JsonResult adminSubmit(@Valid Admin admin, BindingResult result, HttpSession session){
        // 這個要注意不能使用 result.hasErrors(),是無法回資料的,不走if判斷。
        if (result.hasFieldErrors()) {
            // JsonResult 是一個介面資料的封裝類
            return new JsonResult(ResultCode.FAIL, result.getFieldError().getDefaultMessage());
        }else{
            Admin session_admin = (Admin) session.getAttribute("admin");
            admin.setAdminCreateTime(new Date());
            admin.setAdminUpdateTime(new Date());
            admin.setAdminCreateUserId(session_admin.getAdminId());
            logger.info("增加的使用者資訊+"+admin);
            adminService.insert(admin);
            return new JsonResult();
        }
    }
}

前段HTML

<!-- layui的表單元件 -->
<div class="layui-container">
    <form class="layui-form" onsubmit="return false;">
        <div class="layui-form-item">
            <label class="layui-form-label">使用者名稱</label>
            <div class="layui-input-block">
                <input type="text" name="adminUser" autocomplete="off" placeholder="請輸入使用者名稱" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">密碼</label>
            <div class="layui-input-block">
                <input type="password" name="adminPassword" autocomplete="off" placeholder="請輸入密碼" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">手機號</label>
            <div class="layui-input-block">
                <input type="text" name="adminPhone" lay-verify="phone|number" autocomplete="off" placeholder="請輸入手機號" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">郵箱</label>
            <div class="layui-input-block">
                <input type="text" name="adminEmail" lay-verify="email" autocomplete="off" placeholder="請輸入郵箱" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">鎖定</label>
            <div class="layui-input-block">
                <input type="checkbox" name="adminLocked" lay-skin="switch" lay-filter="switchTest" lay-text="ON|OFF">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">鹽值</label>
            <div class="layui-input-block">
                <input type="text" name="adminSalt" autocomplete="off" placeholder="請輸入標題" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" id="data_sub">立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</div>
</body>
<script type="text/javascript" th:inline="javascript">
    // 獲取專案名
    const context = [[${#httpServletRequest.getContextPath()}]];
	// 提示框的函式
    function error_tipe(error_hint) {
        layer.msg(error_hint, {
            icon: 5,
            time: 2000 //2秒關閉(如果不配置,預設是3秒)
        }, function(){
            return false;
        });
    }
	
    layui.use(['form'], function() {
        var form = layui.form
            ,layer = layui.layer;

        $("#data_sub").click(function() {
			
            let adminUser = $("input[name='adminUser']").val();
            let adminPassword = $("input[name='adminPassword']").val();
            let adminPhone = $("input[name='adminPhone']").val();
            let adminEmail = $("input[name='adminEmail']").val();
            let adminLocked = $("input[name='adminLocked']").val();
            let adminSalt = $("input[name='adminSalt']").val();

            if(adminUser.length < 2 || adminUser.length > 5) {
                error_tipe("使用者名稱不能少於2個字元或者超過5個字元");
                return false;
            }
            if(adminPassword.length < 6 || adminPassword.length > 12) {
                error_tipe("密碼長度不能少於6個字元或者超過12個字元");
                return false;
            }
            if(adminSalt.length < 2 || adminSalt.length > 4) {
                error_tipe("使用者名稱不能少於2個字元或者超過5個字元");
                return false;
            }

            let data_sub = {
                "adminUser": adminUser,
                "adminPassword": adminPassword,
                "adminPhone": adminPhone,
                "adminEmail": adminEmail,
                "adminLocked": adminLocked == "on" ? '1' : '0',
                "adminSalt": adminSalt
            };

            console.log(data_sub);

            $.post(context+"/admin/author/user/submit_add", data_sub, function(res) {
                if(res.code == 205){
                    error_tipe(res.msg);
                }else if(res.code == 200){
                    layer.msg("新增成功!", {
                        icon: 1,
                        time: 2000 //2秒關閉(如果不配置,預設是3秒)
                    }, function(){
                        // 重新整理父頁面的
                        location.href = context+'/admin/author/user';
                        var index = parent.layer.getFrameIndex(window.name); //先得到當前iframe層的索引
                        parent.layer.close(index); //再執行關閉
                    });
                }
            })

        })
    })
</script>