JSF Authentication Login Logout Database Example

2y ago
337 Views
66 Downloads
263.80 KB
24 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Axel Lin
Transcription

21/04/2017JSF Authentication Login Logout Database Example JournalDevFree eBook: Java Design Patterns (130 Pages) Download Now! Your email address please.SEND ME NOW!JAVA TUTORIAL#INDEX POSTS#INTERVIEW QUESTIONSRESOURCESSTOREHOME » JSF » JSF AUTHENTICATION LOGIN LOGOUT DATABASE EXAMPLEJSF Authentication Login Logout DatabaseExampleJULY 10, 2016 BY PANKAJ — 55 COMMENTSAuthentication mechanism allows users to have secure access to the application by validating theusername and password. We will be using JSF view for login, DAO object ,HttpSession for sessionmanagement, JSF managed bean and mysql database.Lets now look in detail as how to create a JSF login logout authentication mechanism in JSF application.Step 1: Create the table Users in mysql database asCREATE TABLE Users(uid int(20) NOT NULL AUTO INCREMENT,uname VARCHAR(60) NOT NULL,password VARCHAR(60) NOT NULL,PRIMARY KEY(uid));Here we create user table with uid as the primary key, username and password elds with not nullconstraints.Step 2: Insert data into the table Users as;INSERT INTO Users VALUES(1,'adam','adam');Before we move on to our project related code, below image shows the project structure in Eclipse. Justcreate a dynamic web project and convert it to maven to get the project stub and then keep on addingdi erent components.http://www.journaldev.com/7252/jsf authentication login logout database example1/24

21/04/2017JSF Authentication Login Logout Database Example JournalDevFree eBook: Java Design Patterns (130 Pages) Download Now! Your email address please.SEND ME NOW!Step 3: Create the JSF login page login.xhtml as; ?xml version '1.0' encoding 'UTF‐8' ? !DOCTYPE html PUBLIC "‐//W3C//DTD XHTML 1.0 xhtml1‐transitional.dtd" html xmlns "http://www.w3.org/1999/xhtml"xmlns:h "http://java.sun.com/jsf/html" h:head title login /title /h:head h:body h:form h3 JSF Login Logout /h3 h:outputText value "Username" / h:inputText id "username" value "#{login.user}" /h:inputText h:message for "username" /h:message br /br br /br h:outputText value "Password" / h:inputSecret id "password" value "#{login.pwd}" /h:inputSecret h:message for "password" /h:message br /br br /br h:commandButton action "#{login.validateUsernamePassword}"value "Login" /h:commandButton /h:form /h:body /html http://www.journaldev.com/7252/jsf authentication login logout database example2/24

21/04/2017JSF Authentication Login Logout Database Example JournalDevHere we are creating a JSFloginviewJavapagewith usernameandpasswordeldsNow!and set values for theseFreeeBook:DesignPatterns (130Pages)Downloadelds through the login managed bean. We invoke the validateUsernamePassword method on click of Your email address please.Login button to validate the username and password.SEND ME NOW!Step 4: Create the managed bean Login.java as;package com.journaldev.jsf.beans;import java.io.Serializable;import javax.faces.application.FacesMessage;import javax.faces.bean.ManagedBean;import javax.faces.bean.SessionScoped;import javax.faces.context.FacesContext;import javax.servlet.http.HttpSession;import com.journaldev.jsf.dao.LoginDAO;import SessionScopedpublic class Login implements Serializable {private static final long serialVersionUID 1094801825228386363L;private String pwd;private String msg;private String user;public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd pwd;}public String getMsg() {return msg;}We declare three String variables user, pwd and msg for username, password and error message eldsalong with the getter and setter methods. We write a method validateUsernamePassword() for validatingthe username and password eld by invoking the LoginDAO class to fetch the username and password fromthe database and compare it with the front end values passed. If the username and password does notmatch an error message is displayed as “Incorrect username and password” . Also a logout() method iswritten to perform logout by invalidating HTTPSession attached.http://www.journaldev.com/7252/jsf authentication login logout database example3/24

