Skip to main content

Manejo de Expiracion de Sesion con Jakarta EE

Manejo de Expiración de Sesión con Jakarta EE





Video de demostración



En el archivo web.xml 

agregar

    <error-page>

    <exception-type>javax.faces.application.ViewExpiredException</exception-type>

    <location>/expired.xhtml</location>

</error-page>




agregar

  

    <listener>

  <listener-class>

 com.javscaz.fiscalprinter.security.SecuritySessionListener

  </listener-class>

</listener>


Crear la clase SecuritySessionListener.java

Para manejar la creación y destrucción de sesiones

import com.avbravo.jmoordb.configuration.JmoordbContext;

import com.avbravo.jmoordbutils.JsfUtil;

import java.io.Serializable;

import java.util.Date;

import javax.servlet.http.HttpSession;

import javax.servlet.http.HttpSessionEvent;

import javax.servlet.http.HttpSessionListener;

import org.primefaces.PrimeFaces;


/**

 *

 * @author avbravo

 */

public class SecuritySessionListener implements HttpSessionListener, Serializable {


    @Override

    public void sessionCreated(HttpSessionEvent se) {

        System.out.println("Session created : " + se.getSession().getId() + " at " + new Date());


    }


    @Override

    public void sessionDestroyed(HttpSessionEvent se) {

        HttpSession session = se.getSession();

           System.out.println("session destroyed :" + session.getId() + " Logging out user... at  " + new Date());


    }

}
























Crear la pagina expired.xhtml







<?xml version='1.0' encoding='UTF-8' ?>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"

      xmlns:h="http://java.sun.com/jsf/html"

      xmlns:f="http://java.sun.com/jsf/core"

      xmlns:b="http://bootsfaces.net/ui"

      xmlns:p="http://primefaces.org/ui"

      xmlns:jmoordbjsf="http://jmoordbjsf.com/taglib">

    <h:head> 

        <title>#{msg['application.title']}</title>

        <meta name="author" content="Aristides Villarreal"></meta>

        <style type="text/css">

            .form-signin {

                margin: 0 auto;

                max-width: 330px;

                padding: 15px;

            }

        </style>

        <f:facet name="first">

            <f:view locale="#{jmoordbLanguajes.locale !=null?jmoordbLanguajes.locale:'es'}"></f:view>

            <f:loadBundle basename="com.properties.messages" var="msg" />

            <f:loadBundle basename="com.jmoordbutils.properties.application" var="app" />


        </f:facet>

        <meta http-equiv="refresh" content="15;url=./login.xhtml"/>


    </h:head>

    <h:body style="padding-top: 60px; background-color: #000000">


        <h:form styleClass="form-signin" prependId="false" id="form">


            <h2 class="form-signin-heading"></h2>


           <h1 style="color:white">Sesion expirada</h1>


            <p style="color:white"> Para proteger su seguridad </p>

            <p>Sera redireccionado a la pagina de autentificación</p>


            <p style="color:white"> Espere unos segundos...</p>

            <a href="./login.xhtml"> o de Clic aqui para ir al Login</a>

        </h:form>


    </h:body>

</html>










Pagina login.xhtml

en el login agregar en el header

<meta http-equiv="refresh" content="#{facesContext.externalContext.sessionMaxInactiveInterval};url=#{request.contextPath}/#{loginController.expired()}"/>



Quedaria


<?xml version='1.0' encoding='UTF-8' ?>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"

      xmlns:h="http://java.sun.com/jsf/html"

      xmlns:f="http://java.sun.com/jsf/core"

      xmlns:b="http://bootsfaces.net/ui"

      xmlns:p="http://primefaces.org/ui"

      xmlns:jmoordbjsf="http://jmoordbjsf.com/taglib">

    <h:head> 

        <title>#{msg['application.title']}</title>

        <meta name="author" content="Aristides Villarreal"></meta>

        <style type="text/css">

            .form-signin {

                margin: 0 auto;

                max-width: 330px;

                padding: 15px;

            }

        </style>

        <f:facet name="first">

            <f:view locale="#{jmoordbLanguajes.locale !=null?jmoordbLanguajes.locale:'es'}"></f:view>

            <f:loadBundle basename="com.properties.messages" var="msg" />

            <f:loadBundle basename="com.jmoordbutils.properties.application" var="app" />


        </f:facet>

