AJAX and JBoss

Today i would like to show you how you can use AJAX in a JSP side with jboss.
It is not that easy to find a good tutorial, so i try to do my best to make it as easy as it is.
So enjoy reading 🙂 


Sunday, 08 October 2006

First we need to have a working JavaScript.


<script language="javascript">
function ajaxLoadPage(pageToLoad, contentName) {
        var req;
        var url = "action=ajaxLoadPage&page="+pageToLoad;    
        if (window.XMLHttpRequest) {     // firefox etc.
            req = new XMLHttpRequest();
        } else if (window.ActiveXObject) { // internet explorer
            req = new ActiveXObject("Microsoft.XMLHTTP");
        // the action has to be POST.
        // inetsource is the name of your Servlet
        // true means asynchron as i remember :)        
        req.open("POST", 'inetsource', true);
        req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        req.setRequestHeader('Content-Length',  url.length);    
        // set callback function into that function to avoid using
        // a global request variable this time
        req.onreadystatechange = function callback () {
               if (req.readyState == 4) {
                if (req.status == 200) {       
                    document.getElementById (contentName).innerHTML
								= req.responseText;


Lets now take a look at the servlet. ( i will explain it all later )

  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                                throws ServletException, IOException {
    try {
      String action = req.getParameter(PARAM_ACTION);
      if (isSet(action&& action.equals(“ajaxLoadPage”)) {
        String pageToLoad = req.getParameter(“page”)
        if (isSet (pageToLoad)) {          
          req.getRequestDispatcher(pageToLoad).forward(req, resp);          
    catch (ServletException e) {
    catch (IOException e) {

  private boolean isSet (String requestStr) {
    if requestStr != null && requestStr.length()>0return true;
    return false;
So lets now create a working example.
You have to create a JSP (do not call it example.jsp) file with the following link
<a href=”javascript:ajaxLoadPage(‘example.jsp’, ‘content’);”>Example</a>
because we want to load the example.jsp page into the div content,
we also have to create a div called content.
<div id=”content”> thats my div </div>

If you now click on that link, the servlet will try to load you JSP File called example.jsp.
So if you created a file with the content <b> my First AJAX Page </b>

Your div will now have written my FIRST AJAX Page into its DIV.
Thats all.



Leave a Reply

Your email address will not be published. Required fields are marked *