2
I’m studying Java EE, but I’m having a hard time validating data entry forms. My Search CadastrarInstrutor
collects the form fields and checks their contents.
Below is the code of my JSP page (I put only the content of body of my page, and the validation form occurring in my.
cadastra-instructor.jsp
<%
String erros = "";
String converter = "";
if (request.getAttribute("erro") != null && request.getAttribute("erroConverter") != null) {
erros = (String) request.getAttribute("erro");
converter = (String) request.getAttribute("erroConverter");
}
%>
<form method="post" action="cadastroInstrutor">
<p>Nome:
<input type="text" name="nome"/>
<span class="erro" style="color: red;">${erros}</span>
</p>
<p>Matrícula:
<input type="text" name="matricula"/>
<span class="erro" style="color: red;">${erros}</span>
</p>
<p>Conclusão de Gradução:
<input type="text" name="graduacao"/>
<span class="erro" style="color: red;">${erros}</span>
<span class="erroConverter" style="color: red;">${erroConverter}</span>
</p>
<input type="submit" value="Enviar Dados"/>
</form>
Register instructor.java
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean isFormValido = true;
try {
String nome = request.getParameter("nome");
String matricula = request.getParameter("matricula");
String ano = request.getParameter("graduacao");
if (nome.isEmpty() || matricula.isEmpty() || ano.isEmpty()) {
request.setAttribute("erro", "Você não preencheu todos os campos!\");
isFormValido = false;
}
Integer anoGraduacao = Integer.parseInt(ano);
} catch (NullPointerException e) {
request.setAttribute("erro", "Você não preencheu todos os campos!");
isFormValido = false;
} catch (NumberFormatException e) {
request.setAttribute("erroConverter", "Apenas números são aceitos neste campo!");
isFormValido = false;
}
if (isFormValido) {
// Salvar no banco e então redirecionar para a listagem.
response.sendRedirect("listagem-instrutor.jsp");
} else {
request.getRequestDispatcher("cadastro-instrutor.jsp").forward(request, response);
}
}
By definition of the teacher (will be introduced in the future), for now, the use of JSTL is unavailable, therefore the use of scriptlets. No Javascript focus for form validation.
The question then is: How would you perform this validation, and where would you perform it?
In Servlet I would check if the parameters are not null before using
isEmpty
. In the JSP, the{erros}
I would leave only one at the beginning or end of the form and use the attributerequired
us inputs. I think only this to check if the form was filled in, if they were more complex validations I would create a specific Serublet for this.– Renan Gomes