>
não consigo o formato correto após fazer o login e ir para http://localhost:8080/Chamados/ListarChamados,
SEU IP = 127.0.0.1
<br><a href='http://localhost:8080/Chamados/Login?msg=logoff'>Sair</a>
<table width='100%'>
<tr bgcolor='#c0c0c0'>
<td>ID</td>
<td>Titulo</td>
<td>Editar</td>
<td>Apagar</td>
</tr>
<td>1</td>
<td>Teste BD 1</td>
<td><a href='http://localhost:8080/Chamados/EditarChamado?id=1'>[EDITAR]</a></td>
<td><a href='http://localhost:8080/Chamados/ListarChamados?id=1'>[APAGAR]</a></td>
</tr>
<td>2</td>
<td>response</td>
<td><a href='http://localhost:8080/Chamados/EditarChamado?id=2'>[EDITAR]</a></td>
<td><a href='http://localhost:8080/Chamados/ListarChamados?id=2'>[APAGAR]</a></td>
</tr>
</table>
Classe LoginServlet
public class LoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
PrintWriter out = response.getWriter();
if (request.getParameter("msg") != null) {
if (request.getParameter("msg").equals("error")) {
out.println("<span> style='color:red' Login e/ou Senha INCORRETOS! </span>");
}
}
out.println("<html>");
out.println("<head>");
//Abaixo aparece na aba do navegador
out.println("<title>Login do Sistema</title>");
out.println("</head>");
out.println("<body>");
// texto título
out.println("<h1>Preencha seu Login e Senha </h1>");
// coloca quebra de linha
out.println("<hr/>");
// criar formulário
out.println("<form method='POST'>");
out.println("Login:<br> <input type='text' name='txtLogin'>");
out.println("<br>");
out.println("Senha:<br> <input type='password' name='txtSenha'>");
out.println("<br>");
// botão
out.println("<input type='submit' value='Logar'>");
out.println("</form>");
// pula linha
out.println("<br>");
out.println("<a href='http://localhost:8080/Chamados/ListarChamados'>Listar Chamados</a>");
out.println("<br>");
out.println("<a href='http://localhost:8080/Chamados/Logoff'>Sair</a>");
out.println("</body>");
out.println("</html>");
} catch (IOException e) {
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String login = request.getParameter("txtLogin");
String senha = request.getParameter("txtSenha");
//carregando o driver de conexão
try {
Class.forName("com.mysql.jdbc.Driver");
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/chamados_rlsystem", "root", "123");
String sql ="SELECT * FROM usuarios WHERE login=? AND senha=?";
PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setString(1, login);
pstm.setString(2, senha);
ResultSet rs = pstm.executeQuery(); // executeQuery para queries
if (rs.next()) {
pstm.close();
conn.close();
HttpSession sessao = request.getSession(); // HttpSession colocar ou ler variáveis de sessão
sessao.setAttribute("login", login); // aqui coloca variavel de sessão
sessao.setAttribute("info", request.getRemoteAddr());
response.sendRedirect("http://localhost:8080/Chamados/ListarChamados");
}else {
pstm.close();
conn.close();
response.sendRedirect("http://localhost:8080/Chamados/Login?msg=error");
}
} catch (SQLException e) {
out.println("Problema no banco de dados, erro: "+e.getMessage());
}
} catch (ClassNotFoundException ex) {
out.println("Problema ao carregaro driver de conexão, erro: "+ex.getMessage());
}
}
}
classe ListarChamadosServlet
public class ListarChamadosServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
HttpSession sessao = request.getSession();
if (sessao.getAttribute("login") == null) {
response.sendRedirect("http://localhost:8080/Chamados/Login");
}
out.println("SEU IP = " + sessao.getAttribute("info"));
out.println("<br><a href='http://localhost:8080/Chamados/Login?msg=logoff'>Sair</a>");
try {
Class.forName("com.mysql.jdbc.Driver");
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/chamados_rlsystem", "root", "123");
// Deleta o registro
// Quando existir uma QUERY String id
if(request.getParameter("id")!= null) {
int ID = Integer.parseInt(request.getParameter("id"));
String sqlDelete = "DELETE FROM chamados WHERE id=?";
PreparedStatement pstm = conn.prepareStatement(sqlDelete);
pstm.setInt(1, ID);
pstm.execute();
}
String sql = "SELECT * FROM chamados";
Statement stm = conn.createStatement();
ResultSet rs = stm.executeQuery(sql);
// Criando tabela na pagina html
out.println("<table width='100%'>");
out.println("<tr bgcolor='#c0c0c0'>");
out.println("<td>ID</td>");
out.println("<td>Titulo</td>");
out.println("<td>Editar</td>");
out.println("<td>Apagar</td>");
out.println("</tr>");
while(rs.next()) {
out.println("<td>"+ rs.getInt("id")+ "</td>");
out.println("<td>"+ rs.getString("titulo")+ "</td>");
out.println("<td><a href='http://localhost:8080/Chamados/EditarChamado?id=" +rs.getInt("id")+ "'>[EDITAR]</a></td>"); //link
out.println("<td><a href='http://localhost:8080/Chamados/ListarChamados?id=" +rs.getInt("id")+ "'>[APAGAR]</a></td>"); //link
out.println("</tr>");
}
out.println("</table>");
stm.close();
conn.close();
} catch (SQLException e) {
out.println("Problema no banco de dados, erro: "+e.getMessage());
}
} catch (ClassNotFoundException ex) {
out.println("Problema ao carregar o driver de conexão, erro: "+ex.getMessage());
}
}
}
Banco de Dados
### BD para JEE do rlsystem
DROP DATABASE chamados_rlsystem;
##
CREATE DATABASE chamados_rlsystem;
use chamados_rlsystem;
CREATE TABLE chamados (
id INT( 20 ) AUTO_INCREMENT ,
titulo VARCHAR(255),
conteudo TEXT,
data DATETIME,
PRIMARY KEY ( id )
);
/*conteúdo das tabelas*/
SELECT * FROM chamados;
SHOW tables;
/* detalhes da tabela */
DESCRIBE chamados;
# Tabela usuarios para fazer login no sitema
CREATE TABLE usuarios(
id INT( 20 ) AUTO_INCREMENT ,
login VARCHAR(255),
senha VARCHAR(255),
PRIMARY KEY ( id )
);
SELECT * FROM usuarios;
SHOW tables;
DESCRIBE usuarios;
INSERT INTO usuarios (login, senha) VALUES ('admin', '123');
Aqui a web.xml
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<web-app xmlns:xsi=\"http://w3.org/2001/XMLSchema-instance\" xmlns=\"http://java.sun.com/xml/ns/javaee\" xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\" id=\"WebApp_ID\" version=\"2.5\">
<display-name>Chamados</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>IndexServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/Index</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>NovoChamadoServlet</display-name>
<servlet-name>NovoChamadoServlet</servlet-name>
<servlet-class>NovoChamadoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NovoChamadoServlet</servlet-name>
<url-pattern>/NovoChamado</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>ListarChamados</display-name>
<servlet-name>ListarChamados</servlet-name>
<servlet-class>ListarChamadosServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ListarChamados</servlet-name>
<url-pattern>/ListarChamados</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>EditarChamadoServlet</display-name>
<servlet-name>EditarChamadoServlet</servlet-name>
<servlet-class>EditarChamadoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>EditarChamadoServlet</servlet-name>
<url-pattern>/EditarChamado</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>Login</display-name>
<servlet-name>Login</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>60</session-timeout>
</session-config>
</web-app>
Resolvido
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
PrintWriter out = response.getWriter();
out.println(\"<html>\");
out.println(\"<head>\");
//Abaixo aparece na aba do navegador
out.println(\"<title>Login do Sistema</title>\");
out.println(\"</head>\");
out.println(\"<body>\");
// texto título
out.println(\"<h1>Preencha seu Login e Senha </h1>\");
// coloca quebra de linha
out.println(\"<hr/>\");
out.println(\"<br>\");
//ERRO usuário inválido
if (request.getParameter(\"msg\") != null) {
if (request.getParameter(\"msg\").equals(\"error\")) {
out.println(\"<span style=\'color: red\'>Login e/ou senhas incorreto!</span>\");
}
}
out.println(\"<br>\");
// criar formulário
out.println(\"<form method=\'POST\'>\");
out.println(\"Login:<br> <input type=\'text\' name=\'txtLogin\'>\");
out.println(\"<br>\");
out.println(\"Senha:<br> <input type=\'password\' name=\'txtSenha\'>\");
out.println(\"<br>\");
// botão
out.println(\"<input type=\'submit\' value=\'Logar\'>\");
out.println(\"</form>\");
// pula linha
out.println(\"<br>\");
out.println(\"<a href=\'http://localhost:8080/Chamados/ListarChamados\'>Listar Chamados</a>\");
out.println(\"<br>\");
out.println(\"<a href=\'http://localhost:8080/Chamados/Logoff\'>Sair</a>\");
out.println(\"</body>\");
out.println(\"</html>\");
} catch (IOException e) {
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String login = request.getParameter(\"txtLogin\");
String senha = request.getParameter(\"txtSenha\");
//carregando o driver de conexão
try {
Class.forName(\"com.mysql.jdbc.Driver\");
try {
Connection conn = DriverManager.getConnection(\"jdbc:mysql://localhost/chamados_rlsystem\", \"root\", \"123\");
String sql =\"SELECT * FROM usuarios WHERE login = ? AND senha = ?\";
PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setString(1, login);
pstm.setString(2, senha);
ResultSet rs = pstm.executeQuery(); // executeQuery para queries
if (rs.next()) {
pstm.close();
conn.close();
HttpSession sessao = request.getSession(); // HttpSession colocar ou ler variáveis de sessão
sessao.setAttribute(\"login\", login); // aqui coloca variavel de sessão
sessao.setAttribute(\"info\", request.getRemoteAddr());
response.sendRedirect(\"http://localhost:8080/Chamados/ListarChamados\");
}else {
pstm.close();
conn.close();
response.sendRedirect(\"http://localhost:8080/Chamados/Login?msg=error\");
}
} catch (SQLException e) {
out.println(\"Problema no banco de dados, erro: \"+e.getMessage());
}
} catch (ClassNotFoundException ex) {
out.println(\"Problema ao carregaro driver de conexão, erro: \"+ex.getMessage());
}
}
}
public class ListarChamadosServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
HttpSession sessao = request.getSession();
if (sessao.getAttribute(\"login\") == null) {
response.sendRedirect(\"http://localhost:8080/Chamados/Login\");
}
try {
Class.forName(\"com.mysql.jdbc.Driver\");
try {
Connection conn = DriverManager.getConnection(\"jdbc:mysql://localhost/chamados_rlsystem\", \"root\", \"123\");
// Deleta o registro
// Quando existir uma QUERY String id
if(request.getParameter(\"id\")!= null) {
int ID = Integer.parseInt(request.getParameter(\"id\"));
String sqlDelete = \"DELETE FROM chamados WHERE id=?\";
PreparedStatement pstm = conn.prepareStatement(sqlDelete);
pstm.setInt(1, ID);
pstm.execute();
}
String sql = \"SELECT * FROM chamados\";
Statement stm = conn.createStatement();
ResultSet rs = stm.executeQuery(sql);
// Criando tabela na pagina html
out.println(\"<table width=\'100%\'>\");
out.println(\"<tr bgcolor=\'#c0c0c0\'>\");
out.println(\"<td>ID</td>\");
out.println(\"<td>Titulo</td>\");
out.println(\"<td>Editar</td>\");
out.println(\"<td>Apagar</td>\");
out.println(\"</tr>\");
while(rs.next()) {
out.println(\"<td>\"+ rs.getInt(\"id\")+ \"</td>\");
out.println(\"<td>\"+ rs.getString(\"titulo\")+ \"</td>\");
out.println(\"<td><a href=\'http://localhost:8080/Chamados/EditarChamado?id=\" +rs.getInt(\"id\")+ \"\'>[EDITAR]</a></td>\"); //link
out.println(\"<td><a href=\'http://localhost:8080/Chamados/ListarChamados?id=\" +rs.getInt(\"id\")+ \"\'>[APAGAR]</a></td>\"); //link
out.println(\"</tr>\");
}
out.println(\"</table>\");
out.println(\"<br>\");
//out.println(\" SEU IP = \" + sessao.getAttribute(\"info\"));
out.println(\"<span style=\'color: green\'> SEU IP = </span>\"+ sessao.getAttribute(\"info\"));
out.println(\"<br>\");
out.println(\"<br><a href=\'http://localhost:8080/Chamados/Login?msg=logoff\'>Sair</a>\");
stm.close();
conn.close();
} catch (SQLException e) {
out.println(\"Problema no banco de dados, erro: \"+e.getMessage());
}
} catch (ClassNotFoundException ex) {
out.println(\"Problema ao carregar o driver de conexão, erro: \"+ex.getMessage());
}
}
}