elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: ¿Eres nuevo? ¿Tienes dudas acerca del funcionamiento de la comunidad? Lee las Reglas Generales


  Mostrar Temas
Páginas: [1]
1  Programación / Java / Editar elementos en un ArrayList en: 8 Enero 2017, 18:06 pm
Hola a todos, espero que puedan ayudarme.



Tengo un archivo index.jsp que recoge unos datos (un numero y un múltiplo)

Código
  1. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  2. <%@page contentType="text/html" pageEncoding="UTF-8" %>
  3. <!DOCTYPE html>
  4. <html>
  5.    <head>
  6.        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7.        <title>Bonus</title>
  8.    </head>
  9.    <body>
  10.        <h1>Bonus</h1>
  11.        <form method="get" action="/WebApplication4/NewServlet">
  12.            <table>
  13.                <tr>
  14.                    <th>Numero</th>
  15.                    <th>Multiplo</th>
  16.                </tr>
  17.                <c:forEach var="i" begin="0" end="2" step="1">
  18.                    <tr>
  19.                        <td><input type="text" value="" name="numero"/></td>
  20.                        <td><input type="text" value="" name="multiplo"/></td>
  21.                    </tr>
  22.                </c:forEach>
  23.            </table>
  24.            <button type="submit">Enviar</button>
  25.            <button type="reset">Reiniciar</button>
  26.        </form>
  27.    </body>
  28. </html>
  29.  



A continuación, paso estos números a un Servlet (NewServlet.java)
Código
  1. package servlet;
  2.  
  3. import java.io.IOException;
  4. import java.util.ArrayList;
  5. import java.util.Enumeration;
  6. import java.util.HashMap;
  7. import java.util.List;
  8. import java.util.Map;
  9. import javax.servlet.ServletException;
  10. import javax.servlet.annotation.WebServlet;
  11. import javax.servlet.http.HttpServlet;
  12. import javax.servlet.http.HttpServletRequest;
  13. import javax.servlet.http.HttpServletResponse;
  14.  
  15. @WebServlet(name = "NewServlet", urlPatterns = {"/NewServlet"})
  16. public class NewServlet extends HttpServlet {
  17.  
  18.    public double getBonus(String multiplo) {
  19.        return Double.parseDouble(multiplo) * 100.0;
  20.    }
  21.  
  22.    /**
  23.      * Processes requests for both HTTP
  24.      * <code>GET</code> and
  25.      * <code>POST</code> methods.
  26.      *
  27.      * @param request servlet request
  28.      * @param response servlet response
  29.      * @throws ServletException if a servlet-specific error occurs
  30.      * @throws IOException if an I/O error occurs
  31.      */
  32.    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  33.            throws ServletException, IOException {
  34.        response.setContentType("text/html;charset=UTF-8");
  35.  
  36.        int k = 0;
  37.        Enumeration Data = request.getParameterNames();
  38.        Map<String, String[]> Element = new HashMap<String, String[]>();
  39.        ArrayList<String> myList = new ArrayList();
  40.  
  41.        while (Data.hasMoreElements()) {
  42.            String Param = (String)Data.nextElement();
  43.            String[] ValeursParam = request.getParameterValues(Param);
  44.            myList.add(Param);
  45.            Element.put(Param, request.getParameterValues(Param));
  46.            k++;
  47.        }
  48.        List<HashMap<String, String>> List = new ArrayList<HashMap<String, String>>();
  49.  
  50.        int i = 0;
  51.        for(i=0; i<Element.get(myList.get(0)).length; i++) {
  52.            HashMap<String, String> ElementS = new HashMap<String, String>();
  53.            for(int j=0; j<k; j++) {
  54.                ElementS.put(myList.get(j), Element.get(myList.get(j))[i].toString());
  55.            }
  56.            List.add(ElementS);
  57.        }
  58.  
  59.        Beans servlet = new Beans();
  60.        servlet.setListBeans(List);
  61.  
  62.        request.setAttribute("Beans", servlet);
  63.        request.getRequestDispatcher("bonus.jsp").forward(request, response);
  64.    }
  65.  
  66.    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
  67.    /**
  68.      * Handles the HTTP
  69.      * <code>GET</code> method.
  70.      *
  71.      * @param request servlet request
  72.      * @param response servlet response
  73.      * @throws ServletException if a servlet-specific error occurs
  74.      * @throws IOException if an I/O error occurs
  75.      */
  76.    @Override
  77.    protected void doGet(HttpServletRequest request, HttpServletResponse response)
  78.            throws ServletException, IOException {
  79.        processRequest(request, response);
  80.    }
  81.  
  82.    /**
  83.      * Handles the HTTP
  84.      * <code>POST</code> method.
  85.      *
  86.      * @param request servlet request
  87.      * @param response servlet response
  88.      * @throws ServletException if a servlet-specific error occurs
  89.      * @throws IOException if an I/O error occurs
  90.      */
  91.    @Override
  92.    protected void doPost(HttpServletRequest request, HttpServletResponse response)
  93.            throws ServletException, IOException {
  94.        processRequest(request, response);
  95.    }
  96.  
  97.    /**
  98.      * Returns a short description of the servlet.
  99.      *
  100.      * @return a String containing servlet description
  101.      */
  102.    @Override
  103.    public String getServletInfo() {
  104.        return "Short description";
  105.    }// </editor-fold>
  106.  
  107. }
  108.  



