0

I'm a beginner on JSP, I'm trying to develop a small MVC project, and for login page, it's kind of easy to use MVC, like, login.jsp-->LoginServlet.java--->UserBean.java.

But, after signing in, I have a Main.jsp page with several html elements on it, one of these elements is a dropdown list, and the items are from database, I've seen that people doing this with below code inside the jsp, but this is not so "MVC", right? there's no "C", so, I'm curious to know what it the best practice for this scenario? Thanks!

<%
database stuff...
while(resultset.next()){
 %>
  <option value="<%=rs.getString("DEPT_NO")%>"><%=rs.getString("DEPT_NAME")%></option>  
  <% }
gfytd
  • 1,747
  • 2
  • 24
  • 47

1 Answers1

2

To populate a drop-down list using MVC pattern ,

  1. In the LoginServlet the get the data from the database .
  2. As you are using MVC pattern , can use a DAO class for retrieving the data from the database. You should also have the bean class to pass the values as objects.
  3. Finally, set the object (e.g ArrayList) to request attribute and Forward it to the main.jsp

So you will have the object in the request , now display it in the dropdown box using jstl using forEach tag,

            <c:forEach var="temp" items="${list}">                    
                    <c:out value="${temp}"></c:out>                    
            </c:forEach>

see this How to avoid Java code in JSP files?

Hope this helps !!

Community
  • 1
  • 1
Santhosh
  • 8,181
  • 4
  • 29
  • 56