La idea es enviar a la vista una variable que contenga un ArrayList<User>, para iterar sobre ella.
Controlador Principal
Código:
Objeto Userpackage com.springapp.mvc; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.ArrayList; @Controller public class HelloController { ArrayList<User> users = new ArrayList<User>(); public void addUsers(String name, String lastName){ User user = new User(); user.setName(name); user.setLastName(lastName); this.users.add(user); } public ArrayList<User> getUsers(){ return this.users; } public void setUsers(){ this.addUsers("romel","gomez"); this.addUsers("rudy","gomez"); } @RequestMapping("/users") public String users(ModelMap model){ this.setUsers(); model.addAttribute("variable",this.getUsers()); return "users"; } }
Código:
package com.springapp.mvc; /** * User class * User: romel * Date: 11/05/13 * Time: 12:08 PM */ public class User { public String name; public String lastName; public void setName(String name){ this.name = name; } public void setLastName(String lastName){ this.lastName = lastName; } public String getName(){ return this.name; } public String getLastName(){ return this.lastName; } }
Yo quisiera saber como obtener la variable para hacer algo como esto. Vale destacar que no me reconoce $variable como variable valida.
users.jsp
Código:
<%@ page import="com.springapp.mvc.User" %> <%@ page import="java.util.ArrayList" %> <%-- Users view User: romel Date: 11/05/13 Time: 12:29 PM --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title></title> </head> <body> <% for(ArrayList<User> data:$variable){ System.out.println("Nombre: "+data.name+", Apellido:"+data.lastName); } %> </body> </html>
saludos