Los datos del array los paso a un Beans

Código
  1. package servlet;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.HashMap;
  5. import java.util.List;
  6.  
  7. public class Beans {
  8.  
  9.    private List<HashMap<String, String>> ListBeans;
  10.  
  11.    public List<HashMap<String, String>> getListBeans() {
  12.        return this.ListBeans;
  13.    }
  14.  
  15.    public void setListBeans(List<HashMap<String, String>> ListBeans) {
  16.        this.ListBeans = ListBeans;
  17.    }
  18.  
  19. }
  20.  



Y finalmente otro archivo .jsp los muestra

Código
  1. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  2. <%@page contentType="text/html" pageEncoding="UTF-8" %>
  3. <!DOCTYPE html>
  4. <html>
  5.    <head>
  6.        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7.        <title>Bonus</title>
  8.    </head>
  9.    <body>
  10.        <h1>Bonus</h1>
  11.        <c:forEach items="${Beans.listBeans}" var="ElementS" varStatus="status">
  12.            <div class="ElementS">
  13.                <div class="numeroElementS">
  14.                    Numero: <c:out value="${ !empty ElementS['numero'] ? ElementS['numero'] : 'Vacio' }" />
  15.                </div>
  16.                <div class="bonusElementS">
  17.                    Bonus: <c:out value="${ !empty ElementS['multiplo'] ? ElementS['multiplo'] : 'Vacio' }" />
  18.                </div>
  19.            </div>
  20.        </c:forEach>
  21.    </body>
  22. </html>
  23.  

Pues bien, quiero que en el archivo Servlet, los valores "múltiplo" sean editados (necesito multiplicarlos por otro valor) y sea este resultado (llamado bonus) y no el "múltiplo", lo que muestre el archivo bonus.jsp

Espero que hayan entendido el problema.

Gracias por su ayuda.

2  Programación / Java / Obtener datos de un ArrayList [Editado] en: 12 Diciembre 2016, 23:26 pm
Hola, soy nuevo aquí. Antes de nada comentar que estoy empezando con java y me cuesta bastante.

Os expongo el problema:

Debo hacer una aplicación web que recoja unos datos (.jsp) los pase a un servlet, este a un beans para encapsular los objetos en uno solo y la salida de los datos la muestre otra página .jsp



Index.jsp

Código
  1. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  2. <%@page contentType="text/html" pageEncoding="UTF-8"%>
  3. <!DOCTYPE html>
  4. <html>
  5.    <head>
  6.        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7.        <title>Bonus Calculation</title>
  8.    </head>
  9.    <body>
  10.        <h1>Bonus Calculation</h1>
  11.        <form method="get" action="/WebApplication4/NewServlet">
  12.            <table>
  13.                <tr>
  14.                    <th>Numero SSN</th>
  15.                    <th>Multiple</th>
  16.                </tr>
  17.                <c:forEach var="i" begin="0" end="2" step="1">
  18.                    <tr>
  19.                        <td><input type="text" value="" name="nombre"/></td>
  20.                        <td><input type="text" value="" name="multiplier"/></td>
  21.                    </tr>
  22.                </c:forEach>
  23.            </table>
  24.            <button type="submit">Envoyer</button>
  25.            <button type="reset">Réinitialiser</button>
  26.        </form>
  27.    </body>
  28. </html>
  29.  



