尝试在我的 JSP 中获取数组列表结果总是在空变量中



我正在做一个项目,我需要做一个研究领域,它将在jsp页面上重定向我以显示结果。我在没有任何数据库的情况下工作,所以我将用户在输入中写入的字符串与字符串数组进行比较。

我有一个欢迎.jsp像这样:

<form name="form" method="post" action="http://localhost:8080/Miniproject/ResServlet">
   <label for="book">Search for a book</label><br>
  <input type="text" name="book" id="book">
  <br>
  <input type="submit" value="Chercher un livre" id="button_submit_book">
</form> 

我的servlet ResServlet.java是:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String book = request.getParameter("book");
        ArrayList<String> resultat = Reservation.search(book);
         request.setAttribute("resultat",resultat);
         RequestDispatcher dispatcher=getServletContext().getRequestDispatcher("/view/books.jsp");
            dispatcher.include(request, response);

        doGet(request, response);
    }

我的预订.java模型是:

import java.util.ArrayList;
public class Reservation {
     public String book;
     public String getBook() {
            return this.book;
        }
     public void setBook( String book ) {
            this.book = book;
        }
     public static ArrayList<String> search( String book ) {
         String book1 = book.toLowerCase();
         String[] booksarray = {"De la guerre, Clausewitz","Les Misérables, Victor Hugo","Le Rouge et le noir, Stendhal","livre1","livre2","livre3","livre4"};
         ArrayList<String> result = new ArrayList<String>();
         for (String bookname: booksarray) {   
             String book2 = bookname.toLowerCase();
             if(book2.equals(book1)) {
                 result.add(bookname);
             }
            }
        return result;
         }

        }

我试图用等号做,但也用包含,但没有任何效果

最后,书籍.jsp文件是:

<h2>RESULT OF THE RESEARCH</h2>
<% String[] resultat = request.getParameterValues("resultat"); %><br>
<% out.println(resultat); %><br>

但是在我的书中.jsp它总是显示"空"我不知道为什么......

如果你们中的一个人知道为什么它不起作用,它会对我有很大帮助,感谢您的关注和时间:D

您已经在请求对象中设置了结果,我还没有对此进行测试,但我通常会将会话中的值设置为

session.setAttribute("resultat", resultat);

在您的书籍中.jsp然后您可以将其检索为

<% ArrayList<String> resultat = (ArrayList<String>)(session.getAttribute("resultat")); %>

同样可能适用于请求对象,值得对此进行测试,但您需要使用 getAttribute((,而不是 getParameterValues((,因为这不是参数。

请注意,您设置的属性具有 ArrayList 类型,因此在调用 getAttribute(( 时需要使用相同的类型(ArrayList 与 String[] 不同(

最新更新