简体   繁体   中英

Pass selected value from dropdown using JSP

I need to implement some basic dropdown using jsp and java, but I can't find more info how to do that. So I never write something using JSP and when I didnt find nothing that help the last options for me was to ask. I want to get the selected value and when click the button to send the value to anoher .jsp file ("selector.jsp in my case") Please folks help me with some easy solution.

pP: Sorry for my english (:

index.jsp

    <FORM method="post" action="selector.jsp">
    <select name="select" id="dropdown">
        <% 
            Test t = new Test();
            t.getList().add("a");
            t.getList().add("b");
            t.getList().add("c");
            for(int i=0; i < t.getList().size(); i++){ 
        %>
        <Option value="<%t.getList().get(i);%>"><%=t.getList().get(i)%></Option>
        <%}%>
    </select>
    <input type="submit" value="click"> 

selector.jsp

    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
    You selected:
    <%
       request.getParameter("select");
       request.getParameterValues("select");
    %>
   </body>
   </html>

I found a solution by removing

value="<%t.getList().get(i);%>"

from and leave the code just with

<Option><%=t.getList().get(i)%></Option>

but i don't know why... if someone can explain will be great. Thx! (:

As you have indicated in your post, the problem is solved by replacing

value="<%t.getList().get(i);%>"

with

<Option><%=t.getList().get(i)%></Option>

The reason that works is as follows:

In your first form, <%t.getList().get(i);%>, you have a JSP scriptlet. This is Java code that is executed inline. In your case, this executes the "get" method. Note however that the get method returns a value, but this value is not output into the response stream.

In your second form, you have formed a JSP expression by using "<%=". "<%=" is shorthand for "out.println", thus you have provided shorthand for the following:

<Option><% out.println(t.getList().get(i)) %></Option>

This writes the return value of the method call to the output stream. So that when this output reaches the browser, there is an actual value within the Option tags.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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