Para poder realizar este ejecicio debes de tener las siguientes requerimientos:
Primero cremos una tabla en mysql llamada usuario para poder ingresar nuestro login y password
CREATE TABLE `usuario` ( `idUsuario` INT NOT NULL AUTO_INCREMENT, `nombreUsuario` VARCHAR(100) NOT NULL, `password` VARCHAR(30) NOT NULL, PRIMARY KEY (`idUsuario`)) ENGINE = MyISAM DEFAULT CHARACTER SET = utf8;
Una vez instalados maven,eclipse y tomcat comenzamos con configurar maven en eclipse nos vamos al menú que dice Window->Preferences;
Destendemos donde dice Maven y seleccionamos Installations y agregamos la ruta donde se encuentra nuestra instalación de maven y presionamos Apply
Una vez configurado maven nos vamos a File->New->MavenProject
Seleccionamos en Create a simple project y presionamos Next
Una vez generado nuestro proyecto maven nos vamos al archivo pom.xml y pegamos el siguiente código esta para poder compilar con java 1.8.
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>






<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutosoftware</groupId>
<artifactId>LoginTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>LoginTest</name>
<dependencies>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.10</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.10</version>
</dependency>
<!-- http://repo1.maven.org/maven -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sun.el</groupId>
<artifactId>el-ri</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
version="2.2">
<navigation-rule>
<from-view-id>/index.xhtml</from-view-id>
<navigation-case>
<from-outcome>welcome</from-outcome>
<to-view-id>/welcome.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
<application>
<resource-bundle>
<base-name>com.tutosoftware.logintest.mensajes</base-name>
<var>bundle</var>
</resource-bundle>
</application>
</faces-config>




<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title><ui:insert name="title">#{bundle['application.defaultpage.titulo']}</ui:insert></title>
<link href="#{request.contextPath}/css/simple.css" rel="stylesheet" type="text/css" />
</h:head>
<h:body>
<div id="container">
<div id="header">
<ui:insert name="header">
<h1>#{bundle['application.defaultpage.header.contenido']}</h1>
</ui:insert>
</div>
<div id="content">
<ui:insert name="content">
#{bundle['application.defaultpage.body.contenido']}
</ui:insert>
</div>
<div id="footer">
<ui:insert name="footer">
#{bundle['application.defaultpage.footer.contenido']}
</ui:insert>
</div>
</div>
</h:body>
</html>



user.name = Usuario user.password = password user.name.validation = Ingresar usuario user.password.validation = Ingresar password application.login = Login application.loginpage.title = Login page application.welcome = Bienvenido application.welcomepage.titulo = Página de bienvenida application.defaultpage.titulo = Login Test application.defaultpage.header.contenido = Bienvenido a Login Test application.defaultpage.body.contenido = Su contenido aquí application.defaultpage.footer.contenido = Gracias por usar la aplicación


@CHARSET "ISO-8859-1";
h1, p, body, html {
margin:0;
padding:0;
}
body {
background-color:#EEEEEE;
}
#container {
width:100%;
}
#header {
background-color:#FFA500;
}
#header h1 {
margin-bottom: 0px;
}
#content {
float:left;
width:100%;
}
#footer {
clear:both; /*No floating elements are allowed on left or right*/
background-color:#FFA500;
text-align:center;
font-weight: bold;
}
.errorMessage {
color: red;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<ui:composition template="/WEB-INF/templates/simple.xhtml">
<ui:define name="title">
#{bundle['application.loginpage.title']}
</ui:define>
<ui:define name="content">
<h:form>
<h:panelGrid columns="3">
<h:outputText value="#{bundle['user.name']}" />
<h:inputText
id="nombreUsuario"
value="#{login.usuario}"
required="true"
requiredMessage="#{bundle['user.name.validation']}" />
<h:message for="nombreUsuario" styleClass="errorMessage"/>
<h:outputText value="#{bundle['user.password']}" />
<h:inputSecret
id="password"
value="#{login.password}"
required="true"
requiredMessage="#{bundle['user.password.validation']}" />
<h:message for="password" styleClass="errorMessage"/>
</h:panelGrid>
<h:commandButton action="#{login.validarUsuarioPassword}" value="#{bundle['application.login']}" />
<br/><br/>
</h:form>
</ui:define>
</ui:composition>
</html>




package com.tutosoftware.logintest.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.tutosoftware.logintest.dao.LoginDAO;
import com.tutosoftware.logintest.util.SessionUtils;
@ManagedBean
@SessionScoped
public class Login implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String password;
private String msg;
private String usuario;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getUsuario() {
return usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
public String validarUsuarioPassword(){
boolean valid = LoginDAO.validate(usuario, password);
System.out.println(valid);
if (valid) {
HttpSession session = SessionUtils.getSession();
session.setAttribute("username",usuario);
return "welcome";
}else {
FacesContext.getCurrentInstance().addMessage(
null,
new FacesMessage(FacesMessage.SEVERITY_WARN,
"Usuario o password incorrecto",
"Por favor introducir password y usuario correcto"));
return "index";
}
}
public String salir(){
HttpSession session = SessionUtils.getSession();
session.invalidate();
return "index";
}
}
package com.tutosoftware.logintest.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.tutosoftware.logintest.util.DataConnect;
public class LoginDAO {
public static boolean validate(String usuario, String password) {
Connection con = null;
PreparedStatement ps = null;
try {
con = DataConnect.getConnection();
ps = con.prepareStatement("Select nombreUsuario, password from usuario where nombreUsuario = ? and password = ? ");
ps.setString(1, usuario);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return true;
}
} catch (SQLException ex) {
System.out.println("Login error -->" + ex.getMessage());
return false;
} finally {
DataConnect.close(con);
}
return false;
}
}
package com.tutosoftware.logintest.util;
import java.sql.Connection;
import java.sql.DriverManager;
public class DataConnect {
public static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/pruebadb","root","lara");
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) {
}
}
}
package com.tutosoftware.logintest.util;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public class SessionUtils {
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;
}
}
package com.tutosoftware.logintest.filtro;
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 AuthorizationFilter implements Filter {
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// TODO Auto-generated method stub
try {
HttpServletRequest reqt = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
HttpSession ses = reqt.getSession(false);
String reqURI = reqt.getRequestURI();
if (reqURI.indexOf("/index.xhtml") >= 0
|| (ses != null && ses.getAttribute("username") != null)
|| reqURI.indexOf("/public/") >= 0
|| reqURI.contains("javax.faces.resource"))
chain.doFilter(request, response);
else
resp.sendRedirect(reqt.getContextPath() + "/faces/index.xhtml");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<ui:composition template="/WEB-INF/templates/simple.xhtml">
<ui:define name="title">
#{bundle['application.welcomepage.titulo']}
</ui:define>
<ui:define name="content">
<h:form>
#{bundle['application.welcome']}, #{login.usuario}! <br/>
<h:commandLink action="#{login.salir}" value="Salir" />
</h:form>
</ui:define>
</ui:composition>
</html>
INSERT INTO pruebadb.usuario VALUES(null,'adminjsf','lara');






