Ankur
Ankur

Reputation: 51128

How do I trigger a servlet method on page load

I have entries in a text file which I want to load into a drop down box.

I want this to happen on loading a jsp page. I could easily do this if I had a button that triggered the passing of a request object to the servlet. How do I send a request object on page load - do I need to use Javascript or is this something I can do with just jps.

Upvotes: 2

Views: 4003

Answers (2)

BalusC
BalusC

Reputation: 1109755

You can use Servlet's doGet() method to preprocess data on GET requests. The doPost() is to be used to postprocess data on POST requests (when you submit the form).

Example:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<Option> options = optionDAO.list();
    request.setAttribute("options", options);
    request.getRequestDispatcher("page.jsp").forward(request, response);
}

Where the Option class is just your own javabean class containing the properties value and label. You can also use a List<Map<String, String>> instead if you like.

In JSP you can use the JSTL c:forEach to iterate over a list

<select name="foo">
    <c:forEach items="${options}" var="option">
        <option value="${option.value}">${option.label}</option>
    </c:forEach>
</select>

Finally map the servlet in web.xml and invoke the request so that it matches its url-pattern, e.g. http://example.com/contextroot/page.

Upvotes: 0

cletus
cletus

Reputation: 625457

Where you can populate it on the serverside. By that I mean that when you create the select box on your JSP, populate it then. For example:

<select id="sel1" name="animal">
<c:forEach var="animal" items="${model.animals}">
<option value="<c:out value="${animal.id}"/><c:out value="${animal.name}"/></option>
</c:forEach>
</select>

If that isn't possible, practical or desired, you'll need to use some form of AJAX method. Personally I use jQuery for this. For example:

<select id="sel1" name="animal">
</select>

<script type="text/javascript">
$(function() {
  $.get('/server/getanimals', function(data, textStatus) {
    var sel = $("#sel1");
    for (var i=0; i<data.length; i++) {
      sel.append('<option value="' + data[i].id + '">' + data[i].name + '</option>');
    }
  }, 'json');
});
</script>

The above calls /server/getanimals on page ready. It is expecting to be returned a JSON object with a list of animals that it then uses to populate the select box.

There are lots of ways to skin this particular cat.

Upvotes: 2

Related Questions