<meta http-equiv="refresh" content="#{facesContext.externalContext.sessionMaxInactiveInterval};url=#{request.contextPath}/#{loginController.expired()}"/>

    </h:head>

    <h:body style="padding-top: 60px; background-color: lightslategray">

        <jmoordbjsf:ajaxstatus text="Verificando credenciales"/>

        

        <b:container fluid="true"> 

            <h:form styleClass="form-signin" prependId="false" id="form">


       

                <p:messages id="growl" closable="true"  />

                <h2 class="form-signin-heading"><p:outputLabel value="#{msg['application.title']}" style="color: white"/></h2>



                <jmoordbjsf:login

                    id="username"

                    fieldusername="#{loginController.username}"

                    labelusername="#{app['login.username']}"

                    fieldpassword="#{loginController.password}"

                    dologin="#{loginController.doLogin()}"

                    showone="false"

                    idone="rol"


                    />



                <p:outputLabel value="#{msg['application.version']}" style="color: white"/>



            </h:form>

        </b:container>

    </h:body>

</html>












Template.xhtml

En la plantilla para que se habilite en todas las páginas agregamos


<meta http-equiv="refresh" content="#{facesContext.externalContext.sessionMaxInactiveInterval};url=#{request.contextPath}/#{loginController.expired()}"/>


Quedaria

<?xml version='1.0' encoding='UTF-8' ?>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"

      xmlns:h="http://java.sun.com/jsf/html"

      xmlns:f="http://java.sun.com/jsf/core"

      xmlns:b="http://bootsfaces.net/ui"

      xmlns:ui="http://java.sun.com/jsf/facelets"


      xmlns:jmoordbjsf="http://jmoordbjsf.com/taglib"

      xmlns:p="http://primefaces.org/ui">

    <h:head>

        <f:facet name="first">

            <f:view locale="#{jmoordbLanguajes.locale !=null?jmoordbLanguajes.locale:'es'}"></f:view>

            <f:loadBundle basename="com.properties.messages" var="msg" />

            <f:loadBundle basename="com.jmoordbutils.properties.application" var="app" />


        </f:facet>

        <title>#{msg['application.shorttitle']}</title>

        <meta name="author" content="Aristides Villarreal" />

        <meta name="description" content="BootsFaces, a powerful JSF framework that takes the best from Bootstrap and jQuery UI to let develop well-designed state-of-the-art next-gen Front-end Enterprise Applications fast and easy supporting HTML5." />

        <meta name="KEYWORDS" content="jsf, bootstrap, framework, java, enterprise, server, faces, jquery, usability, next-gen, web, html5, easy, modern, well-designed, website, state-of-the-art" />

        <meta name="robots" content="index, follow" />


<meta http-equiv="refresh" content="#{facesContext.externalContext.sessionMaxInactiveInterval};url=#{request.contextPath}/#{loginController.expired()}"/>

        <style type="text/css">


            .ui-growl {


                right: 10%;

                top: 20%;

            }

        </style>

        <jmoordbjsf:metatemplate/>

        <jmoordbjsf:csstemplate/>

        <style>.tooltip-inner {

                max-width: 350px;

                /* If max-width does not work, try using width instead */

                width: 350px; 

            }</style>


     


        <script name="jquery/jquery.js" library="primefaces" target="head" ></script>

    </h:head>

    <h:body style="padding-top: 85px;padding-bottom: 85px;" >


        <jmoordbjsf:jstemplate/>

       


        <ui:insert name="nbtop">


            <ui:include src="/layout/top.xhtml"/>

        </ui:insert>



        <b:container fluid="true">

            <b:row>

                <b:column medium-screen="2" hidden="tiny-screen,small-screen" style-class="site-navigation">

                    <ui:include src="left.xhtml" />

                </b:column>

                <b:column medium-screen="9">

                    <ui:insert name="content"/>

                </b:column>

                <b:column medium-screen="1"  hidden="tiny-screen,small-screen">

                    <div style="position:fixed;top:118px" class="internal-navigation">

                        <ui:insert name="content-navigator"/>

                    </div>

                </b:column>

            </b:row>

        </b:container>


        <ui:insert name="nbtop">

            <ui:include src="/layout/footer.xhtml"/>

        </ui:insert>

        


    </h:body>

