-
-
Save pjomcsJAVA/ffabc2051a3a6f0231ba63d5051cba2b to your computer and use it in GitHub Desktop.
Primefaces Login Example with Database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 javax.servlet.http.HttpSession; | |
@WebFilter(filterName = "AuthFilter", urlPatterns = {"*.xhtml"}) | |
public class AuthFilter implements Filter { | |
public AuthFilter() { | |
} | |
@Override | |
public void init(FilterConfig filterConfig) throws ServletException { | |
} | |
@Override | |
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(false); | |
// allow user to proceed if url is login.xhtml or user logged in or user is accessing any page in //public folder | |
String reqURI = req.getRequestURI(); | |
if ( reqURI.indexOf("/login.xhtml") >= 0 || (ses != null && ses.getAttribute("username") != null) | |
|| reqURI.indexOf("/public/") >= 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() + "/login.xhtml"); // Anonymous user. Redirect to login page | |
} | |
catch(Throwable t) { | |
System.out.println( t.getMessage()); | |
} | |
} //doFilter | |
@Override | |
public void destroy() { | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.sql.Connection; | |
import java.sql.DriverManager; | |
import java.sql.SQLException; | |
public class DBCon { | |
public Connection getConnection() { | |
Connection con = null; | |
try { | |
String dbDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; | |
String dbURL = "jdbc:sqlserver://SERVER_NAME;database=DB_NAME;user=USER_NAME;password=PASSWORD"; | |
Class.forName(dbDriver); | |
con = DriverManager.getConnection(dbURL); | |
System.out.println("DB Connecting"); | |
} catch (ClassNotFoundException | SQLException e) { | |
e.printStackTrace(); | |
System.out.println("Database.getConnection() Error -->" + e.getMessage()); | |
} | |
return con; | |
} | |
public void close(Connection con) { | |
try { | |
con.close(); | |
} catch (Exception ex) { | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version='1.0' encoding='UTF-8'?> | |
<faces-config version="2.0" | |
xmlns="http://java.sun.com/xml/ns/javaee" | |
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | |
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"> | |
<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> | |
</navigation-case> | |
</navigation-rule> | |
</faces-config> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="ISO-8859-1" ?> | |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> | |
<html xmlns="http://www.w3.org/1999/xhtml" | |
xmlns:h="http://java.sun.com/jsf/html" | |
xmlns:p="http://primefaces.org/ui" | |
xmlns:f="http://java.sun.com/jsf/core" | |
xmlns:ui="http://java.sun.com/jsf/facelets"> | |
<h:head> | |
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> | |
<title>Login Page</title> | |
<link type="text/css" | |
href="${facesContext.externalContext.requestContextPath}/resources/css/style.css" | |
rel="stylesheet" /> | |
<link type="image/x-icon" | |
href="${facesContext.externalContext.requestContextPath}/resources/images/favicon.ico" | |
rel="shortcut icon" /> | |
</h:head> | |
<h:body> | |
<div id="message"> | |
<p:ajaxStatus style="display:block; margin-top:.5em;"> | |
<f:facet name="default"> | |
<h:outputText value="Please enter your credentials." /> | |
</f:facet> | |
<f:facet name="start"> | |
<h:outputText value="Please wait #{loginBean.uname}, Connecting database..." /> | |
</f:facet> | |
<f:facet name="complete"> | |
<h:outputText value="Please try again #{loginBean.uname}, Database/Login error!!" /> | |
</f:facet> | |
</p:ajaxStatus> | |
</div> | |
<h:form id="loginForm"> | |
<p:growl id="msg" showDetail="true" life="4000" /> | |
<p:panel id="loginPnl" header="Login" | |
style="width: 350px; margin: 0 auto;"> | |
<h:panelGrid id="loginPanel" columns="2" cellpadding="5"> | |
<h:outputText value="Username" /> | |
<p:inputText id="username" value="#{loginBean.uname}"></p:inputText> | |
<p:spacer /><p:spacer /> | |
<h:outputText value="Password" /> | |
<p:password id="password" value="#{loginBean.password}" | |
feedback="false"></p:password> | |
<p:message for="password"></p:message> | |
</h:panelGrid> | |
<h:panelGrid columns="1" cellpadding="10" width="100%"> | |
<p:commandButton id="loginButton" action="#{loginBean.loginProject}" | |
value="Login" update="loginForm" ajax="true" style="float: right;"> | |
</p:commandButton> | |
</h:panelGrid> | |
</p:panel> | |
<p:blockUI block="loginPnl" trigger="loginButton" style="float:right;"> | |
<p:graphicImage value="resources/images/loader.gif" /> | |
</p:blockUI> | |
</h:form> | |
</h:body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
@ManagedBean(name = "loginBean") | |
@SessionScoped | |
public class LoginBean implements Serializable { | |
private static final long serialVersionUID = 1L; | |
private String password; | |
private String message, uname; | |
public String getMessage() { | |
return message; | |
} | |
public void setMessage(String message) { | |
this.message = message; | |
} | |
public String getPassword() { | |
return password; | |
} | |
public void setPassword(String password) { | |
this.password = password; | |
} | |
public String getUname() { | |
return uname; | |
} | |
public void setUname(String uname) { | |
this.uname = uname; | |
} | |
public String loginProject() { | |
boolean result = LoginDAO.login(uname, password); | |
if (result) { | |
// get Http Session and store username | |
HttpSession session = Util.getSession(); | |
session.setAttribute("username", uname); | |
return "index"; | |
} else { | |
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, | |
"Invalid Login!", | |
"Please Try Again!")); | |
// invalidate session, and redirect to other pages | |
//message = "Invalid Login. Please Try Again!"; | |
return "login"; | |
} | |
} | |
public String logout() { | |
HttpSession session = Util.getSession(); | |
session.invalidate(); | |
return "login"; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.sql.Connection; | |
import java.sql.PreparedStatement; | |
import java.sql.ResultSet; | |
import javax.faces.application.FacesMessage; | |
import javax.faces.context.FacesContext; | |
import com.jpmc.acaps.repo.DBCon; | |
public class LoginDAO { | |
public static boolean login(String user, String password) { | |
Connection con = null; | |
PreparedStatement ps = null; | |
DBCon dbcon = new DBCon(); | |
try { | |
con = dbcon.getConnection(); | |
ps = con.prepareStatement( | |
"SELECT username, password FROM UserLogin WHERE username= ? and password= ? "); | |
ps.setString(1, user); | |
ps.setString(2, password); | |
ResultSet rs = ps.executeQuery(); | |
if (rs.next()) // found | |
{ | |
System.out.println(rs.getString("username")); | |
return true; | |
} | |
else { | |
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, | |
"LoginDAO!", | |
"Wrong password message test!")); | |
return false; | |
} | |
} | |
catch (Exception ex) { | |
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, | |
"Database Error", | |
"Unable to connect database")); | |
System.out.println("Error in login() -->" + ex.getMessage()); | |
return false; | |
} finally { | |
dbcon.close(con); | |
} | |
} | |
public static void main(String[] args) { | |
System.out.println(LoginDAO.login("user", "pass")); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
PrimeFaces login example using MySQL db | |
Required Jar | |
jsf-api.jar | |
jsf-impl.jar | |
jstl.jar | |
mysql-connector-java-5.1.13-bin.jar | |
primefaces-3.4.1.jar | |
standard.jar |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.faces.context.FacesContext; | |
import javax.servlet.http.HttpServletRequest; | |
import javax.servlet.http.HttpSession; | |
public class Util { | |
public static HttpSession getSession() { | |
return (HttpSession) | |
FacesContext. | |
getCurrentInstance(). | |
getExternalContext(). | |
getSession(false); | |
} | |
public static HttpServletRequest getRequest() { | |
return (HttpServletRequest) FacesContext. | |
getCurrentInstance(). | |
getExternalContext().getRequest(); | |
} | |
public static String getUserName() | |
{ | |
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false); | |
return session.getAttribute("username").toString(); | |
} | |
public static String getUserId() | |
{ | |
HttpSession session = getSession(); | |
if ( session != null ) | |
return (String) session.getAttribute("userid"); | |
else | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment