gpt4 book ai didi

java - 向同一页面和同一 servlet 发送请求参数

转载 作者:太空宇宙 更新时间:2023-11-04 09:08:29 25 4
gpt4 key购买 nike

所以,我试图从下拉列表中获取值并将它们添加到 ArrayList 以便稍后我可以显示它,但我不知道该怎么做?

基本上,当用户按下下一步(发送)按钮时,Servlet 应该获取值参数,并将其存储到数组列表中以供以后使用,并且应该将他们引导回表单页面,以便他们可以进行更多选择或通过按完成(列表)按钮查看他们选择了哪些选项

Servlet(水果servlet)

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html;charset=UTF-8");

String wasSent = request.getParameter("send");
String Submitted = request.getParameter("list");
ArrayList<Double> fruitsList = new ArrayList<Double>();


if (wasSent != null) {
String fruits = request.getParameter("Values");
fruitsList.add(fruits);
request.setAttribute("List", fruitsList);
RequestDispatcher rs = request.getRequestDispatcher("form.html");
rs.forward(request, response);

} else if (Submitted != null) {

//get the list and display all the values
}

}

最佳答案

在您的 servlet 中您可以使用 session在数组中设置您的值,以便该值将被保存,直到您将其从 session 中删除。您的代码将如下所示:

 protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html;charset=UTF-8");

String fruits = request.getParameter("Values");
ArrayList<String> fruitsList1 = new ArrayList<String>();
//get values which are in session
ArrayList<String> fruitsList = (ArrayList<String>)request.getSession().getAttribute("List");

//if attribute value is not null
if (fruitsList != null) {
//add new values
fruitsList.add(fruits);
request.getSession().setAttribute("List", fruitsList);
RequestDispatcher rs = request.getRequestDispatcher("form.html");
rs.forward(request, response);

} else if (fruitsList== null) {
//adding value selected in array list
fruitsList1.add(fruits);
//setting values
request.getSession().setAttribute("List", fruitsList1);
RequestDispatcher rs = request.getRequestDispatcher("form.html");
rs.forward(request, response);
} else{

//remove values
}

}

关于java - 向同一页面和同一 servlet 发送请求参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59935627/

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