You need to enable JavaScript to run this app. Spring MVC中Ajax登录请求返回404但Controller处理成功的问题排查
优惠活动
大模型
产品
解决方案
定价
更多

Spring MVC中Ajax登录请求返回404但Controller处理成功的问题排查

登录功能问题(Spring MVC Ajax 404)

问题背景

开发基于Spring MVC的简易登录表单,已编写APIResponseModel类,该类包含Status、Message、HTTPStatus三个变量及对应getter、setter方法。
填写账号凭证、点击提交按钮后,Ajax请求返回404状态码;但排查Controller层逻辑发现,同一请求实际处理完成后返回了{"status":"200","message":"Login Success!!","data":"Admin"}的成功结构,Ajax端却收到404错误。
现附上各环节相关代码,请求定位错误原因:


相关代码

Spring Controller

@RequestMapping("/login")
public APIResponseModel getLoginPage(@ModelAttribute("loginUser") UserDTO userDto, HttpSession session) {
    APIResponseModel apiResponseModel = new Utils().getDefaultApiResponse();
    logger.info("USER DTO :" + userDto.toString());
    List<String> errorList = new ArrayList<>();
    try {
        userService = new UserServiceImpl();
        UserModel userModel = userService.validateLogin(userDto, null, errorList);
        if (errorList.isEmpty()) {
            apiResponseModel.setMessage("Login Success!!");
            apiResponseModel.setStatus(HttpStatus.OK);
            if (userModel.getRole() == Constants.UserRole.ADMIN) {
                apiResponseModel.setData("Admin");
            } else if (userModel.getRole() == Constants.UserRole.STORE_MANAGER) {
                apiResponseModel.setData("StoreOwner");
            } else {
                apiResponseModel.setData("landing");
            }
            session.setAttribute("loggedInUser", userModel);
        } else {
            apiResponseModel.setMessage(errorList.isEmpty() ? "Invalid Credientials !!" : errorList.toString());
        }
    } catch (Exception exe) {
        exe.printStackTrace();
        logger.info("Exception occured at : " + exe.getMessage());
    }
    logger.info("------------------------------------------------------------------------");
    logger.info(apiResponseModel);
    return apiResponseModel;
}

登录校验JS函数

function processLogin(e) {
    e.preventDefault(); 
    let formData = new FormData();
    console.log($("#email").val()); 
    console.log($("#password").val());
    formData.append("email", $("#email").val());
    formData.append("password", $("#password").val()); 
    
    var obj = new MasterAjax();
    obj.requestType = "POST";
    obj.url = "login";
    obj.data = formData;
    obj.contentType = false;
    obj.requestData(function(responseData) {
        console.log("RESPONSE DATA :::::::" + responseData);
        console.log(responseData.status);
        console.log(responseData.message);
        console.log(responseData.data);
        if (responseData.status == "OK" || responseData.status == "ok") {
            alert("success");
        } else {
            alert("Login failed");
        }
    }); 
}

MasterAjax类

class MasterAjax {
    constructor() {
        this.requestType = null;
        this.url = null;
        this.timeout = 100000;
        this.enctype = null;
        this.data = null;
        this.processData = null;
        this.contentType = null;
        this.responseData = null;
        this.responseStatus = null;
        this.responseStatusCode = null;
    }
    
    requestData(callBack) {
        var parameterError = false;
        if (null == this.requestType) {
            parameterError = true;
            console.log("Error: Request Type can't be null");
        }    
        if (null === this.url || undefined === this.url || "undefined" === this.url) {
            parameterError = true;
            console.log("Error: URL can't be null");
        }  
        if (null == this.data || this.data.length <= 0) {
            // 控制台提示数据为空
        }
        if (parameterError === false) {
            $.ajax({
                type: this.requestType,
                enctype: this.enctype,
                processData: this.processData, 
                contentType: this.contentType, 
                url: global_contextPath + "/" + this.url,
                data: this.data,
                timeout: this.timeout,
                success: function(responseData, textStatus) {
                    callBack(responseData, textStatus);
                },
                error: function(responseData, textStatus) {
                    callBack(responseData, textStatus); 
                }
            }); 
        }
    }
}

登录表单

<form class="page" name="loginForm">
 <input class="email" id="email" path="email" type='text' align="center" placeholder="用户名/邮箱" />
 <input class="pass" id="password" path="password" type='password' align="center" placeholder="密码" />
 <button class="submit" onclick="processLogin(event)">登录</button>
 <p class="forgot" align="center"><a href="#">忘记密码?</a></p>
</form>

错误定位及修复方案

  • 核心错误1:Controller返回值未绑定响应体
    Spring MVC默认将Controller返回值解析为视图跳转地址,而非JSON响应。当前方法直接返回APIResponseModel对象,未标注@ResponseBody,导致Spring尝试将对象转为视图名时解析失败,触发404。
    修复方式:在getLoginPage方法上添加@ResponseBody注解;或将Controller类的@Controller替换为@RestController(该注解默认包含所有方法的@ResponseBody)。

  • 核心错误2:Ajax processData参数配置缺失
    使用FormData传递表单数据时,jQuery Ajax默认会序列化请求数据,破坏原生FormData格式。当前仅设置了contentType: false,未设置processData: false,可能导致请求格式异常触发路由不匹配。
    修复方式:在MasterAjax的Ajax配置中,将processData硬编码为false;或在实例化MasterAjax时给processData赋值false。

  • 次要错误:状态码判断逻辑不匹配
    JS中判断responseData.status == "OK",但APIResponseModel的status字段设置的是HttpStatus.OK枚举或数值200,并非字符串"OK",会导致即使请求成功也触发失败提示。
    修复方式:将判断逻辑改为responseData.status == 200。


内容的提问来源于stack exchange,提问作者shivam sharma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.16 19:06:09