You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot注册页面开发遇Whitelabel Error Page问题求助

问题解决步骤

核心问题分析

  • 表单提交格式与@RequestBody不兼容:表单默认以application/x-www-form-urlencoded格式提交数据,但@RequestBody仅支持解析JSON格式,导致参数解析失败触发Whitelabel错误页。
  • Repository泛型参数不匹配:User实体的id类型为Integer,但UserRepository继承JpaRepository<User, Long>,类型不兼容会引发持久化异常。
  • 缺失Model类导入:Controller的signUp方法使用了Model但未导入对应类,导致编译错误。

代码修正

1. 修正UserController

移除@RequestBody,改用@ModelAttribute接收表单参数,补充GET请求映射用于访问注册页面:

package com.Kumar.signup.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import com.Kumar.signup.user.UserRepository;
import com.Kumar.signup.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;

@Controller
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/signup")
    public String showSignUpForm() {
        return "SignUp";
    }

    @PostMapping("/signup")
    public String signUp(@ModelAttribute User user, Model model) {
        System.out.println("Received user: " + user);
        userRepository.save(user);
        model.addAttribute("name", user.getUsername());
        return "greeting";
    }
}

2. 修正UserRepository

将泛型参数改为与User实体id匹配的Integer:

package com.Kumar.signup.user;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
    User findByUsername(String username);
}

3. 调整页面目录(规范做法)

将SignUp.html从static目录移至templates目录(与Thymeleaf模板引擎的规范目录一致),无需修改文件名。

4. 补充表单字段(可选)

若User实体的email字段为必填项,在SignUp.html中添加邮箱输入框:

<label for="email">Email:</label><br>
<input type="email" id="email" name="email" required><br>

验证流程

  1. 启动Spring Boot应用,访问http://localhost:8080/signup打开注册页面。
  2. 填写表单并提交,将自动跳转到greeting页面,显示欢迎信息。

内容的提问来源于stack exchange,提问作者Huso Koc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 10:32:06