Form info to Servlet and JSP - java

0

I've been stuck for a few days and I can not move forward.

  • I collect data from a form in SERVLET .
  • I create a ArrayList where I will save the objects that will be created with the fields received through the form
  • I pass the flow (the list in my case) to the JSP, I go through it and I get the value. So far so good.
  • I re-enter the different values in the form and when I add it and go through the list again I see that the object previously entered in the list is no longer there.

Student Class:

package model;

import java.util.ArrayList;
import java.util.List;

public class Alumno {
    private String name;
    private String dni;
    private String exam;
    private double nota;

    public Alumno(String name, String dni, String exam, Double nota) {

        this.name = name;
        this.dni = dni;
        this.exam = exam;
        this.nota = nota;
    }

    @Override
    public String toString() {
        return "Alumno [name=" + name + ", dni=" + dni + ", exam=" + exam + ", nota=" + nota + "]";
    }

    // GETTERS AND SETERS
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDni() {
        return dni;
    }
    public void setDni(String dni) {
        this.dni = dni;
    }
    public String getExam() {
        return exam;
    }
    public void setExam(String exam) {
        this.exam = exam;
    }
    public double getNota() {
        return nota;
    }
    public void setNota(double nota) {
        this.nota = nota;
    }
}

Driver:

package control;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Alumno;

/**
 * Servlet implementation class Controlador
 */
@WebServlet("/Controlador")
public class Controlador extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Controlador() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());

        // Recojo lops parámetros del formulrio

        String nombre = request.getParameter("nombre");
        String dni = request.getParameter("dni");
        String exam = request.getParameter("examen");
        Double nota = Double.parseDouble(request.getParameter("nota"));

        // Creo un ARRAYLIST de Alumnos
        List<Alumno> listaAlumnos = new ArrayList<Alumno>();

        // Añado varios objetos Alumno a la lista
        listaAlumnos.add(new Alumno("Luis","56567878g", "MATE", 7.2));
        listaAlumnos.add(new Alumno("Manu","56546878g", "Lengua", 5.4));
        listaAlumnos.add(new Alumno("Jorge","56569878g", "Inglés", 6.2));
        listaAlumnos.add(new Alumno("Col","5656709g", "Informática", 0.2));


        // Añado los objeto Alumno a la lista   OJOOOOOOOO
        listaAlumnos.add(new Alumno(nombre, dni, exam, nota));  // Aquí creo un objeto alumno con los datos introducidos en el formulario

        // Dejo la lista en el request
        request.setAttribute("listaAlumnos", listaAlumnos);

        // Le paso el flujo a la jsp
         request.getRequestDispatcher("/Presentacion.jsp").forward(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
}

JSP:

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

<!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=UTF-8">
<title>Datos de los alumnos registrados</title>
</head>

<body>
    <h1>Datos de los alumnos</h1>
    <%
        // El problema es que en la lista 
        // solo me esta guardando un valor y luego vuelve a empezar de 0 
        // Creo una lista y le agrego la que tenía en el REQUEST
        ArrayList<Alumno> listaAlumnos = (ArrayList<Alumno>) request.getAttribute("listaAlumnos");
    %>   
    <% 
    for(int i = 0; i < listaAlumnos.size(); i++) {
    %>
<ul>
    <li><% out.println(listaAlumnos.get(i)); %></li>
    <%} %>
</ul>

    <a href="index.html">Añadir mas alumnos</a>
</body>
</html>
    
asked by Lois 29.06.2018 в 19:32
source

1 answer

0

The request only "lives" during the processing of an HTTP request. When the JSP finishes generating the HTML, the request ends and the request disappears. The next call starts with no values in attribute .

If you want it to last between calls, you can save the values in HttpSession , which is associated with the user's web session.

The problem with the session is that the user can open several browser windows, and then the activity of all the windows would be written in the same session , crushing. For that reason, it would be convenient that when calling the servlet for the first time a unique id was generated, and the attributes in the session were saved with that id (eg session.getAttribute("listaAlumnos" + id); ). You would have to enter that id in the form (as a hidden field, for example), so that the servlet can retrieve it to get the corresponding attributes from session .

    
answered by 29.06.2018 в 20:29