繁体   English   中英

Vue 请求中的 POST 参数到 Java Servlet 没有通过 Servlet?

[英]POST parameters in Vue request to Java Servlet not getting through to 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。

唔。 我通常这样做的方法是定义一个 class ,它是输入数据(数据传输对象)的 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 引导和注释来控制它,我怀疑您的操作级别错误。 我认为您需要向 HttpServletRequest.getParameter 询问“postData”或类似的东西,它本身就是 map。 我建议您在调试器中暂停并查看 req 的参数部分中的内容,或者使用 printf 记录 req.getParameters() 中的内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM