2009-05-12

Ajax in Confluence plugin using a servlet

3rd part in Confluence plugin development series..
While working with Confluence I found 2 ways to make Ajax requests:
  1. make requests to servlets
  2. make JSON requests to XWork actions
Today I'll describe the 1st way using a servlet. In my application I had 2 comboboxes: one for select of a city and other for a department. A list of departments is different for every city so when client selects a city, a list of departments needs to be reloaded.
The implementation is very simple and requires only to properly configure the servlet:
  1. edit your atlassian-plugin.xml file and add a servlet definition, see Developer documentation for further info
  2. <servlet name="Ajax List Servlet"
    key="ajaxListServlet"
    class="dot.userinfo.users.servlets.AjaxListServlet">
    <description>Ajax List Servlet</description>
    <url-pattern>/getlist/</url-pattern>
    </servlet>
  3. implement AjaxListServlet class, I prefer to generate HTML code directly, but you can generate JSON array as well
  4. public class AjaxListServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void service(HttpServletRequest req,
    HttpServletResponse resp)
    throws ServletException, IOException {

    String list = req.getParameter("list");

    if ("dep".equalsIgnoreCase(list)) {
    String cityName = req.getParameter("city");

    // generate departments list HTML
    StringBuffer sb = new StringBuffer();
    sb.append("<option value='' selected></option>");
    try {
    for (DepartmentInfo dep : getDepartmentsDao().
    getByCityName(cityName)) {
    sb.append("<option>");
    sb.append(dep.getName());
    sb.append("</option>");
    }
    } catch (Exception e) {
    // handle exception
    }
    resp.getOutputStream().print(sb.toString());
    return;
    }
    }

    private DepartmentsDao getDepartmentsDao() {
    return DaoFactory.getDepartmentsDao();
    }
    }
  5. put comboboxes for city and department in .vm page
  6. #tag( Select "id=city" "name='user.city'" 
    "list=citiesDao.all"
    "listKey=name" "listValue=name"
    "emptyOption='true'" "theme='notable'" )
    #tag( Select "id=department" "name='user.department'"
    "list=departmentsDao.all"
    "listKey=name" "listValue=name"
    "emptyOption='true'" "theme='notable'" )
  7. and, finally, attach javascript to city combobox. here is a JQuery code
  8. jQuery(function($) {
    $("document").ready(function () {

    $("#city").change(function() {
    var cityName = $("#city option:selected").val();
    $.get("/plugins/servlet/getlist/",
    {list: "dep", city: cityName}, function(data) {
    $("#department").html(data);
    });
    });

    });
    });
    don't forget to include JQuery in your .vm page header
    <html>
    <head>
    <title>...</title>
    #requireResource("confluence.web.resources:jquery")
    </head>

No comments:

Post a Comment