Introducción
Ya hemos visto en el anterior post un poco de teoría
Struts2 - Action (profundizando)
Vamos a ver ahora un par de ejemplos, con las aproximaciones que hace Struts2 para el manejo de la info que viaja en la app. Es decir, esos Beans que se manejan en la aplicación, querremos usarlos de una u otra manera.
Las dos aproximaciones que tenemos son:
1. Object-backed action classes
2. ModelDriven action classes
Objetivo
Nuestro proyecto debe quedar algo por estilo. Recuerda que siempre lo tienes disponible desde mi enlace a GitHub.
Bean
Como hemos dicho, lo primero es que la información viaje a través de la aplicación, para lo cual vamos a hacer uso de un Bean de usuario.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | package com.mr.knight.beans; public class User { private String userID; private String password; private String userName; public String getUserID() { return userID; } public void setUserID(String userID) { this.userID = userID; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } } |
Primera aproximación. Object-backed Action Class
Vamos a ver las modificaciones que debemos realizar.
Lo primero es fijarnos que debemos una variable para manejar el Bean.
LoginObjectBackedAction.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | package com.mr.knight.struts2.action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.ResultPath; import org.apache.struts2.convention.annotation.Results; import com.mr.knight.beans.User; import com.opensymphony.xwork2.Action; @org.apache.struts2.convention.annotation.Action("loginObject") @Namespace("/User") @ResultPath("/") @Results({ @Result(name = "success", location = "homeObject.jsp"), @Result(name = "input", location = "loginObject.jsp") }) public class LoginObjectBackedAction implements Action { @Override public String execute() throws Exception { if ("jose".equals(getUser().getUserID()) && "admin".equals(getUser().getPassword())) { getUser().setUserName("Jose Caballero"); return SUCCESS; } else { return INPUT; } } private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } } |
A nivel de la vista, debemos referenciar esa misma variable, para aunque mal dicho, "inyectárselo" al JSP.
loginObject.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ taglib uri="/struts-tags" prefix="s"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Login Page</title> </head> <body> <h3>Welcome User, please login below</h3> <s:form action="loginObject"> <s:textfield name="user.userID" label="User Name"></s:textfield> <s:textfield name="user.password" label="Password" type="password"></s:textfield> <s:submit value="Login"></s:submit> </s:form> </body> </html> |
Vemos como para hacer referencia al Bean User, lo marcamos como tal, y luego referenciamos sus propiedades.
Segunda aproximación. ModelDriven Action Class
Para las Action ModelDriven, tenemos que implementar com.opensymphony.xwork2.ModelDriven. Esta interfaz es de tipo parametrizado utilizando genéricos de Java y necesitamos proporcionar el tipo como nuestra de la clase bean. La interfaz ModelDriven contiene sólo un método getModel () que necesitamos para implementar y devolver el Bean.
El otro punto importante a destacar es que el Action debe tener una variable de nivel de clase para el bean y necesitamos crear una instancia.
Esto se ve mejor con un ejemplo:
LoginModelDrivenAction.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | package com.mr.knight.struts2.action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.ResultPath; import org.apache.struts2.convention.annotation.Results; import com.mr.knight.beans.User; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; @org.apache.struts2.convention.annotation.Action("loginModelDriven") @Namespace("/User") @ResultPath("/") @Results({ @Result(name = "success", location = "homeModelDriven.jsp"), @Result(name = "input", location = "loginModelDriven.jsp") }) public class LoginModelDrivenAction extends ActionSupport implements Action, ModelDriven<User> { @Override public String execute() throws Exception { if ("jose".equals(user.getUserID()) && "admin".equals(user.getPassword())) { user.setUserName("Jose Caballero"); addActionMessage("Welcome Admin, do some work."); return SUCCESS; } else { addActionError("User name is not valid"); addActionError("Password is wrong"); return INPUT; } } @Override public User getModel() { return user; } private User user = new User(); } |
loginModelDriven.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | <%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%-- Using Struts2 Tags in JSP --%> <%@ taglib uri="/struts-tags" prefix="s"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Login Page</title> <!-- Adding CSS for Styling of error messages --> <style type="text/css"> .errorDiv { background-color: gray; border: 1px solid black; width: 400px; margin-bottom: 8px; } </style> </head> <body> <h3>Welcome User, please login below</h3> <s:if test="hasActionErrors()"> <div class="errorDiv"> <s:actionerror /> </div> </s:if> <s:form action="loginModelDriven"> <s:textfield name="userID" label="User Name"></s:textfield> <s:textfield name="password" label="Password" type="password"></s:textfield> <s:submit value="Login"></s:submit> </s:form> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | <%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%> <%@ taglib uri="/struts-tags" prefix="s"%> <!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=US-ASCII"> <title>Welcome Page</title> <style type="text/css"> .welcome { background-color: green; border: 1px solid black; width: 400px; } // ul.actionMessage is added by Struts2 API ul.actionMessage li { color: yellow; } </style> </head> <body> <h3>Example msg</h3> <s:if test="hasActionMessages()"> <div class="welcome"> <s:actionmessage /> </div> </s:if> <br> <br> <s:property value="getText('msg.welcome')" /> <s:property value="userName" /> </body> </html> |
Como podemos ver, es más cómodo no referencias a la variable del Action que tenemos con el Bean. Nos independiza un poco más del hecho de que sea uno u otro objeto el que la maneje.
Resumen
Si nos fijamos en ambos enfoques, el enfoque ModelDriven es fácil de implementar y mantener, ya que no requiere cambios en las páginas JSP.
Ahora cada cual...
No hay comentarios:
Publicar un comentario
Nota: solo los miembros de este blog pueden publicar comentarios.