Update JSP Excerpt via Servlet

1

I have the following case:

I have an index.jsp file, which has the structure below:

<jsp:include page="templates/header.jspf"/>
<div id="view">
<jsp:include page="home.jspf"/>
</div>
<jsp:include page="templates/footer.jspf"/>

For navigation I call the pages via ajax, and change the content of the div from id="view", via the JS below:

function abrirPag(valor){

    var url = valor;

    xmlRequest.open("GET",url,true);
    xmlRequest.onreadystatechange = mudancaEstado;
    xmlRequest.send(null);
    return url;
}

function mudancaEstado(){
    if (xmlRequest.readyState == 4){
        document.getElementById("view").innerHTML = xmlRequest.responseText;
    }
}

But I have a problem. I have a login form, which accepts login from clients and administrators. After logging in, I would like the system to validate the user type and reload this index.jsp including the corresponding header (it is a header for unlogged user, one for clients and one for administrators). I can not do this via servlet.

I tried to use RequestDispatcher for this, but it did not work.

I have also tried to call the JS function to reload the page, but it runs independently of the Servlet stream and I can not tell if the user who tried to log in actually exists, or whether he is an admin or a client.

Does anyone know how I could solve this?

    
asked by anonymous 20.06.2016 / 19:05

1 answer

0

One solution would be to create the 3 header structures on the page and leave them invisible. You make them visible according to the return coming from Servlet. This return can be a simple json.

Example:

<div class="invisible" id="adm">
<!-- aqui o código para montar o header de adm -->
</div>
<div class="invisible" id="client">
<!-- aqui o código para montar o header de adm -->
</div>
<div class="invisible" id="default">
<!-- aqui o código para montar o header de adm -->
</div>

Then you make an ajax request for Servlet:

$.post("your-domain.com/login", {username: "admin", password: "123admin"}).done(function(retorno){
       var json = JSON.parse(retorno);
       if(json.isAdmin){
          $("#adm").removeClass("invisible");
       } else if(json.isClient) {
          $("#client").removeClass("invisible");
       }
       //continua a logica para não logado também
});

Finally, in the servlet, you return a json if the login was as expected (administrator, client, not logged in)

//Logica de negócio, verifica no banco, bla bla bla
//...
Resultado resultado = new Resultado();
resultado.setIsAdmin(true);
resultado.setIsCliente(false);
resultado.setNaoLogado(false);
Gson gson = new Gson();

response.setContentType("text/html");
response.getWriter().write(gson.toJson(resultado));

This is just one of several solutions you can choose from.

To create JSON from a class, I used the Google lib called Gson. I used JQuery also to send a post request to the servlet.

    
24.06.2016 / 23:24