gpt4 book ai didi

java - 如何从java servlet获取参数值

转载 作者:行者123 更新时间:2023-12-01 08:03:47 27 4
gpt4 key购买 nike

我试图获取传递给 Java Servlet 的参数值,但返回的字符串不正确。我将值存储在映射中并检查键是否存在。

Map params;
params = request.getParameterMap();

String id = params.get("id").toString();
String data = params.get("data").toString();

System.out.println("streaming" + data + " with id of " + id);

但是,如果我通过 http://localhost:8080/Serv/stream/data?data=hereisdata&id=you 调用此 servlet,我的输出将如下所示:

streaming[Ljava.lang.String;@5e2091d3 with id of [Ljava.lang.String;@36314ab8

我错过了什么?

编辑:由于建议的答案不起作用,我将整个类(class)包括在内,因为我可能会在类(class)中搞砸一些事情:

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import Engine.Streamer;


public class AnalyzerController {

private Map params;
private String pathInfo;
private HttpServletRequest request;

public AnalyzerController(HttpServletRequest request)
{
this.params = request.getParameterMap();
this.pathInfo = request.getPathInfo();
}

public void processRequest()
{
System.out.println("procing with " + pathInfo);

switch(pathInfo){
case "/stream/data":
if(params.containsKey("id") && params.containsKey("data")) processStream();
break;
}
}

private void processStream()
{
System.out.println("we are told to stream");
String data = request.getParameter("data");
String id = request.getParameter("id");
Streamer stream = new Streamer();

stream.streamInput(data, "Analyzer", id);
}
}

这一行具体抛出了 NPE:String data = request.getParameter("data");

最佳答案

如果您查看 Request#getParameterMap() 的文档,它返回 Map类型 Map<String, String[]> 。因此,需要从值 String[] 中取出第一个元素从 map 返回的数组。

String id = params.get("id")[0];

当然,您可以避免这一切,直接使用 Request#getParameter() 从请求对象中获取参数。方法。

String id = request.getParameter("id");

编辑:查看您的类代码,似乎实例变量 request未初始化。在构造函数中初始化它,如下所示:

public AnalyzerController(HttpServletRequest request)
{
this.request = request; // Initialize your instance variable request which is used in the other methods.
this.params = request.getParameterMap();
this.pathInfo = request.getPathInfo();
}

关于java - 如何从java servlet获取参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23212065/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com