</html>






En el LoginController.java


Crear el método expired() que devuelve el path a la pagina expired.xhtml


     // <editor-fold defaultstate="collapsed" desc="String expired()">

     

     public String expired(){


        return "faces/expired.xhtml?faces-redirect=true";

     }// </editor-fold>




Comments

Popular posts from this blog

Cambiando el estado de un checkbox

Cambiando el Estado de un CheckBox Algunas veces deseamos controlar el estado de un checkbox o cambiarlo segùn determinadas condiciones. Pasos: 1. Creamos un proyecto Web. 2. En el diseñador agregamos un checkbox y dos botones. * Dar click derecho en el checkbox y luego seleccionar Add Binding Attribute, para agregar los atributos al checkbox, de manera que los podamos usar en nuestro código. Generando automáticamente private Checkbox checkbox1 = new Checkbox(); public Checkbox getCheckbox1() { return checkbox1; } public void setCheckbox1(Checkbox c) { this.checkbox1 = c; } 3.Damos click derecho en el botón Habilitar, y seleccionamos Edit Action Event Handler. A continuación, agregamos el código: this.checkbox1.setSelected(true);, el método setSelected con valor true, marca el checkbox como seleccionado, y un valor de false, quita la marca. public String button1_action() { // TODO: Process the action. Return value is a navigation //

Corregir el error el archivo de manifiesto en proyectos maven

Corregir el error en el archivo de manifiesto en proyectos maven Si creamos un proyecto maven con NetBeans e intentamos ejecutarlo encontraríamos el siguiente error Agregamos el plugin   <artifactId>maven-jar-plugin</artifactId>  <plugin>                 <groupId>org.apache.maven.plugins</groupId>                 <artifactId>maven-jar-plugin</artifactId>                 <version>2.4</version>                 <configuration>                     <archive>                         <manifest>                             <mainClass>org.javscaz.maven1.App</mainClass>                         </manifest>                                           </archive>                 </configuration>             </plugin> Luego al construir el proyecto con dependencias, podemos ejecutar el .jar

Tutorial básico de aplicaciones Web con NetBeans parte 1

NetBeans ofrece un excelente soporte para el desarrollo de aplicaciones Web, en esta ocasión lo haremos utilizando el Framework Java Server Faces 2.0. En el Menu Seleccionamos Nuevo->Proyecto y luego en Categorias Java Web y en tipo de Proyectos Web  Application indicamos el nombre del proyecto Seleccinamos el servidor Web, usamos GlassFish ya que este soporta EJB3.0 y JSF 2.0 Framework Java Server Faces El IDE genera el esquelto del proyecto Web Pages   almacenamos las paginas .html, xhtml, jsf, los archivos de recursos, los scripts .js, imagenes Source Packages    Son las clases Java  Test Packages    Son las clases que usamos para los Test Libraries     Tenemos las bibliotecas de Java y GlassFish necesarias para ejecutar la aplicación Web. Test Libraries     Están las bibliotecas usadas para los test  Configuration Files    Archivos de configuración de la aplicación. Ejecutamos la aplicación  Esperamos que se inicie GlassFish y se cargue la aplicación Este se