[RESOLVIDO] Validação Login com Expression Language

4 respostas
C

Boa tarde Colegas,

Estou estudando Java Web com o Curso da Caelum FJ-21. De acordo com a apostila é encorajado o uso de EL +JSTL para quem utiliza JSP (Limpo e Elegante).

Consegui realizar a autenticação da seguinte maneira: Criei Index.jsp com o formulario com action para autentica-usuario.jsp onde é efetuado busca dos parametros, instancias de POJO (JavaBean) e do DAO.

Qual a minha duvida? Como faço para usar EL+JSTL no meu Index.jsp

Segue abaixo codigos do que fiz.

Index.jsp

<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Pagina Login</title>
</head>
<body>
	
	<center>
      <img src="imagens/login2.jpg" alt="" />
      <p>&nbsp;</p>
      <p>&nbsp;</p>
	</center>
	<form action="autentica-usuario.jsp" method="post">
		<p align="center">
		Usuario.:<input type="text" name="tf_usuario"/>
		Senha.:<input type="password"" name="tf_senha"/>
		</p>
		<p align="center">
		<input type="submit" value="Enviar"/>
		<input type="reset" value="Limpar"/>
		</p>
	</form>
</body>
</html>

autentica-usuario.jsp

<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@page import="br.com.neri.modelo.Login" %>
<%@page import="br.com.neri.dao.LoginDAO"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Autentica Usuario</title>
</head>
<body>

<%
	String status = "false";
	
	String usuario = request.getParameter("tf_usuario");
	String senha = request.getParameter("tf_senha");

	Login lgUsuario = new Login();
	lgUsuario.setLog_usuario(usuario);
	lgUsuario.setLog_senha(senha);
	
	LoginDAO lgDao = new LoginDAO();
	status = lgDao.verificaLogin(lgUsuario);
	
	if(status == "true")
	{
		response.sendRedirect("bemvindo.jsp");
	}else{
		response.sendRedirect("index.jsp");
	}
%>
</body>
</html>

loginDao.java

package br.com.neri.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import br.com.neri.jdbc.ConnectionFactory;
import br.com.neri.modelo.Login;



public class LoginDAO {
	
	private Connection connection;
	
	public LoginDAO(){
		
		this.connection = new ConnectionFactory().getConnection();
		
	}
	
	public void adiciona(Login login) throws SQLException{
		
		String sqlAdiciona = "insert into login (log_usuario,log_senha,log_nivelacesso) values(?,?,?)";
		
		
		try {
			
			//prepara inserção
			PreparedStatement stmt = connection.prepareStatement(sqlAdiciona);
			
			//seta valores
			stmt.setString(1, login.getLog_usuario());
			stmt.setString(2, login.getLog_senha());
			stmt.setString(3, login.getLog_nivelAcesso());
			
			//executa
			stmt.execute();
			stmt.close();
			
		} catch (SQLException erroSql) {
			throw new RuntimeException(erroSql);
		}
	}
	
	public String verificaLogin(Login login){
		
		String sqlVerifica = "select * from login where log_usuario=? and log_senha=?";
		String status = "";
		
		try {
			
			PreparedStatement stmt = connection.prepareStatement(sqlVerifica);
			stmt.setString(1, login.getLog_usuario());
			stmt.setString(2, login.getLog_senha());
			ResultSet rs = stmt.executeQuery();
			
			if(rs.next()){
				
				status = "true";
			}
			
		} catch (SQLException erroSql) {
			throw new RuntimeException(erroSql);
		}
		
		return status;
	}
	
	public List<Login> getLista(){
		
		try{
			
			List<Login> loginList = new ArrayList<Login>();
			PreparedStatement stmt = this.connection.prepareStatement("select * from login");
			ResultSet rs = stmt.executeQuery();
			
			while (rs.next()) {
				
				//cria objeto login
				Login login = new Login();
				login.setLog_usuario(rs.getString("log_usuario"));
				login.setLog_senha(rs.getString("log_senha"));
				login.setLog_nivelAcesso(rs.getString("log_nivelacesso"));
				
				//adiciona o objeto a lista
				loginList.add(login);
			}
		rs.close();
		stmt.close();
		return loginList;
		}catch (SQLException erroSql) {
			throw new RuntimeException(erroSql);
		}
	}
	
	/*public void verifica(String u, String s){
		
		String sqlVerifica = "select from login where log_usuario=? and log_senha=?";
		
		try{
			PreparedStatement stmt = connection.prepareStatement(sqlVerifica);
			ResultSet rs = stmt.executeQuery();
			
			
		rs.close();
		stmt.close();
		}catch(SQLException erroSql){
			throw new RuntimeException(erroSql);
		}
	}*/
	
