【问题标题】:I can not make a request and the Response to a servlet我无法向 servlet 发出请求和响应
【发布时间】:2015-01-29 13:03:20
【问题描述】:

我有一个 servlet。在其中我形成一条线,当我输入浏览器链接时,他告诉我旋转线。一切都很好。现在我想创建一个字符串数组,并根据链接中的参数旋转特定的行。怎么办?

@WebServlet("/goods")
public class GoodsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.print("{\"name\":\"Pavel\",\"sname\":\"Petrashov\",\"age\":24,\"params\":{\"heigth\":188, \"weight\":72, \"strong\":100}}");
    }
}

我想拥有

 List<String> list = new ArrayList<String>();
        list.add("{\"name\":\"Pavel\",\"sname\":\"Petrashov\",\"age\":24,\"params\":{\"heigth\":188, \"weight\":72, \"strong\":100}}");
        list.add("{\"name\":\"Bill\",\"sname\":\"Gey\",\"age\":99,\"params\":{\"heigth\":188, \"weight\":70, \"strong\":100}}");
        list.add("{\"name\":\"Uill\",\"sname\":\"Smitt\",\"age\":12,\"params\":{\"heigth\":188, \"weight\":99, \"strong\":100}}");

并确保我的引用 http://localhost:666/sg/goods接受了一些参数,具体取决于哪个将返回数组元素

【问题讨论】:

    标签: java jakarta-ee servlets httpsession


    【解决方案1】:

    您的意思是根据 GET 参数打印出列表中的字符串之一吗?如果那是你想要的 String myParameter = request.getParameter("param"); 会给你get参数。将参数作为查询字符串传递给 url,例如 http://localhost:666/sg/goods?param=2

    现在使用参数从列表中获取字符串

    try{ int index = Integer.parseInt(myParameter); out.println(list.get(index)); } catch(IndexOutOfBoundsException|NumberFormatException ex){ System.err.println("Invalid get parameter"); }

    【讨论】:

    • 我只是按照你之前说的做了,但是答案是正确的,我查了一下。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    相关资源
    最近更新 更多