NewServlet.java
(Aquí es donde tengo el problema y no se como tomar los datos, porque he probado de diferentes formas)

Código
  1. package servlet;
  2.  
  3. import java.io.IOException;
  4. import java.util.ArrayList;
  5. import java.util.Enumeration;
  6. import java.util.HashMap;
  7. import java.util.LinkedHashMap;
  8. import java.util.List;
  9. import java.util.Map;
  10. import javax.servlet.ServletException;
  11. import javax.servlet.annotation.WebServlet;
  12. import javax.servlet.http.HttpServlet;
  13. import javax.servlet.http.HttpServletRequest;
  14. import javax.servlet.http.HttpServletResponse;
  15.  
  16. @WebServlet(name = "NewServlet", urlPatterns = {"/NewServlet"})
  17. public class NewServlet extends HttpServlet {
  18.  
  19.    public double getBonus(String multiplier) {
  20.        return Double.parseDouble(multiplier) * 100.0;
  21.    }
  22.  
  23.    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  24.            throws ServletException, IOException {
  25.        response.setContentType("text/html;charset=UTF-8");
  26.  
  27.        int counter = 0;
  28.        Enumeration Data = request.getParameterNames();
  29.        Map<String, String[]> calcul = new HashMap<String, String[]>();
  30.        ArrayList<String> myList = new ArrayList();
  31.  
  32.        while (Data.hasMoreElements()) {
  33.            String Param = (String)Data.nextElement();
  34.            myList.add(Param);
  35.            calcul.put(Param, request.getParameterValues(Param));
  36.            counter++;
  37.        }
  38.        List<Map<String, String>> List = new ArrayList<Map<String, String>>();
  39.  
  40.        for(int i=0; i<calcul.get(myList.get(0)).length; i++) {
  41.            Map<String, String> calcul2 = new HashMap<String, String>();
  42.            for(int j=0; j<counter; j++) {
  43.                calcul2.put(myList.get(j), calcul.get(myList.get(j))[i].toString());
  44.            }
  45.            List.add(calcul2);
  46.        }
  47. /*AQUI ES DONDE DEBO EXTRAER LOS DATOS DEL ARRAY PARA PASARLOS AL BEANS*/
  48.  
  49.        Beans servlet = new Beans();
  50.        servlet.setNombre(nombre);
  51.        servlet.setBonus(bonus);
  52.  
  53.        request.setAttribute("Beans", servlet);
  54.        request.getRequestDispatcher("bonus.jsp").forward(request, response);
  55.    }
  56. }
  57.  



Beans.java

Código
  1. package servlet;
  2.  
  3. public class Beans {
  4.  
  5.    private String nombre, bonus;
  6.  
  7.    public String getNombre(){
  8.        return this.nombre;
  9.    }
  10.    public void setNombre(String nombre) {
  11.        this.nombre = nombre;
  12.    }
  13.    public String getBonus(){
  14.        return this.bonus;
  15.    }
  16.    public void setBonus(String bonus) {
  17.        this.bonus = bonus;
  18.    }
  19. }
  20.  



Bonus.jsp

Código
  1. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  2. <%@page contentType="text/html" pageEncoding="UTF-8"%>
  3. <!DOCTYPE html>
  4. <html>
  5.    <head>
  6.        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7.        <title>JSP Page</title>
  8.    </head>
  9.    <body>
  10.        <h1>Bonus Calculation:</h1>
  11.        <c:forEach items="${List}" var="calcul">
  12.            <div class="calcul">
  13.                <div class="nombreCalcul">
  14.                    <c:out value="${calcul['nombre']}" />
  15.                </div>
  16.                <div class="bonusCalcul">
  17.                    <c:out value="${calcul['bonus']}" />
  18.                </div>
  19.            </div>
  20.        </c:forEach>
  21.    </body>
  22. </html>
  23.  



Espero que puedan ayudarme, gracias.

Editado
Páginas: [1]
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines