Pessoal, é o seguinte, estou cadastrando um usuário (nome e cpf) bem simples mesmo, esta funcionando tudo normal, exibir e cadastrar, só que como eu quero deixar o código organizado eu preciso de uma ajudinha de vocês aí! segue os códigos abaixo:
Servlet (svdados)package classes;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class svdados
*/
@WebServlet({ "/svdados", "/SVDADOS", "/Svdados" })
public class svdados extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public svdados() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
PrintWriter out = response.getWriter();
if(request.getParameter("acao").equalsIgnoreCase("cadastrar")){
String nome = request.getParameter("nome");
String cpf = request.getParameter("cpf");
if(cpf.length() != 11 || !cpf.matches("[0-9]*")){
response.sendRedirect("index.jsp?erro=1");
}
else{
try{
usuario u = new usuario();
u.addUsuario(nome, cpf);
response.sendRedirect("relatorio.jsp");
}
catch(Exception e){
System.out.println("Erro Servlet "+e.getMessage());
}
}
}
}
}
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Dados</title>
</head>
<body>
<%
if(request.getParameter("erro") != null){
if(request.getParameter("erro").equalsIgnoreCase("1")){
%>
<h3>Erro, CPF Inválido!</h3>
<%
}
}
%>
<form action="svdados?acao=cadastrar" method="post">
Nome <input type="text" name="nome" required>
<br>
CPF <input type="text" name="cpf" required pattern="[0-9]*">
<br>
<input type="submit" value="Enviar">
</form>
</body>
</html>
[/<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Dados</title>
</head>
<body>
<%
if(request.getParameter("erro") != null){
if(request.getParameter("erro").equalsIgnoreCase("1")){
%>
<h3>Erro, CPF Inválido!</h3>
<%
}
}
%>
<form action="svdados?acao=cadastrar" method="post">
Nome <input type="text" name="nome" required>
<br>
CPF <input type="text" name="cpf" required pattern="[0-9]*">
<br>
<input type="submit" value="Enviar">
</form>
</body>
</html>
package classes;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.xml.ws.Response;
public class usuario {
private String nome;
private String cpf;
private String id;
public String getId(){
return id;
}
public void setId(String id){
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public void addUsuario(String nome, String cpf){
String sql = "INSERT INTO usuario (nome,cpf) values (?,?)";
try{
Connection con = conexao.getConnection();
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, nome);
stmt.setString(2, cpf);
stmt.execute();
stmt.close();
con.close();
}
catch(SQLException e){
System.out.println("Erro SQL : "+e.getMessage());
}
catch(Exception e){
System.out.println("Erro na classe Usuário: "+e.getMessage());
}
}
public void exibeUsuario(){
try{
Connection con = conexao.getConnection();
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("SELECT * FROM usuario");
while(rs.next()){
this.setId(rs.getString("idusuario"));
this.setNome(nome = rs.getString("nome"));
this.setCpf(rs.getString("cpf"));
}
}
catch(Exception e){
System.out.println("Erro! "+e.getMessage());
}
}
}
relatorio.jsp
<%@page import="java.sql.*"%>
<%@page import="classes.*"%>
<%@page import="java.sql.ResultSet"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Lista de usuários</title>
</head>
<body>
<h2>Lista de Usuários</h2>
<table border=1>
<tr>
<td>ID</td>
<td>Nome</td>
<td>CPF</td>
</tr>
<%
usuario u = new usuario();
// Aqui executaria o método para exibir os usuários cadastrados.
%>
</table>
<br>
<a href="index.jsp">Voltar</a>
</body>
</html>
Também tem a classe conexão, mas acho que não seja necessário por aqui, no caso , eu estou enviando o nome e o cpf do formulário na pagina "index.jsp" para o servlet (svdados), lá ele verifica se o cpf tem 11 números, se tiver ele passa e insere no banco de dados usando o método (u.addUsuario(nome,cpf)), bem, o que eu queria era executar um método que mostrasse a lista de todos os usuários cadastrados... sei como fazer normal usando o ResultSet e imprimindo, mas será que não tem um modo de fazer utilizando apenas o método? Obrigado!
:!: Se vocês também acharem outro modo melhor de "embelezar" o código podem dar dicas ai! o que eu quero é aprender mais!
