首页 > 解决方案 > Vue请求中的POST参数对Java Servlet没有通过Servlet?

问题描述

我目前正在学习 Vue,并试图将一些 post 变量发送到一个简单的 Java servlet。但是,当我尝试访问它们时,所有对 getParameter 的调用都显示为 NULL。

我使用以下代码发送发布请求:

    let formData = new FormData();
    formData.append('brukernavn',this.skjema.brukernavn);
    formData.append('passord',this.skjema.passord);
        console.log(formData);      
    axios.post('/BoardgamesRegister/ajax/login',formData)
    .then(function(response){
        console.log(response);
        })
    .catch(function(error){
    });

但是,当我尝试使用此代码在服务器端访问这些变量时,我只是将 NULL 作为值。

public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException  {       
    
    System.out.println(req.getParameter("brukernavn"));
    System.out.println(req.getParameter("passord"));
    
    this.executeRequest(req,res,pw,null);
}

问题是,如果我尝试将 GET 参数添加到调用的 URL,则 getParameter 方法会正确获取该值。因此,我的 POST 变量似乎以某种方式丢失了请求。我的 Vue 代码有问题还是服务器端有问题?我尝试通过请求参数进行枚举,并且只显示了获取参数,而不是发布参数。

这似乎是 Java Servlet 中的一个问题,因为当我尝试将请求发送到 PHP 脚本时,POST 参数被正确拾取。

@Tim 的评论不是问题,但它确实引领了正确的道路。我不知何故错过了 Axios 自动将调用后参数加密为 JSON。所以在正常的 POST 请求中,getParameter 确实可以工作,但在这里不行。所以现在,我只需要找到一种方法来阻止 Axios 转换为 JSON。

标签: javavue.jsservlets

解决方案


唔。我通常这样做的方式是定义一个类,它是输入数据(数据传输对象)的 DTO,我把它作为定义为 REST 的方法的参数(连同 @RequestBody 注释)通过@PostMapping 的端点。

@PostMapping("/thingDetail")
@ApiResponses(value = {
    @ApiResponse(code = 200, message = "Success"),
    @ApiResponse(code = 500, message = "Internal Server Error")
})
@ApiOperation(value = "Get detail information about a thing.")
public ThingDetailsDTO getThingDetails(@RequestBody ThingDetailsRequestDTO requestDto)
{
    return thingService.getDetails(requestDto);
}

但是,如果您没有使用 Spring Boot 和注释来控制它,我怀疑您的操作级别错误。我认为您需要向 HttpServletRequest.getParameter 询问“postData”或类似的东西,这本身就是一张地图。我建议您在调试器中暂停并查看 req 的参数部分中的内容,或者使用 printf 记录 req.getParameters() 中的内容。


推荐阅读