183,443` Total Views

67 comments

  • Hallo Sir,

    I tried the code. Somehow I can still access the /public/home.xhtml without login.

    Regards

    Daniel

    • You can access login.xhtml and any other pages under /public directory without login. But you can’t access other directory or any other pages under your web directory. This is the logic.

  • Hello. Can you help me, please? I tried to do like this and when I click the Login button, I was redirected to the same page. But I see the content of this page at a first time. Seems like this page is standard login page, and I confused from where it come. I have a mind that it is due to the Realm. You can find the screenshot there http://minus.com/lcTW68sBf05U1. Please help me resolve this issue.

    • No more needed. I’ve fixed :) Thank you very much for your tutorial! It is very helpful!

      • hello, sir. I have one more question. The login process is successful and all is going OK. However, when I click “refresh” button in the browser or any other link, my http session is over and i need to login again. So, the problem is that session is over when the page refreshes. How can I prevent this? Many thanks.

        • Actually, after successful login, have a close look at your browser’s url which is still login.xhtml though you have redirected to home.xhtml. That’s why when you refresh the page it goes to login.xhtml and you thought the session has been expired but it does’t. But this will happen only for the very first time after login. If you browse any other pages after login this will not happen.

          • To solve this you need to update your navigation-rule with redirect like the following

            <navigation-rule>
                    <from-view-id>/login.xhtml</from-view-id>
                    <navigation-case>
                        <from-outcome>home</from-outcome>
                        <to-view-id>/home.xhtml</to-view-id>
                    <redirect>     
                    </redirect>
                    </navigation-case>
             </navigation-rule>
            

            For more information about this visit the link

          • Fact is that i’ve implemented the redirection using the FacesContext.getCurrentInstance().getExternalContext().redirect(url). So after successful login i have a correct url (as for me). Also I have implemented the verification (logged in user or not) using the “” tag. If user logged in, the “Logout” button would be shown. Otherwise – Login button. Now, after successful login, the “Logout” button shows and it is correct. And after I press refresh button, the “Login” button shows (session has been closed?). Could you suggest something in this case?

          • Sorry, the tag that I meant is c:if

  • i tried the code and it is running well..what i want to do is,if anyone has logged in, he gets the home page but if he opens any other tab in the same browser he should get home page instead of login page..can anyone help me with this??

    • can anybody answer me??

      • It generally does that, if someone logged on then he can browse any page even in new tab. I am not sure what you exactly wanted to know.

        • i will explain it more clearly by taking an example.if i login into my gmail account and after logged in when i open the login link in new tab it does not displays the login page instead it shows the logged in account…that is exactly what i want in my application…

        • after login it happens that i can access any page in new tab also…but what i want to implement is, once a user is logged in and without logout if he tries to login again he should not get the login page, he should get the logged in pages….

        • thanks…i got it…

          • Can you share with us? Thanks.

          • i just made some changes in filter class….

            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
                     try {
             
               // check whether session variable is set
              HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse res = (HttpServletResponse) response;
            HttpSession ses = req.getSession(true);
            String reqURI = req.getRequestURI();
            //user is logged in. Login again will redirect  him to home page directly at every attempt.
            if(ses.getAttribute("username")!=null &amp;&amp; reqURI.contains("login.xhtml"))
                      {
             res.sendRedirect(req.getContextPath() + "/home.xhtml");
                      }
            //  allow user to proccede if url is login.xhtml or user logged in or user is accessing any page in //public folder
                         if ( reqURI.indexOf("/login.xhtml") &gt;= 0 || (ses != null &amp;&amp; ses.getAttribute("username") != null)
                                                   || reqURI.indexOf("/public/") &gt;= 0 || reqURI.contains("javax.faces.resource") )
                                {chain.doFilter(request, response);} 
                         else                   // user didn't log in but asking for a page that is not allowed so take user to login page
                                { res.sendRedirect(req.getContextPath() + "/faces/login.xhtml");}  // Anonymous user. Redirect to login page  
                  }
            
          • how can i implement remember me feature in this login example? can u help me with that…

            • Create two properties with getter and setter like this
              boolean remember;
              String remember1 = “”;

              Now add the following lines after line 52 at LoginBean.java

              FacesContext facesContext = FacesContext.getCurrentInstance();
              // Save the uname and password in a cookie
              Cookie btuser = new Cookie("btuser", uname);
              Cookie btpasswd = new Cookie("btpasswd",password);
              		if(remember == false){
              			remember1 = "false";
              		}
              		else{
              			remember1 = "true";
              		}
              		Cookie btremember = new Cookie("btremember",remember1);
              		btuser.setMaxAge(3600);
              		btpasswd.setMaxAge(3600);		
              ((HttpServletResponse)facesContext.getExternalContext().getResponse()).addCookie(btuser);
              
              ((HttpServletResponse)facesContext.getExternalContext().getResponse()).addCookie(btpasswd);
              
              ((HttpServletResponse)facesContext.getExternalContext().getResponse()).addCookie(btremember);
              

              Now create method and call it from constructor for checking the cookies

              public void checkCookie(){
              	FacesContext facesContext = FacesContext.getCurrentInstance();
              	String cookieName = null;
              	Cookie cookie[] = ((HttpServletRequest)facesContext.getExternalContext().getRequest()).getCookies();
              		if(cookie != null && cookie.length > 0){
              			for(int i = 0; i<cookie.length; i++){
              				cookieName = cookie[i].getName();
              				if(cookieName.equals("btuser")){
              					uname = cookie[i].getValue();
              				}
              				else if(cookieName.equals("btpasswd")){
              					password = cookie[i].getValue();
              				}
              				else if(cookieName.equals("btremember")){
              					remember1 = cookie[i].getValue();
              					if(remember1.equals("false")){
              						remember = false;
              					}
              					else if(remember1.equals("true")){
              						remember = true;
              					}
              				}
              			}
              		}
              		else
              			System.out.println("Cannot find any cookie");
              	}
              

              And also add the following two lines to your view page.

              <h:selectBooleanCheckbox id="remember" value="#{loginBean.remember}" onclick="return check(this);" />
              <h:outputLabel for="remember">Remember Me</h:outputLabel>
              
          • thanks for ur huge support….thank u…

          • i tried for hours but remember me is nt working.after adding the method and updating loginbean it is working as usual…everytime its asking username and password.

            • This code works perfectly for me. Several issues you have to notice.

              1. Your getUname() method

              public String getUname() {
                      if (remember == false) {
                          uname = "";
                          return uname;
                      } else {
                          return uname;
                      }
                  }
              

              2. Your getPassword() method

              public String getPassword() {
                      if (remember == false) {
                          password = "";
                          return password;
                      } else {
                          return password;
                      }
                  }
              

              3. You have to call the checkCookie() method from constructor of your LoginBean.java

              public LoginBean() {
                      checkCookie();
                  }
              

              4. Finally add redisplay attribute to display the cookie password.

              <p:password id="password" value="#{loginBean.password}"  feedback="false" redisplay="true"></p:password>
              
  • Hi,
    I thank you for this tutorial. I tried to test it but when i run the project i get this error “http://localhost:8083/jsfcrud/”.jsfcrud is the name of my project.I will be gratefull for your answer.Thank you again.

  • i tried the code but when i run the project i get the first page login.xhtml without the input fields login and password ,just the output fields

  • great code but when i click logout ,i find my self in the login page but when i clock on previous browser bouton i access direclty to the home page ??? security fail !!!!!!!!!!!
    can u solve us this problem?

    • Add the following lines after line 31 of AuthFilter.java

      res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
      res.setHeader("Pragma", "no-cache"); // HTTP 1.0.
      res.setDateHeader("Expires", 0); // Proxies.
      

      After clicking back button of browser the home page comes from the browser’s cache. So you need to tell the web browser not to cache the restricted page.

      See details here.

  • sir,i want to provide one hyper link for registration in login form but when i click hyper link i’m getting only login form& separately if i will run the registration form then too i got the login form pls help me.

    • Keep your registration form or any other forms(that you want to browse without login) to public folder.

      • sir i have kept in public folder but still same prob is coming.

        • sir pls provide me some solution sir.i have kept all form inside the web content.& if i want to run separately registration form then it return in the login form.if i’m clicking the hyper link in login form it is not open the registration form

          • Your link should look like the following.

            <a href="public/registration.xhtml" rel="nofollow">New User? Register Here!</a>
            
  • sir I have did like that but still i’m not able to go for registration form when i’m clicking the hyper link of registration form in the login form it is not opening the registration form,it is not taking any action my login page is like this..

    login

            
     <a href="registration.xhtml" rel="nofollow">CREATE AN ACCOUNT</a>
    

    pls provide me solution for that sir ASAP.

  • Thanks a lot sir now it work.

  • Wonderful tutorial.But I need help to implement logout logic?

  • Atique Rabbani

    Hello Bari,
    Great Java learning blog. Pls keep going. It will be very useful for all Java learners. You may eventually publish this as an ebook.
    Best Wishes
    Atique Rabbani

  • I tried integrate this code in my application, but unfortunately after authentication success I can not navigate through other pages? What is the solution? pleeeeeze help me ?

    • Can you provide your directory structure?

      • project-name
        —-src (classes java)
        —-library
        —-build
        —-webcontent (xhtml pages)

        • I am not sure, after authentication success why you can not navigate through other pages.
          Anyway, I have provided my NetBeans source code of the project with example of sample navigation after successful login.
          You can download this and also let me know if the problem is solved.

  • Great Example !!

    Many thanks!

  • sureshpathak13

    Hi,
    I am trying to execute this application but getting exception.
    SEVERE: Exception starting filter AuthFilter
    java.lang.ClassNotFoundException: java.filters.AuthFilter
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:532)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:514)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:133)
    at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:256)
    at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:382)
    at org.apache.catalina.core.ApplicationFilterConfig.(ApplicationFilterConfig.java:103)
    at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4650)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5306)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    8 Jul, 2013 1:56:32 AM org.apache.catalina.core.StandardContext startInternal
    SEVERE: Error filterStart

    • Ensure all the listed jars present at your class path.
      1. jsf-api.jar
      2. jsf-impl.jar
      3. jstl.jar
      4. mysql-connector-java-5.1.13-bin.jar
      5. mysql-connector-java-5.1.13-bin.jar
      6. mysql-connector-java-5.1.13-bin.jar

  • At the very beginning, your userinfo table definition creates two fields ‘user’ and ‘pass’, but you use them as ‘username’ and ‘password’ elsewhere–even in the immediate INSERT statement.!!!

  • In faces-config.xml I set a new redirect when a user logout.

    /home.xhtml

    logout
    /logout.xhtml

    But you need to click the button twice to go to the logout page.

    One more question, I will create an administration page, how do you do to only the administrator or group of administrators consult page after login and others failed.

    • For your first problem try this

      <navigation-rule>
              <from-view-id>/login.xhtml</from-view-id>
              <navigation-case>
                  <from-outcome>home</from-outcome>
                  <to-view-id>/home.xhtml</to-view-id>
                  <redirect>     
                  </redirect>
              </navigation-case>
          </navigation-rule>
          <navigation-rule>
              <from-view-id>/home.xhtml</from-view-id>
              <navigation-case>
                  <from-outcome>login</from-outcome>
                  <to-view-id>/login.xhtml</to-view-id>
              </navigation-case>
          </navigation-rule>
      

      The empty redirect tag of first navigation is important.

      For your second problem you can authenticate the administrator(s) by using their role.

  • Excelente tutorial me sirvio de mucho…..
    muchas gracias……

  • could you make me a human resource project that asks first the user the to login first then the admin can add, edit, delete data about the existing entry. thanks a lot. this should help me.

  • greet post thanks so much
    but i have a question how you view VO objects after getting it from DAO i mean this is a nested dataTable right?
    i have a problem with it and i cant figure out how to solve it

  • Salam, please help me, I am a student and this is my first project in jsf and I’m leads to develop an application, I could not import this project in my eclipse
    merci d”avance ^_^

  • hi, beautiful code I have a problem trying to call a page -in-class system home.xhmtl nobody available ….

    I am attaching the code

    Security SMS Code

    I know how to help ? thanks

  • Hey Sir Many thanks for the Project but when i was trying to run the SQL command i kept getting error at the last line that is (INSERT INTO `userinfo` (`id`,`username`,`password`) VALUES
    (1,’admin’,’123′);) the error kept saying check yuor manual…….., and also when i tried the login page the h form( xmlns:h=”http://java.sun.com/jsf/html”) keeps saying error please tell me what i have done wrong??

  • Very helpfull tutorial sir.I am new in jsf .It helped me a lot for applying session in my project.

  • Benjamin Jimenez

    Great project but I have a doubt. Is there a way that if I access by, let’s say, “http://localhost:8080/LoginApp/”(this is my project folder) in a new tab, after I logged in, I end up in home.xhtml and not in login.xhtml?
    I know you already fixed the problem where after loggin in you go to “http://localhost:8080/LoginApp/login.xhtml” and end up in home.xhtml but It doesn’t seems to work when you access directly by the main folder “http://localhost:8080/LoginApp/”

  • Hello, Sir. Can you tell me the MySql query for deleting a record from a table after a particular time period,like 3 months. Actually, I’m building a small web app of selling products onl9 and I want a product info to be deleted automatically after 3 months,

  • hello, thanks 4 da example, but.. in what moment the filter is called? thanks

  • It works in my project, very good post, thx !!!

  • Hi sir,

    I have problem once i logout from application and hit back button it show previous page information it is one of the security concern please suggest me on that

  • Hi everybody!
    I got a little problem with logout. when i login , if i do some actions before logout, the logout doesnt work perfectly. when i click on previous button on my browser it returns on the page which i came from.
    Please help me.

    Excuse my bad english.

  • In loginbean.java, I can’t use Util.getSession in Eclipse. I try to find some libraries to solve the problem! But I cannot! Do you have any advice?

  • Sir..thank you so much..I learn a lot from your blogs..God Bless..May you continue in sharing your knowledge to us…

  • Sir Thanks for the great tutorial. But I have a one problem. When I click login button, Nothing happens. and I inserted FacesContext.getCurrentInsctance().addMessage to check the back end. It works fine. But it seems like navigation rule is not working. My code is

    index.xhtml

    smartdealer
    smart_dealer.xhtml

    Could you kindly check the what is the problem?

  • Hello Sir,
    I been searching for this kind of sample code. I’m currently developing a Faculty Online Evaluation with the Primefaces framework.

    It works!

    Thank you so much for sharing.

  • Thanks! Your tutorial is very helpful. I modified the code a little bit to adapt it to my application, but this saved me a lot of time.

Leave a Reply

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


one × = 5