21/04/2017JSF Authentication Login Logout Database Example JournalDevStep 5: Now create the LoginDAOjavaclassas below.NotethatdatabaseoperationsFree eBook:JavaDesignPatterns(130Pages)DownloadNow! code is not optimized to be used in a real project, I wrote it as quickly as possible because the idea is to learn authentication in JSFYour email address please.applications.SEND ME NOW!package com.journaldev.jsf.dao;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import com.journaldev.jsf.util.DataConnect;public class LoginDAO {public static boolean validate(String user, String password) {Connection con null;PreparedStatement ps null;try {con DataConnect.getConnection();ps con.prepareStatement("Select uname, password from Userswhere uname ? and password ?");ps.setString(1, user);ps.setString(2, password);ResultSet rs ps.executeQuery();if (rs.next()) {//result found, means valid inputsreturn true;}} catch (SQLException ex) {System.out.println("Login error ‐‐ " ex.getMessage());return false;} finally {DataConnect.close(con);}return false;In the validate() method we rst establish connection to the database by invoking the DataConnect classgetConnection method. We use PreparedStatement to build the query to fetch the data from the databasewith the user entered values. If we get any data in result set, it means input is valid and we return true, elsefalse.Step 6: Create the DataConnect.java class as;package 7252/jsf authentication login logout database example4/24

21/04/2017JSF Authentication Login Logout Database Example JournalDevimport java.sql.Connection;Free eBook: Java Design Patterns (130 Pages) Download Now!import java.sql.DriverManager; Your email address please.public class DataConnect {SEND ME NOW!public static Connection getConnection() {try {Class.forName("com.mysql.jdbc.Driver");Connection con t:3306/cardb", "pankaj","pankaj123");return con;} catch (Exception ex) {System.out.println("Database.getConnection() Error ‐‐ " ex.getMessage());return null;}}public static void close(Connection con) {try {con.close();} catch (Exception ex) {}}}We load the JDBC driver using Class.forName method and use DriverManager.getConnection methodpassing the url, username and password to connect to the database.Step 7: Create SessionUtils.java to obtain and manage session related user information.package com.journaldev.jsf.beans;import javax.faces.context.FacesContext;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;public class SessionUtils {public static HttpSession getSession() {return (HttpSession) xt().getSession(false);}public static HttpServletRequest getRequest() {return (HttpServletRequest) sf authentication login logout database example5/24

21/04/2017JSF Authentication Login Logout Database Example JournalDev}Free eBook: Java Design Patterns (130 Pages) Download Now! Your email address please.public static String getUserName() {ME NOW! FacesContext.getCurrentInstance()HttpSession session false);return c static String getUserId() {HttpSession session getSession();if (session ! null)return (String) session.getAttribute("userid");elsereturn null;}}Here we obtain a session for each user logged through the getUserId method thereby associating a sessionid to a particular user id.Step 8: Create the authorization lter class as;package com.journaldev.jsf.filter;import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.annotation.WebFilter;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import me "AuthFilter", urlPatterns { "*.xhtml" })public class AuthorizationFilter implements Filter {public AuthorizationFilter() {}@Overridepublic void init(FilterConfig filterConfig) throws ServletException {}@Overridehttp://www.journaldev.com/7252/jsf authentication login logout database example6/24

21/04/2017JSF Authentication Login Logout Database Example JournalDevpublic void eBook: Java Design Patterns(130 Pages)Download Now! response,FilterChain chain) throws IOException, ServletException { Your email address please.try {SEND ME NOW!HttpServletRequest reqt (HttpServletRequest) request;HttpServletResponse resp (HttpServletResponse) response;HttpSession ses reqt.getSession(false);We implement the standard lter class by overriding the destroy and doFilter methods. In the doFiltermethod we will redirect user to login page if he tries to access other page without logging in.Step 9: Create admin.xhtml as; ?xml version '1.0' encoding 'UTF‐8' ? !DOCTYPE html PUBLIC "‐//W3C//DTD XHTML 1.0 xhtml1‐transitional.dtd" html xmlns "http://www.w3.org/1999/xhtml"xmlns:h "http://java.sun.com/jsf/html" h:head title Facelet Title /title /h:head h:body h:form p Welcome #{login.user} /p h:commandLink action "#{login.logout}" value "Logout" /h:commandLink /h:form /h:body /html This page is rendered when the user logs in successfully. Logout functionality is implemented by calling thelogout method of the Login.java class.Step 10: Create faces‐config.xml le as; ?xml version '1.0' encoding 'UTF‐8'? faces‐config version "2.2" xmlns "http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi chemaLocation p.org/xml/ns/javaee/web‐facesconfig 2 2.xsd" navigation‐rule from‐view‐id /login.xhtml /from‐view‐id navigation‐case from‐outcome admin /from‐outcome to‐view‐id /admin.xhtml /to‐view‐id /navigation‐case /navigation‐rule http://www.journaldev.com/7252/jsf authentication login logout database example7/24

21/04/2017JSF Authentication Login Logout Database Example JournalDevFree eBook: Java Design Patterns (130 Pages) Download Now! /faces‐config Your email address please.Once done with all the steps speci ed above runtheMEapplicationand see the following output in theSENDNOW!browser.Login PageAuthentication Error PageLogin Success Pagehttp://www.journaldev.com/7252/jsf authentication login logout database example8/24

21/04/2017JSF Authentication Login Logout Database Example JournalDevFree eBook: Java Design Patterns (130 Pages) Download Now! Your email address please.SEND ME NOW!Accessing admin.xhtml while logged inJust click on the Logout link and the session will be invalidated, after that try to access admin.xhtml pageand you will be redirected to the login page, go ahead and download the project from below link and try itout.Download JSF Authentication Login Logout Project9026 downloadsFILED UNDER: JAVA EE, JSFAbout Pankajhttp://www.journaldev.com/7252/jsf authentication login logout database example9/24

21/04/2017JSF Authentication Login Logout Database Example JournalDevIf you have come this far, it meansthat youwhatyou arereading.not reachFree eBook:JavalikedDesignPatterns(130Pages) WhyDownloadNow! little more and connectwith me directly on Google Plus, Facebook or Twitter. I would love to hear your thoughts and opinions on my Your email address please.articles directly.Recently I started creating video tutorials too, so docheckmy videos on Youtube.SENDME outNOW!« 5 Advanced Java Books for Experienced ProgrammersJSF Interview Questions And Answers »Commentsshekar saysAPRIL 17, 2017 AT 4:43 AMGreat examplesReplydoppioB saysMARCH 21, 2017 AT 7:12 AMHi, i took some classes of your code and when I tried to login, it send me that error:Etat HTTP 500 – java.lang.NullPointerExceptionThe error pointed to “session.setAttribute (“key”, value), I thought it came from my DBB but after longresearchs I just TRY to change the return value in the method HttpSession getSession() and I put. “true”instead of “false” and I don’t know why I could access to the next page after login. I would like to knowwhyReplyryan saysFEBRUARY 16, 2017 AT 3:57 AMworks great but when i log out i can still go back using the back navigation button .How can i disable itReplyRod Wilson saysDECEMBER 19, 2016 AT 6:46 AMThe warning messages will not render. An error message of “INFO: WARNING: FacesMessage(s) havebeen enqueued, but may not have been displayed.” Any ideas as to why this is occurring?http://www.journaldev.com/7252/jsf authentication login logout database example10/24

21/04/2017JSF Authentication Login Logout Database Example JournalDevReplyFree eBook: Java Design Patterns (130 Pages) Download Now! Your email address please.SEND ME NOW!Juan Lamata Feliz saysDECEMBER 13, 2016 AT 10:12 AMgracias por el aporte 3ReplyWillian saysDECEMBER 13, 2016 AT 6:41 AMThis is working for multiple users?Replymhashimi saysNOVEMBER 30, 2016 AT 7:13 PMthis session can be used for multiple users or one, per machine/ip?help please, a feedback would be niceReplyAisha saysNOVEMBER 25, 2016 AT 7:40 AMexcuse me can you help me to do online nursery system by jsp it’s important to nish it in this weekend.please if you can send to meReplyHans Newton saysNOVEMBER 13, 2016 AT 11:19 AMIt works perfect.Thanks!http://www.journaldev.com/7252/jsf authentication login logout database example11/24

21/04/2017JSF Authentication Login Logout Database Example JournalDevReplyFree eBook: Java Design Patterns (130 Pages) Download Now! Your email address please.Ayoub saysSEND ME NOW!FEBRUARY 1, 2017 AT 9:05 AMHi , can you send me the Code !!Replyraed saysOCTOBER 29, 2016 AT 2:45 PMHello Pankaj,could you please tell us or better show us with Code how can i check if the Session Timeout is happenandthe User hit a button to send a request how can we manage this situation to prevent an ExceptionbecauseTimeout of the Session ?thanks RaedReplyyosser saysSEPTEMBER 30, 2016 AT 3:54 PMthank uReplyHrvoje saysAUGUST 9, 2016 AT 7:36 AMI have a problem with this code, everything works great bu if I try to log in multiple users and then logout only one every users session is killed ? Quite a problem or just me ?ReplyFabio sayshttp://www.journaldev.com/7252/jsf authentication login logout database example12/24

21/04/2017JSF Authentication Login Logout Database Example JournalDevSEPTEMBER 22, 2016 AT 2:37 PMFree eBook: Java Design Patterns (130 Pages) Download Now! Your email addressYeah.! please.I have the same problem this method kind accept only one Login at time. How to solve it?ReplySEND ME NOW!Tavakkaljon Dehqonov saysJUNE 23, 2016 AT 9:15 PMHELO Pankaj.I am using this proekt.How can download package com.journaldevReplyGrzesiek saysJUNE 12, 2016 AT 1:25 AMOnHttpSession session SessionBean.getSession();i’ve error: “error: cannot nd symbol”Can you help me?ReplyPankaj saysJUNE 12, 2016 AT 7:10 AMActually I changed the class name of SpringBean to SpringUtils and forgot to update the code inLogin.java class. I have updated the code in the post as well as project zip le. You can download theproject now, it will work ne.ReplyChristian saysJUNE 8, 2016 AT 4:38 AMjava.lang.NullPointerException - You have to add the mysql connector library.It was perfect! That’s work ne, thank you.http://www.journaldev.com/7252/jsf authentication login logout database example13/24

21/04/2017JSF Authentication Login Logout Database Example JournalDevReplyFree eBook: Java Design Patterns (130 Pages) Download Now! Your email address please.SEND ME NOW!edward saysMAY 23, 2016 AT 3:36 AMthe app seems great though its throwing an exception joe saysMAY 15, 2016 AT 1:23 AMPerfect! That’s work ne, thank youReplyVitor Da Costa saysMAY 3, 2016 AT 11:49 PMThanks a lot )ReplySamy saysAPRIL 20, 2016 AT 8:59 AMAn Error Occurred:java.lang.NullPointerExceptionReplyravi saysAPRIL 3, 2016 AT 10:19 AMDear Pankaj,Thanks a lot. The code you provided helped a lot with my project. One question though, how would youexclude a page from authentication. For example, if you want the user to see the home page rst, whichhttp://www.journaldev.com/7252/jsf authentication login logout database example14/24

21/04/2017JSF Authentication Login Logout Database Example JournalDevshould have a link to FreelogineBook:page. JavaAny Designsuggestionswouldbe immenselyappreciated.Patterns(130 Pages)DownloadNow!Ravi Your email address please.ReplySEND ME NOW!Mustafa Darcan saysMARCH 1, 2016 AT 1:23 PMI get an error of java.lang.NullPointerException .How can I x this ?Replyzongi saysOCTOBER 4, 2016 AT 3:03 AMthis question Sound likeThe Project don t want run, how to x itReplyMartin Zwernemann saysFEBRUARY 10, 2016 AT 9:40 AMWithout any entries to web.xml the AuthorizationFilter is never used. Minimum is to include it in web.xmlin follwing manner (replace xxxx with your package name):AuthorizationFilterxxxx. lter.AuthorizationFilterThis Filter authorizes user access to application.error page/error/error.xhtmlReplyMartin Zwernemann saysFEBRUARY 10, 2016 AT 9:44 AMSorry, the xml was eaten by your server. I replaced the XML-marks with asterisks:* lter** lter-name*AuthorizationFilter*/ lter-name*http://www.journaldev.com/7252/jsf authentication login logout database example15/24

21/04/2017JSF Authentication Login Logout Database Example JournalDev* lter-class*xxx. Freelter.AuthorizationFilter*/lter-class*eBook: Java Design Patterns(130 Pages) Download Now!*description*This Filter authorizes user access to application.*/description* Your email address please.*init-param**param-name*error page*/param-name*SEND ME am-value**/init-param**/ lter*ReplyGholamali Irani saysJANUARY 11, 2016 AT 1:13 PMThanks a lot, so helpfulwhat is JSF managed bean behavior with static method?Is it safe with multiple online user? (con ict sessions or not !!)ReplyAlessandro Mattiuzzi saysDECEMBER 15, 2015 AT 5:17 AMReally good my friend. Great exampleReplyKrzysiek saysDECEMBER 4, 2015 AT 10:04 AMThe class name “LoginDAO” is misleading as this it not a DAO object at all, it’s just a simple class whichcontain one (static) method.ReplyAskat saysOCTOBER 27, 2015 AT 11:41 PMlet’s say in the Users table is a eld department , how to map this eld to the JSF page?http://www.journaldev.com/7252/jsf authentication login logout database example16/24

21/04/2017JSF Authentication Login Logout Database Example JournalDevReplyFree eBook: Java Design Patterns (130 Pages) Download Now! Your email address please.SEND ME NOW!alfredo fernandes saysOCTOBER 10, 2015 AT 6:47 AMvery good example.why after logout if you press back button in browser in not invalidated showing the admin page with thename of the logged user?thank you for a reply.ReplyBurakErk saysAPRIL 18, 2016 AT 4:19 AMI think this is a good question. We sould look for that.ReplyBurakErk saysAPRIL 18, 2016 AT 4:23 AMpublic String logout() {HttpSession session SessionBean.getSession();user “”;pwd “”;session.invalidate();return “login”;}This sould work.ReplyBurakErk saysAPRIL 20, 2016 AT 4:08 AMUse this codefor redirection.return “Login.xhtml?faces-redirect true”;————–return “login”;This code is just forwarding the page. And that situation user can click browser’s “backbutton” and see the page which allready logouted.Replyhttp:

JSF Authentication Login Logout Database Example JULY 10, 2016 BY PANKAJ — 55 COMMENTS Authentication mechanism allows users to have secure access to the application by validating the username and password. We will be using JSF view for login, DAO object ,HttpSession for session manageme

Related Documents:

JSF has nothing to do with JSP per se. JSF works with JSP through a JSP tag library bridge. However, the life cycle of JSF is very different from the life cycle of JSP. Facelets fits JSF much better than JSP because Facelets was designed with JSF in mind, whereas integrating JSF and JSP has

JSF includes a set of predefined UI components, an event-driven programming model, and the ability to add third-party components. JSF is designed to be extensible, easy to use, and toolable. This refcard describes the JSF development process, standard JSF tags, the JSF expressi

Building JavaServer Faces Applications 7 JSF – A Web Framework JSR 127 – JSF specification v1.1 JSF 1.2 in progress (JSR 252) JSP 2.1 (JSR 245) will align with JSF JSF spec lead was the Struts architect JavaServer Faces technology simplifies building user interfaces for JavaServer

Broken Authentication - CAPTCHA Bypassing Broken Authentication - Forgotten Function Broken Authentication - Insecure Login Forms Broken Authentication - Logout Management Broken Authentication - Password Attacks Broken Authentication - Weak Passwords Session Management - Admin

2.2 User Logout Command for Radius Subscriber Logout The Portal Page web server can send this command to instruct the NSE to logout the subscriber. This is the XML command with the following DTD: ?xml version "1.0" encoding "UTF-8"? !-- DTD defines Logout command sent to NSE -- !ELEMENT SUB_MAC_ADDR (#PCDATA) !ELEMENT SUB_USER_NAME (# .

Barracuda Spam Firewall: Login and logout activity: All logs generated by Barracuda spam virus firewall when login or logout is happened on barracuda spam firewall web interface. Barracuda Spam Filter: User login success: This category provides information related to user login success into barracuda spam filter.

JSF control boards JSF changes holding tank Individual JSF design changes S s a Study-specific archives NIMA, DTRA, NRO, etc. Program Offices Intel Centers JSFPO, JFCOM, DoD, etc. Threat C&P information Operational context information Natural environment & infrastructure C&P information Blue s

2 Annual Book of ASTM Standards, Vol 06.03. 3 Annual Book of ASTM Standards, Vol 14.03. 4 Reagent Chemicals, American Chemical Society Specifications, American Chemical Society, Washington, DC. For suggestions on the testing of reagents not listed by the American Chemical Society, see Analar Standards for Laboratory Chemicals, BDH Ltd., Poole, Dorset, U.K., and the United States Pharmacopeia .