	public void altera(Login login){
		
		String sqlAltera = "update login set log_usuario=?,log_senha=?,log_nivelacesso=? where log_codigo=?";
		
		
		try {
			
			PreparedStatement stmt = connection.prepareStatement(sqlAltera);
			stmt.setString(1, login.getLog_usuario());
			stmt.setString(2, login.getLog_senha());
			stmt.setString(3, login.getLog_nivelAcesso());
			stmt.setLong(4, login.getLog_codigo());
			
			stmt.execute();
			stmt.close();
			
		} catch (SQLException erroSql) {
			throw new RuntimeException(erroSql);
		}
	}
	
	public void remove(Login login){
		
		String sqlRemove = "delete from login where log_codigo=?";
		
		try {
			
			PreparedStatement stmt = connection.prepareStatement(sqlRemove);
			stmt.setLong(1, login.getLog_codigo());
			
			stmt.execute();
			stmt.close();
			
		} catch (SQLException erroSql) {
			throw new RuntimeException(erroSql);
		}
	}
}

[size=18]O QUE FAÇO?[/size]

4 Respostas

R

coloca na pagina <c:if> </c:if> e implementa sua logica nela

C

Apliquei sua sugestao. No entanto, como eu faço para caso autenticacao "false" ele volte para o index.jsp e os campos "resetados"?

<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Pagina Login</title>
</head>
<body>
	<c:if test="${empty param.tf_usuario }">

	<center>
      <img src="imagens/login2.jpg" alt="" />
      <p>&nbsp;</p>
      <p>&nbsp;</p>
	</center>
	<form action="" method="post">
		<p align="center">
		Usuario.:<input type="text" name="tf_usuario"/>
		Senha.:<input type="password"" name="tf_senha"/>
		</p>
		<p align="center">
		<input type="submit" value="Enviar"/>
		<input type="reset" value="Limpar"/>
		</p>	
	</form>
		
	</c:if>
	
	<%
	  
	  String usuario = request.getParameter("tf_usuario");
	  String senha = request.getParameter("tf_senha");
	
	%>
	
	<jsp:useBean id="loginUsuario" class="br.com.neri.modelo.Login"></jsp:useBean>
	
		<%
		
		loginUsuario.setLog_usuario(usuario);
		loginUsuario.setLog_senha(senha);
		
		%>
	
	<jsp:useBean id="loginDao" class="br.com.neri.dao.LoginDAO"></jsp:useBean>
	
		<%
		
			String status = loginDao.verificaLogin(loginUsuario);
			if(status == "true"){
				
				response.sendRedirect("bemvindo.jsp");
			}else{
				out.println("acesso negado");
			}
		%>

</body>
</html>

[size=18]O codigo acima funciona mas fica aparecendo o else quando carrega a pagina

OBS.: Tem como eu armazenar uma EL numa variavel local ou entao setar para o meu POJO (JavaBean)?[/size]

C

Estarei utilizando na proxima postagem a aplicação de MVC (Model View Controller) utilizando talvez o Hibernate como camada M.

Aguardem…

lisasf

Olá. :smiley:
Esse post me ajudou muito a esclarecer varias dúvidas.
Meu código está parecido com o implementado acima.
Estou tentando rodar uma aplicação web usando tomcat que usa ?tarefas? que necessitam de conexão com um banco de dados (postgre).
Desenvolvi apenas as paginas de login e cadastro de usuário…
Quando vou tentar fazer login ou cadastrar …aparecem os seguintes erros no tomcat:

org.apache.jasper.JasperException: Unable to compile class for JSP:

An error occurred at line: 23 in the jsp file: /cadastroUsuario.jsp

Usuario cannot be resolved to a type

20:         String tipo = request.getParameter(tipo);

21:         String senha = request.getParameter(senha);

22:

23:         Usuario inUsuario= new Usuario();

24:         inUsuario.setEmail(email);

25:         inUsuario.setNome(nome);

26:         inUsuario.setTipo(tipo);
An error occurred at line: 23 in the jsp file: /cadastroUsuario.jsp

Usuario cannot be resolved to a type

20:         String tipo = request.getParameter(tipo);

21:         String senha = request.getParameter(senha);

22:

23:         Usuario inUsuario= new Usuario();

24:         inUsuario.setEmail(email);

25:         inUsuario.setNome(nome);

26:         inUsuario.setTipo(tipo);
An error occurred at line: 29 in the jsp file: /cadastroUsuario.jsp

UsuarioGeral cannot be resolved to a type

26:         inUsuario.setTipo(tipo);

27:         inUsuario.setSenha(senha);

28:

29:         UsuarioGeral inUG = new UsuarioGeral();

30:         status = inUG.cadastroUsuario(inUsuario);

31:

32:

Alguém pode me auxiliar?

Criado 14 de março de 2011
Ultima resposta 6 de jun. de 2011
Respostas 4
Participantes 3