<?xml version="1.0" encoding="ISO-8859-1"?>
<rss version="2.0">
	<channel>
		<title><![CDATA[Últimas mensagens do tópico "Autenticando em um sistema de Login "]]></title>
		<link>http://www.guj.com.br/posts/list/6.java</link>
		<description><![CDATA[Últimas mensagens enviadas no tópico "Autenticando em um sistema de Login "]]></description>
		<generator>JForum - http://www.jforum.net</generator>
			<item>
				<title>Autenticando em um sistema de Login </title>
				<description><![CDATA[ Pessoal,<br /> <br /> Sou iniciante em programaçao java para web, criei uma classe login, na qual usando cookies, permite que usuarios<br /> sejam autenticados. Quando tento fazer o login com o usuario admin (cadastrado no MySLQ) vem a mensagem:<br /> <br /> Nao foi possivel conectar com o banco.<br /> Parameter index out of range (1 &gt; of parameters, which is 0)<br /> <br /> Tentei diversas formas mas sem sucesso.<br /> <br /> Segue abaixo o codigo.<br /> <br /> package br.home.livraria;<br /> <br /> import java.io.IOException;<br /> import java.io.PrintWriter;<br /> import java.sql.Connection;<br /> import java.sql.DriverManager;<br /> import java.sql.PreparedStatement;<br /> import java.sql.ResultSet;<br /> import java.sql.SQLException;<br /> import javax.servlet.ServletConfig;<br /> import javax.servlet.ServletException;<br /> import javax.servlet.http.*;<br /> import java.sql.*;<br /> <br /> /**<br />  * Servlet implementation class Login<br />  */<br /> public class Login extends HttpServlet {<br /> 	private static final long serialVersionUID = 1L;<br /> 	private Connection conn;<br />        <br />     /**<br />      * @see HttpServlet#HttpServlet()<br />      */<br />     public Login() {<br />         super();<br />         // TODO Auto-generated constructor stub<br />     }<br /> <br /> 	/**<br /> 	 * @see Servlet#init(ServletConfig)<br /> 	 */<br /> 	public void init(ServletConfig config) throws ServletException {<br /> 		// TODO Auto-generated method stub<br /> 		String connectionString = "jdbc:mysql://localhost/livraria?user=root&password=1234";<br /> 		<br /> 	       try {<br /> 	            Class.forName("com.mysql.jdbc.Driver");<br /> 	            conn = DriverManager.getConnection(connectionString);<br /> 	        }<br /> 	        catch (ClassNotFoundException err) {<br /> 	            System.out.println("Nao foi possivel carregar o Driver");<br /> 	            System.out.println(err.getMessage());<br /> 	        }<br /> 	       <br /> 	        catch (SQLException err){<br /> 	            System.out.println("Erro ao estabelecer a conexao com o banco de dados");<br /> 	            System.out.println(err.getMessage());<br /> 	        }<br /> 	    }<br /> 		<br /> <br /> 	/**<br /> 	 * @see Servlet#destroy()<br /> 	 */<br /> 	public void destroy() {<br /> 		// TODO Auto-generated method stub<br /> 	}<br /> <br /> 	/**<br /> 	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)<br /> 	 */<br /> 	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<br /> 		// TODO Auto-generated method stub<br /> 		<br /> 		PrintWriter out = response.getWriter();<br /> 		String html = "";<br /> 		String login = "";<br /> 		<br /> 		Cookie cookies[] = request.getCookies();<br /> 		if (cookies != null){<br /> 			for (int i = 0 ; i &lt; cookies.length; i++){<br /> 				if (cookies[i].getName().equals("login")== true){<br /> 					login = cookies[i].getValue();<br /> 				} //fecha segundo if<br /> 				<br /> 			} //fecha for<br /> 		} //fecha primeiro if<br /> 		<br /> 		<br /> 		html += "&lt;html&gt;";<br /> 		html += "&lt;head&gt;";<br /> 		html += "&lt;title&gt;Biblioteca Online&lt;/title&gt;";<br /> 		html += "&lt;/head&gt;";<br /> 		html += "&lt;body&gt;";<br /> 		html += "&lt;form method='post' target='_self' action='#' &gt;";<br /> 		html += "Login:&lt;input type='text' id='login' name='login' value='" + login + "'&gt;&lt;br/&gt;";<br /> 		html += "Senha:&lt;input type='password' id='password' name='password'&lt;br/&gt;";<br /> 		html += "&lt;input type='submit' id='btnLogin' name='btnLogin' value='Login'&gt;&lt;br/&gt;";<br /> 		html += "&lt;/form&gt;";<br /> 		html += "&lt;/html&gt;";<br /> 	    out.print(html);	<br /> 	}<br /> <br /> 	/**<br /> 	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)<br /> 	 */<br /> 	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<br /> 		// TODO Auto-generated method stub<br /> 		<br /> 		PrintWriter out = response.getWriter();<br /> 		PreparedStatement smt;<br /> 		Cookie cookie;<br /> 	    ResultSet rs;<br /> 	    String sql = "select * from tb_usuario where login = '?' and password = password('?')";<br /> 	    String html = "";<br /> 	    html += "&lt;html&gt;";<br />         html += "&lt;body&gt;";<br />         try {<br />             if (request.getParameter("login")!= null && request.getParameter("password")!= null) {<br />                 smt = conn.prepareStatement(sql);<br />                 smt.setString(1, request.getParameter("login"));<br />                 smt.setString(2, request.getParameter("password"));<br />                 rs = smt.executeQuery();<br />                 <br />                 if (rs.next()){<br />                 	cookie = new Cookie("login", request.getParameter("login"));<br />                 	response.addCookie(cookie);<br />                 	response.sendRedirect("sucesso.html");<br />                 	<br />                 	/* Pratica 3<br />                 	HttpSession session = request.getSession();<br />                 	session.setAttribute("UserName",rs.getString("Nome"));<br />                 	response.sendRedirect("CadastraLivro");*/<br />                 }<br />                 else {<br />                 	html += "usuario ou senha invalidos";<br />                 }<br />                 rs.close();<br />                 smt.close();<br />                 <br />             } else{<br />             	html += "usuario ou senha nao informada !";<br />                 }<br />                 <br />             } catch (SQLException err){<br />             	html += "Nao foi possivel conectar com o banco&lt;br&gt;&lt;br&gt;";<br />             	html += err.getMessage();<br />             }<br />             html+= "&lt;/body&gt;";<br />             html+= "&lt;/html&gt;";<br />             out.print(html);<br />             out.close();           <br />              }     <br /> 	}      <br /> <br /> Att,<br /> <br /> Faria		]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/200767/1011782/autenticando-em-um-sistema-de-login-
</guid>
				<link>http://www.guj.com.br/prepost/200767/1011782/autenticando-em-um-sistema-de-login-
</link>
				<pubDate><![CDATA[Fri, 12 Mar 2010 20:59:11]]> GMT</pubDate>
				<author><![CDATA[ rodrigofariat]]></author>
			</item>
			<item>
				<title>Re:Autenticando em um sistema de Login </title>
				<description><![CDATA[ Olá,<br /> <br /> Tente remover as aspas simples da sua query. Ficaria assim:<br /> <br /> [code]String sql = "select * from tb_usuario where login = ? and password = password(?)"; [/code]<br /> <br /> Quando você chama o setString() do PreparedStatement ele já lida automaticamente com as aspas simples, então você não precisa se preocupar com isso.<br /> <br /> Outra coisa que eu gostaria de falar é que você deve tomar muito cuidado com a forma como você está programando este servlet. Lembre-se de que os servlets são normalmente compartilhados entre as requisições. Desta forma, declarar o objeto da sua conexão com o banco de dados como um atributo do servlet é extremamente perigoso e não recomendado em nenhuma situação (ainda mais em se tratando de um recurso como uma conexão). Para fins de aprendizagem tudo bem (e acho que é esse seu objetivo), mas só neste caso. Só quis te dar esse toque ;)<br /> <br /> Abraço]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/200767/1011861/reautenticando-em-um-sistema-de-login-
</guid>
				<link>http://www.guj.com.br/prepost/200767/1011861/reautenticando-em-um-sistema-de-login-
</link>
				<pubDate><![CDATA[Sat, 13 Mar 2010 09:48:30]]> GMT</pubDate>
				<author><![CDATA[ ctosin]]></author>
			</item>
			<item>
				<title>Re:Autenticando em um sistema de Login </title>
				<description><![CDATA[ Oi Ctosin,<br /> <br /> Funcionou após retirar as aspas.<br /> A idéia é mais para aprendizado mesmo.<br /> Mas caso eu goste de programar em Java, vou segui a dica que voce passou.<br /> <br /> Obrigado !<br /> <br /> Faria]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/200767/1011917/reautenticando-em-um-sistema-de-login-
</guid>
				<link>http://www.guj.com.br/prepost/200767/1011917/reautenticando-em-um-sistema-de-login-
</link>
				<pubDate><![CDATA[Sat, 13 Mar 2010 12:16:03]]> GMT</pubDate>
				<author><![CDATA[ rodrigofariat]]></author>
			</item>
	</channel>
</rss>
