Search code examples
javaspringspring-bootjspjstl

Adding a ArrayList in more than one JSP page


I need to add this to two or more JSP pages. I want to try to avoid boilerplate code and need this code snippet in several JSP pages.

  1. where do I place this code snippet as far as a directory com.lizardking.demographic.xxx?
  2. how would I get it to be placed in the JSP file coming from another external file?
  3. what would this file be considered as far as naming convention, for example, a utility class, etc.

I'm using Spring Boot for the backend.

<%
    ArrayList<String> maritalStatusList = new ArrayList<String>();

        maritalStatusList.add("single/soltero");
        maritalStatusList.add("married/casado");
        maritalStatusList.add("divorced/divorciado");
        maritalStatusList.add("widow(er)/viudo(a)");

    request.setAttribute("maritalStatusList", maritalStatusList);
%>


Marital status/Estado civil
<select id="maritalStatus" name="maritalStatus">
<option value=""></option>
<c:forEach items="${maritalStatusList}" var="listItem">
    <option value="${listItem}" <c:if test="${listItem eq demoEntity.maritalStatus}">selected="selected"</c:if> >
        ${listItem}
    </option>
</c:forEach>    
</select>

Solution

  • If you are using Spring Boot MVC, maybe it's better to insert maritalStatusList from the controller into the Model object. So you can use a method to generate the data of your ArrayList, let's say generateStatusList(), and from your Controller method, before returning the .jsp:

    ...
    ArrayList <String> maritalStatusList = generateStatusList();
    model.addAttribute("maritalStatusList", maritalStatusList);
    ...
    

    And then you can access maritalStatusList with your .jsp code

    Take a look at https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-modelattrib-methods