Question

I have a html page and a java application with Thymeleaf templating engine and I'm looking for a tutorial to make a request to the server and render only part of the page based on response.

At this moment, I have some buttons having a link of the same page with a different parameter, my div is created based on attribute articleList (which I receive from the server based on button_id)

HTML:

<a href="/index?button_id=1"> button 1 </a>
<a href="/index?button_id=2"> button 2 </a>

<div class="" th:each="article : ${articleList}">
    <p th:text="${article.getText()}">Article</p>

Java:

public class NodController implements IGTVGController {
  public void process(
        final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext servletContext, final TemplateEngine templateEngine) 
        throws Exception {

    final WebContext ctx = new WebContext(request, response, servletContext, request.getLocale());

    Integer button_id = Integer.valueOf(request.getParameter("button_id"));
    List<String> articleList = getArticleList(button_id);
    request.getSession().setAttribute("articleList",articleList);

    templateEngine.process("/index", ctx, response.getWriter());
    }

I want my buttons to process my index controller and only change the div with the articles and not refresh the entire page.

I have tried using ajax but I didn't find code examples for server-side that I could understand, so I don't know how to process the request and I don't know how to use servlets. Also I didn't manage to send any request to my current controller.

I have also found in thymeleaf api this method:

public final void process(String templateName, IContext context,
                      IFragmentSpec fragmentSpec, Writer writer)

where IFragmentSpec should "select a fragment of a template to be processed (once read and parsed), discarding the rest of the template" but I couldn't find more information about it as how to use it or if it is what I'm looking for.

Was it helpful?

Solution

this is the javascript code

//get text 1 by ajax
    function getText1(urlstarted) {
        xmlHttp = false;
        if (window.XMLHttpRequest) { // Mozilla, Safari,...
            xmlHttp = new XMLHttpRequest();
            if (xmlHttp.overrideMimeType) {
                // set type accordingly to anticipated content type
                //http_request.overrideMimeType('text/xml');
                xmlHttp.overrideMimeType('text/html');
            }
        } else if (window.ActiveXObject) { // IE
            try {
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }
        if (!xmlHttp) {
            alert('Cannot create XMLHTTP instance');
            return false;
        }

        var url=urlstarted+"/jsp/viewText1.jsp"; //put the link to ur Ajax page here
         xmlHttp.onreadystatechange = startAjaxingText;
        xmlHttp.open("GET", url, true);
        xmlHttp.send(null);
    }
    function startAjaxingText() {
        if (xmlHttp.readyState != 4) {

            document.getElementById('image').style.display='block' ;
            document.getElementById('result').style.display='none' ;
        }

        if (xmlHttp.readyState == 4) {

            if (xmlHttp.status == 200) {




                    document.getElementById('image').style.display='none' ;
                    document.getElementById('result').style.display='block';
                    document.getElementById('result').innerHTML = xmlHttp.responseText;


            } else {
                alert("There was a problem with the request.");
            }
        }

    }
//get text 2 by ajax
    function getText2(urlstarted) {
        xmlHttp = false;
        if (window.XMLHttpRequest) { // Mozilla, Safari,...
            xmlHttp = new XMLHttpRequest();
            if (xmlHttp.overrideMimeType) {
                // set type accordingly to anticipated content type
                //http_request.overrideMimeType('text/xml');
                xmlHttp.overrideMimeType('text/html');
            }
        } else if (window.ActiveXObject) { // IE
            try {
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }
        if (!xmlHttp) {
            alert('Cannot create XMLHTTP instance');
            return false;
        }

        var url=urlstarted+"/jsp/viewText2.jsp"; //put the link to ur Ajax page here
         xmlHttp.onreadystatechange = startAjaxingText2;
        xmlHttp.open("GET", url, true);
        xmlHttp.send(null);
    }
    function startAjaxingText2() {
        if (xmlHttp.readyState != 4) {

            document.getElementById('image').style.display='block' ;
            document.getElementById('result').style.display='none' ;
        }

        if (xmlHttp.readyState == 4) {

            if (xmlHttp.status == 200) {




                    document.getElementById('image').style.display='none' ;
                    document.getElementById('result').style.display='block';
                    document.getElementById('result').innerHTML = xmlHttp.responseText;


            } else {
                alert("There was a problem with the request.");
            }
        }

    }

now your buttons will look like this

    <input name="button_1" id="button_1" type="button" value="button_1" onclick="getText1('<%=request.getContextPath()%>');" />
     <input name="button_2" id="button_2" type="button" value="button_2" 
onclick="getText2('<%=request.getContextPath()%>');" />

your div will look like

<div id="image" style="display:none"><img src="<%= request.getContextPath()%>/images/ajax-loader.gif" alt="Loading...."/> </div>
                <div id="result" style="display:none"></div></td>

your viewText1.jsp page that doing ajax part

out.println("text1");//or any logic u want 

your viewText2.jsp page that doing ajax part

 out.println("text2");//or any logic u want 

note that : the result of viewText1.jsp or viewText2.jsp must be a text either a table or paragraphs

OTHER TIPS

Client-side implementation

You will have to use AJAX to load content from the server dynamically.

  1. Consider designing your frontend as SPA. Look into AngularJS or Knockout.

  2. Also, you can use old-school approach by using something like jQuery AJAX if this is just a small area of your application.

Separation of concerns

I strongly suggest to consider the idea to separate concerns by using server as a REST service and frontend as a client. This is the best practice for large applications if you want to keep them maintainable and scalable.

You should look for tutorials of how to implement REST with your server-side technology. It's very common practice so I think you should be able to find one.

If you have any questions I will be glad to update this answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top