Announcement Announcement Module
Collapse
No announcement yet.
XT Ajax Framwork Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • XT Ajax Framwork

    Hello,

    Im working on a small Webapplication with Spring, Spring MVC, Spring Security and Hibernate. Today I wanted to integrate Ajax, for example to check asynchrounly if a username is already in use while the user is filling out a formular to register.

    I began to write the ajax stuff, but I found it a little bit difficult to integrate it nicely in my existing project. I was reading about it and I found out that I should use tiles when I use ajax and spring mvc. Well, until now I didnt use tiles and I dont want to change my whole configuration.

    As I went on researching, I read about the XT Ajax Framework. It sounds like a really nice solution.
    But I was wondering why it was so hard to find out about the XT Ajax Framework. Is it maybe old and not recommended to use? Are there new solutions which are way better than this? I would like to hear your opinion!

    Thank you very much!

  • #2
    another question: since really nobody is talking about this framework, maybe you could help me with my ajax problem.

    A User wants to register. When he types in the username, an ajax request is send. The Request is mapped to a controller, which looks up the necessary information (is the username in use) and returns a value (string, boolean, whatever.) this value is returned as ....

    at the moment I return it as a ModelAndView value. But then my page looks horrible.

    the red marked area shows where the answer is shown. at this point the new modelandview is shown. in this moment it is the same page as I use for registering, so the page is shown twice.
    Should I use another new jsp, which only contains the word? or what could I return??

    here is my code: (snippets)

    JSP

    Code:
      <script type="text/javascript">
          var anfrage = null;
          
     try {
                  anfrage = new XMLHttpRequest();
              } catch (trymicrosoft) {
                  try {
                    anfrage = new ActiveXObject("Msxml12.XMLHTTP");
                  } catch (othermicrosoft) {
                      try {
                        anfrage = new ActiveXObject("Microsoft.XMLHTTP");
                      } catch (err) {
                          anfrage = null;
                      }
                  }
              }
          
          
              if (anfrage == null) {
      
              }
    
          
    
          function updatePage(){
              if (anfrage.readyState == 4) {   // 4 = Serverantwort steht bereit     
                var answer = anfrage.responseText;
                
                document.getElementById('answer_username').innerHTML = answer;
    
                  
              }
    
          }
          
    
          function checkUsername(){
              var usern = document.getElementById("username").value;
    
              var url = "${pageContext.request.contextPath}/registerajax/"+escape(usern); 
              anfrage.open("POST", url, true); 
              
              anfrage.onreadystatechange = updatePage;
              anfrage.send(usern);
     }
          
          
      </script>
    
    
        <form id="register" class="text" action="${pageContext.request.contextPath}/register" method="post" onSubmit="return pruefen()">
    
    <p class="fontSmall">
        Fill in the formular and register now!<br/>
    
            </p>
    
     <table border="0" cellpadding="0" cellspacing="4">
        <tr>
          <td align="right">Username</td>
          <td><input id="username" type="text" class="inputField" name="username" onChange="checkUsername()"></td>
          <td id="answer_username">  <c:out value="${model.answer}"/>  </td>
        </tr>
    
        <tr>
          <td align="right">Emailaddress</td>
          <td><input type="text" class="inputField" name="email"></td>
        </tr>
        <tr>
    
      </table>
            <br>
              <input type="submit" value="Register">
            
    
        </form>
    Controller

    Code:
    @Controller
    public class RegisterAjaxController {
    
    
        /**
         * is called when the user types in a username and checks whether this name is free for user
         */
        @RequestMapping(value ={"/registerajax/{username}"}, method = RequestMethod.POST)
        public ModelAndView checkUsername(@PathVariable("username") String username) {
            logger.info("checkUsername(..): check username for ajax request, rm=post");
    
            Map myModel = new HashMap();
            boolean userCheckOk;
    
            userCheckOk = regCheck.checkUsername(username);
    
            myModel.put( "answer", userCheckOk );
    
            return new ModelAndView( "register", "model", myModel );
    
        }
    
    }
    Thank you for an answer!

    Comment


    • #3
      If you are using Spring 3 configured with <mvc:annotation-driven/>, you could download Jackson JSON Processor jars and add them to your WEB-INF/lib. Then annotate your controller method with @ResponseBody. The model you return would be printed to the output as a json string which you can use with prototype or jquery to put it on the page. It's all throughly explained in this excellent article by Keith Donald :

      http://blog.springsource.com/2010/01...in-spring-3-0/

      Comment


      • #4
        thanks for your answer! I read that article. Is there any possibility to do it without json? I want to change as less as possible in my configuration....

        Comment


        • #5
          ok.

          I downloaded Jackson Json Processor jars (jackson src 1.6.2), which are a lot of jars and I decided to put in my web-inf/lib folder:

          json-org.jar
          json_simple-1.0.2.jar
          jsontools-core-1.5.jar

          are these the ones I need?

          then I changed my controller, I added @ResponseBody as you said, but I still return a ModelAndView. I understood that I should do that when I read your answer. I give back the "register.jsp", which is the jsp where the request comes from and where the string shall be displayed, is that right?

          Code:
          package project.mvc.controller;
          
          import project.business.logic.RegistrationCheck;
          import java.util.HashMap;
          import java.util.Map;
          import org.slf4j.Logger;
          import org.springframework.beans.factory.annotation.Autowired;
          import org.springframework.beans.factory.annotation.Qualifier;
          import org.springframework.stereotype.Controller;
          import org.springframework.web.bind.annotation.PathVariable;
          import org.springframework.web.bind.annotation.RequestMapping;
          import org.springframework.web.bind.annotation.RequestMethod;
          import org.springframework.web.bind.annotation.RequestParam;
          import org.springframework.web.bind.annotation.ResponseBody;
          import org.springframework.web.servlet.ModelAndView;
          
          
           @Controller
          public class RegisterAjaxController {
          
              private Logger logger = org.slf4j.LoggerFactory.getLogger(RegisterAjaxController.class);
          
          
              @Autowired(required=true)
              @Qualifier("regCheck")
              private RegistrationCheck regCheck;
          
          
              /**
               * is called when the user types in a username and checks whether this name is free for user
               */
              @RequestMapping(value ={"/registerajax/{username}"}, method = RequestMethod.GET)
              public @ResponseBody ModelAndView checkUsername(@PathVariable("username") String username) {
                  logger.info("checkUsername(..): check username for ajax request, rm=post");
          
                  Map myModel = new HashMap();
                  boolean userCheckOk;
          
                  userCheckOk = regCheck.checkUsername(username);
          
                  myModel.put( "answer", userCheckOk );
          
          	return new ModelAndView( "register", "model", myModel );
              }
          
          
          }

          I downloaded the spring example for mvc and ajax, but I dont really understand how to print out the string on my jsp.

          . The model you return would be printed to the output as a json string which you can use with prototype or jquery to put it on the page.
          I have never used prototype or jquery before. I dont understand how I have to change my jsp. Can I keep my ajax methods or do I have to use those from the example from spring?

          here is my code: the green part is the code from the spring example, the red part is my old code. can I use my old code?

          how can I print out the answer? I would be very(!) grateful, if you could give me just a line, a snippet, to show me how to print out, so that I can implement it and learn how to do it! Thank you for your help!

          Code:
          <%@ include file="/WEB-INF/jsp-includes/includes.jsp" %>
          <%@ include file="/WEB-INF/jsp-includes/header.jsp" %>
          
          
            <script type="text/javascript">
          
          
                // Spring Ajax Json Example
          
                $(document).ready(function() {
              // check name availability on focus lost
              $('#name').blur(function() {
                  checkAvailability();
              });
          });
          
          function checkAvailability() {
              $.getJSON("account/availability", { name: $('#name').val() }, function(availability) {
                  if (availability.available) {
                      fieldValidated("name", { valid : true });
                  } else {
                      fieldValidated("name", { valid : false,
                          message : $('#name').val() + " is not available, try " + availability.suggestions });
                  }
              });
          }
          
          
          
          
                /*
                var anfrage = null;
                
                    try {
                        anfrage = new XMLHttpRequest();
                    } catch (trymicrosoft) {
                        try {
                          anfrage = new ActiveXObject("Msxml12.XMLHTTP");
                        } catch (othermicrosoft) {
                            try {
                              anfrage = new ActiveXObject("Microsoft.XMLHTTP");
                            } catch (err) {
                                anfrage = null;
                            }
                        }
                    }
                
                
                    if (anfrage == null) {
                    }
          
                
          
                function updatePage(){
                    if (anfrage.readyState == 4) {   // 4 = Serverantwort steht bereit     
                      var answer = anfrage.responseText;
                      
                      document.getElementById('answer_username').innerHTML = answer;
          
                        
                    }
          
                }
                
          
                function checkUsername(){
                    var usern = document.getElementById("username").value;
          
                    var url = "${pageContext.request.contextPath}/registerajax/"+escape(usern); 
                    anfrage.open("POST", url, true); 
                    anfrage.onreadystatechange = updatePage;
                    anfrage.send(usern);
           }
                */
                
            </script>
          
          
          <%@ include file="/WEB-INF/jsp-includes/headerMenu.jsp" %>
          
          
          
          
          
          
          
              <form id="register" class="text" action="${pageContext.request.contextPath}/register" method="post">
          
          <p class="fontSmall">
              Fill in the formular and register now!
                  </p>
          
           <table border="0" cellpadding="0" cellspacing="4">
              <tr>
                <td align="right">Username</td>
                <td><input id="username" type="text" class="inputField" name="username" onChange="checkUsername()"></td>
                <td id="answer_username">  <c:out value="${model.answer}"/>  </td>
              </tr>
          
          
            </table>
                  <br>
                    <input type="submit" value="Register">
                  
          
              </form>

          Comment


          • #6
            You shouldn't return a modelandview. If you mark the method with @ResponseBody, what you return is directly written to the response, so there is no view or model involved. So you should return directly the object you want to retrieve with ajax on the javascript side, in your case a Boolean object.

            On client side, of course you can use normal javascript way to make an ajax call, but using jquery or prototype is really much easier (nobody that I know use normal javascript for ajax anymore).

            Comment


            • #7
              I solved it. I can keep it like this and just return a string. a model is not needed anymore.
              Last edited by jeeper; Nov 18th, 2010, 08:41 AM.

              Comment

              Working...
              X