0

I'm doing my first WEB project for college that I just started, and I need that JSP file to send the informations to my data bank, but to send all checkbox values I need to deal with a String array variable, that variable should put the right values in the SQL comand, but it only works if all the 3 checkboxes are checked, and I know it's because I called 3 list itens in the SQL comand, so if the user only checks 2, the 3º one doesn't exist, so I tried to put something like a (If array[1] == null){put a "XXX" value on that array}, but I couldn't make it work.

I tried something like this just to put some value in the empty ones: ` String vserv1; String vserv2; String vserv3;

if(vservA[0] == null){
String vserv1 = "XXX";
}
else{
String vserv1 = vservA[0];
}

if(vservA[1] == null){
String vserv2 = "XXX";
}
else{
String vserv2 = vservA[1];
}

if(vservA[2] == null){
String vserv3 = "XXX";
}
else{
String vserv3 = vservA[2];
}

`

By now I only know some things about HTML, CSS, and just a tiny little about JavaScript and JSP.

And I'm still learning English so... I'm sorry if I wrote something wrong = (.

Thats my code:

<head>
    <link rel="shortcut icon" href="img/ico/top.ico">
    <meta name="viewport" content="device=device-width, initial-scale=1.0">
    <title>Crie sua conta Top Show Pet </title>
    <meta charset = "UTF-8">
  <!--<meta http-equiv="refresh" content="0; URL='http://localhost:9999/TopPet/Pagina-Pet/Top-Pet-(PetForm).html'"/>-->
</head>
<body>

<%@page language="java" import="java.sql.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%
  // cria as variaveis e obtem os dados digitados pelo usuario
  String[] vservA       = request.getParameterValues("checkservico");
  String vanimal        = request.getParameter("PetEsc");
  String vdia           = request.getParameter("Data");
  String vhora          = request.getParameter("Hora");


  // variaveis para acessar o banco de dados
  String banco   = "toppetcadastro";
  String usuario = "root";
  String senha   = "";
  String url     = "jdbc:mysql://localhost:3306/" + banco;
  String driver  = "com.mysql.jdbc.Driver";

  // carrega o driver na memoria
    Class.forName( driver );

    // criar variavel para conectar com banco de dados
    Connection conexao ;

  // abrir a conexao com o banco
  conexao = DriverManager.getConnection( url , usuario , senha ) ;
  String select = "SELECT cliente.cpf, cliente.Nome, pet.id from cliente join pet on cliente.CPF = pet.Dono WHERE Email = '"+session.getAttribute("user")+"' and pet.Nome = '"+vanimal+"';";

  // cria o statement
    Statement stm = conexao.createStatement() ;

  // executa o comando do SQL
  ResultSet rs = stm.executeQuery(select);
    rs.next();

    String insert = "INSERT INTO agendado (Servico, Proprietario, Nome_Dono, Animal, Nome_Animal, Dia, Hora) VALUES('"+vservA[0]+" - "+vservA[1]+" - "+vservA[2]+"','"+rs.getString("CPF")+"','"+rs.getString("Nome")+"',"+rs.getString("id")+",'"+vanimal+"','"+vdia+"','"+vhora+"');";

    // executa o comando do SQL
    stm.executeUpdate( insert ) ;

  rs.close();
    stm.close() ;
    conexao.close() ;

    out.print("<br><br>") ;
    out.print("Dados gravados com sucesso!!!") ;

    out.print("<br><br>") ;
    out.print("<a href='http://localhost:9999/TopPet/Pagina-Agendar/Agendamento.jsp'>Continuar</a>") ;
%>

</body>
</html>```
tadman
  • 208,517
  • 23
  • 234
  • 262
  • 1
    **WARNING**: This code urgently needs *placeholder values* as you're just [injecting data arbitrarily](https://bobby-tables.com). – tadman Nov 23 '20 at 21:05
  • I guess it's not safe in any way kkkkk, but it's not mean to work on a real website, not even go online, just to do the extreme basic, but thanks for the warning! Helps a lot! = D – Jônatas Soares Nov 23 '20 at 21:31
  • 1
    It's worth learning the correct way to do this as it saves *hours of frustration and anguish* if you cut corners and leave a bunch of bugs in your code. – tadman Nov 23 '20 at 21:53
  • 1
    I will search more about it, thanks again! – Jônatas Soares Nov 23 '20 at 22:36
  • @JônatasSoares - Any update? – Arvind Kumar Avinash Nov 24 '20 at 07:59
  • Just woke up and trying to implement the code you send, but im having trouble making the `import="java.util.Arrays"` work in the JSP file. @ArvindKumarAvinash – Jônatas Soares Nov 24 '20 at 11:16
  • @JônatasSoares - Check [How do you import classes in JSP?](https://stackoverflow.com/questions/239147/how-do-you-import-classes-in-jsp). Feel free to comment in case of any doubt/issue. – Arvind Kumar Avinash Nov 24 '20 at 11:30

1 Answers1

0

Arrays#setAll

You can use this method to set all null elements of the array to XXX.

Demo:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String[] arr = { "Hello", null, "World", null, "Great" };
        System.out.println("Before: " + Arrays.toString(arr));

        Arrays.setAll(arr, i -> arr[i] == null ? "XXX" : arr[i]);
        System.out.println("After: " + Arrays.toString(arr));
    }
}

Output:

Before: [Hello, null, World, null, Great]
After: [Hello, XXX, World, XXX, Great]

Traditional way:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String[] arr = { "Hello", null, "World", null, "Great" };
        System.out.println("Before: " + Arrays.toString(arr));

        for (int i = 0; i < arr.length; i++) {
            arr[i] = arr[i] == null ? "XXX" : arr[i];
        }
        System.out.println("After: " + Arrays.toString(arr));
    }
}

Output:

Before: [Hello, null, World, null, Great]
After: [Hello, XXX, World, XXX, Great]
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • I think I implemented it right: changed the `Arrays.setAll(arr, i -> arr[i] == null ? "XXX" : arr[i]);` to `vservA.setAll(vservA, i -> vservA[i] == null ? "XXX" : vservA[i]);` wich is my array, and the `out.print` lines I erased since I don't need then to show, but I don't think it's importing the `import="java.util.Arrays"` that I put in the `<%@page language="java" import="java.sql.* import="java.util.Arrays" (...)"%>`, don't know why, but I'm searching. – Jônatas Soares Nov 24 '20 at 11:33
  • I also tried putting the imports together: `import="java.sql.*,java.util.Arrays"` but doesn't seem to work, now the page exception says: - Illegal modifier for the local class Main; only abstract or final is permitted - The method main cannot be declared static; static methods can only be declared in a static or top level type - Cannot invoke setAll(String[], ( i) -> {}) on the array type String[] – Jônatas Soares Nov 24 '20 at 11:43
  • No, you have implemented it incorrectly. It should be `Arrays.setAll(vservA, i -> vservA[i] == null ? "XXX" : vservA[i]);` – Arvind Kumar Avinash Nov 24 '20 at 12:21
  • Also, `<%@ page import="java.sql.*, java.util.Arrays" %>` works fine. Check if you have made some typo. – Arvind Kumar Avinash Nov 24 '20 at 12:28
  • `Illegal modifier for the local class Main...` - Do not create class `Main` inside your JSP. I wrote `class Main` just an example. You just have to use `Arrays.setAll(vservA, i -> vservA[i] == null ? "XXX" : vservA[i]);`. Feel free to comment in case of any doubt/issue. – Arvind Kumar Avinash Nov 24 '20 at 12:32
  • Ooooh, ok sorry, this is still new for me, but the `vservA[2]` is still empty, does the `Arrays.setAll` just set values to empty spaces between other values in the array? Because I think thats the problem, when I check values in the checkbox to send it, in the array the values will build the list, so if I just checked 2 boxes of 3, it will be: `vservA[0] = "Value1"` `vservA[1] = "Value2"` And the third one wouldn't exist. But I need to get 3 values, that's why I set the "XXX" just to have all filled. Also really thanks for the help so far. – Jônatas Soares Nov 24 '20 at 14:21
  • At least I know that the `vservA[0]` will not be null, because at least one checkbox must be checked to Submit the form. – Jônatas Soares Nov 24 '20 at 14:29
  • For this, you need to use `Arrays.setAll(vservA, i -> vservA[i] == null || vservA[i].trim().isEmpty() ? "XXX" : vservA[i]);` – Arvind Kumar Avinash Nov 24 '20 at 14:50
  • I saw it and will mark if it works, still doesn't fill a vservA[2] when I put 2 values, like I said, I think it can't do it because the [2] doesn't exist, but I also tried to set some null values in vservA and then this happened: `Local variable vservA defined in an enclosing scope must be final or effectively final`. So I think I'm trying to do it the hard way actually. The real problem is: When I get the value of the checkbox it creates a array because it's multiple values since all boxes have the same name, and I need 3 variables to fill the SQL comand, but some times only 2 variabels exist – Jônatas Soares Nov 24 '20 at 15:47
  • Ok, since the checkbox with the same name is the problem I changed to different names so i can do this: `String vservA1 = request.getParameter("checkservico1");` `String vservA2 = request.getParameter("checkservico2");` `String vservA3 = request.getParameter("checkservico3");` and it worked, the SQL could send the data, for now it's enouth but like @tadman said, it's not a good way to do it, I will search more to improve, but like I said, thanks! Should I upvote or mark your post? Like, it helped but in the end I didn't use it to solve the problem... And also sorry for the burden. – Jônatas Soares Nov 24 '20 at 16:14
  • @JônatasSoares - You do not have enough reputation points to upvote (you need at least 15 points). So, all you can do is accept the answer. However, I suggest you not to accept it if it didn't solve your problem. – Arvind Kumar Avinash Nov 24 '20 at 16:18