1
I have a database and an html code that I finally managed to make connection but the code is kind of messy because it mixes html with java and mysql... Following example:
<%@page import="java.io.*,java.sql.*" %>
<%
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/cadastro", "root","");
String acao = request.getParameter("acao");
if(acao == null){
acao="listarPessoas";
}
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>cadastro</title>
</head>
<body>
<form action="#" method="post">
<%
if(acao.equals("cadastro")){
String nome = request.getParameter("nome");
String idade = request.getParameter("idade");
if(nome != null && idade != null){
String sql="INSERT INTO pessoa(nome,idade) VALUE(?,?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, nome);
stmt.setString(2, idade);
stmt.execute();
out.println("pessoa" + " "+ nome + " " +idade );
acao="listarPessoas";
acao="novoCadastroPessoas";
out.println("<v> TODOS OS CAMPOS DEVER SER PREENCHIDOS</v>");
}else{
acao="novoCadastroPessoas";
out.println("<v> TODOS OS CAMPOS DEVER SER PREENCHIDOS</v>");
}
}
if(acao.equals("novoCadastro")){
%>
<label for="nome">nome:</label>
<input type = "text " name="nome">
<label for="idade">idade:</label>
<input type="date" id="idade">
<button type="submite" name="acao" value="listarPessoas">voltar</button>
<button type="submite" name="acao" value="cadastro">salvar</button>
<%
}else if(acao.equals("listarPessoas")){
%>
<button type="submit" name="acao" value="novoCadastro">Novo cadastro</button>
<fieldset>
<table>
<thead>
<tr>
<th>Codigo</th>
<th>Nome</th>
<th>Data de nascimento</th>
</tr>
</thead>
</table>
<tr>
<tb></tb>
<tb></tb>
<tb></tb>
</tr>
<fieldset>
<%
}
%>
</form>
</body>
</html>
How can I make html and java not mix, creating classes for functions like connecting to the database or extracting information? And where to put the functions in the code?
Study about Java Server Pages (JSP) and server-side Rendering.
– Piovezan
I didn’t notice that I was already using a JSP. It is worth studying about Taglibs/JSTL. Try it with this Caelum booklet (it is a bit out of date compared to the time it was released, but it is very didactic): https://www.caelum.com.br/apostila-java-web/javaserver-pages/
– Piovezan