How do I work with object as attribute in registering another object using JSP?

Asked

Viewed 82 times

0

I have a Schedule class. In this class I have a Task object. My question is, when creating the screen to record the scheduling, I will have a field to record the Task of this scheduling. Assuming these tasks are already registered in the database. What is the best way to work this in the view, so that the user can select the task and feed the Scheduling Task attribute to perform the registration? I researched things like "Other class object as attribute in JSP", but I didn’t find much, sorry.

1 answer

1


Friend, The process is very simple. First, you will make a call to the bank to display all available tasks. You can save these tasks in a select, for example, where the value is the id of the same. If you’re using requests ajax, could be something like:

var tarefas;
$.ajax({
  method: "GET",
  sucess: function(data){
    /* Vamos imaginar que seu retorno seja um json contendo todas
    as tarefas */
    tarefas = data.tarefas; //aqui temos acesso a todos objetos tarefas
  }
});
var select_tarefas = $("<select></select>");
$(tarefas).each(function(i,e){
  var op = $("<option></option>");
  op.val(e.id).text(e.nome);
  select_tarefas.append(op);
});

At the end you will have an html structure more or less like this:

<select>
  <option value="4332">Tarefa 1</option>
  <option value="4354">Tarefa 2</option>
  <option value="4123">Tarefa 3</option>
</select>

This is just 1 of several ways to have all the task data in your view. (You choose a way that’s more convenient for you)

Now, you need to give one name for the element to be able to access it in the backend.

On the line

var select_tarefas = $("<select></select>");

You can do:

var select_tarefas = $("<select name='q_tarefas'></select>");

Or even:

var select_tarefas = $("<select></select>");
select_tarefas.attr("name", "q_tarefas");

Having this correct structure, when giving a Submit for a link where a Servlet or even a JSP, you may have access to the task through the line:

request.getParameter("q_tarefa"); //Vai retornar o ID selecionado la no front.

From there you simply manually assemble a task object, and set in your Schedule object, example:

Agendamento a = new Agendamento();
Tarefa t = new Tarefa();

t.setId(Integer.parseInt(request.getParameter("q_tarefa"));

a.setTarefa(t);

All right, now you’ve got backend a scheduling object that has as attribute a task object. Although it is an object with only the ID, is just what you need if you are using relational database. Most likely your scheduling table has a Foreign key which is the task table ID.

I hope I helped clear things up a little. Any questions, just comment on the reply.

Hugs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.