Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Tutorial de Jakarta Struts
Tutorial de Jakarta Struts
Qu es Struts ?
n
n
n
Qu proporciona Struts ?
n
n
View Helpers
La mayor parte de las que se necesitan en una situacin real
Implementa javax.sql.DataSource
org.apache.struts.action.ActionServlet
0..n
# doGet
# doPost
<<use>>
org.apache.struts.action.Action
+ perform
<<instantiate>>
org.apache.struts.action.ActionForm
+ reset
+ validate
Action1
ActionN
...
ActionForm1
ActionFormN
...
<<use>>
ActionServlet
n
n
Clases ActionForm
n
Fichero de configuracin
n
n
n
n
n
Acciones JSP
n
Bean
n
HTML
n
Logic
n
n
Template
n
n
Modelo
n
Controlador
n
n
n
Vista
n
n
Demo Portal-3 (y 3)
Clic en Logout
Terminar y lanzar el navegador dos das ms tarde
Estructura de paquetes
es.udc.fbellas.j2ee.util.struts.action
es.udc.fbellas.j2ee.strutstutorial.portal3
http
controller
actions
view
actionforms
messages
model
userfacade
delegate
exceptions
Comentarios
n
WEB-INF/Struts
n
WEB-INF/lib
Internacionalizacin de mensajes
WEB-INF/web.xml (1)
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<distributable/>
<!-- ========================= Servlets ========================= -->
<!-- == Standard Action Servlet Configuration (with debugging) == -->
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servletclass>
WEB-INF/web.xml (2)
<init-param>
<param-name>application</param-name>
<param-value>es.udc.fbellas.j2ee.strutstutorial.portal3.http.
view.messages.Messages</param-value>
</init-param>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/Struts/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
WEB-INF/web.xml (3)
<!-- ================== Servlet mapping ========================== -->
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- ========================= Session ========================== -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<!-- ======================= Welcome page ======================= -->
<welcome-file-list>
<welcome-file>Index.jsp</welcome-file>
</welcome-file-list>
WEB-INF/web.xml (y 4)
<!-- ================= Struts Tag Library Descriptors ============ -->
<taglib>
<taglib-uri>/struts-bean.tld</taglib-uri>
<taglib-location>/WEB-INF/Struts/struts-bean.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/struts-html.tld</taglib-uri>
<taglib-location>/WEB-INF/Struts/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/struts-logic.tld</taglib-uri>
<taglib-location>/WEB-INF/Struts/struts-logic.tld</taglib-location>
</taglib>
</web-app>
Comentarios (1)
n
Servlet org.apache.struts.actions.ActionServlet
n
init-param
n
n
load-on-startup
n
Parmetros de inicializacin
n
n
Comentarios (2)
n
Servlet org.apache.struts.actions.ActionServlet
n
config
n
debug
n
detail
n
Comentarios (y 3)
n
WEB-INF/Struts/struts-config.xml (1)
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config
PUBLIC "-//Apache Software Foundation//DTD Struts Configuration
1.0//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd">
<struts-config>
WEB-INF/Struts/struts-config.xml (2)
<!-- ============ Global Forward Definitions ====================== -->
<global-forwards>
<forward name="MainPage" path="/MainPage.do" redirect="true"/>
<forward name="InternalError" path="/InternalError.jsp"
redirect="true"/>
</global-forwards>
<!-- ============ Action Mapping Definitions ====================== -->
<action-mappings>
<action path="/MainPage"
type="es.udc.fbellas.j2ee.strutstutorial.portal3.http.controller.
actions.MainPageAction">
<forward name="ShowMainPage" path="/MainPage.jsp"/>
</action>
<action path="/Login"
type="es.udc.fbellas.j2ee.strutstutorial.portal3.http.controller.
actions.LoginAction"
name="loginForm"
scope="request"
input="/Login.jsp"
validate="true"/>
WEB-INF/Struts/struts-config.xml (y 3)
<action path="/Logout"
type="es.udc.fbellas.j2ee.strutstutorial.portal3.http.controller.
actions.LogoutAction"/>
<!-- =================================================================
The standard administrative actions available with Struts. These
must be either omitted or protected by security in a real
application deployment.
================================================================ -->
<action path="/admin/addFormBean"
type="org.apache.struts.actions.AddFormBeanAction"/>
...
<action path="/admin/removeMapping"
type="org.apache.struts.actions.RemoveMappingAction"/>
</action-mappings>
</struts-config>
Comentarios (1)
n
n
n
n
Comentarios (y 2)
n
action
n
n
n
n
n
En general, request
En general, true
WEB-INF/classes/es/.../Messages.properties (1)
Buttons.login=Login
ErrorMessages.loginName.notFound=Login name not found
ErrorMessages.mandatoryField=Mandatory field
ErrorMessages.password.incorrect=Incorrect password
ErrorMessages.retry=Please, check if the operation has been performed, \
and retry if necessary
errors.footer=</b></font>
errors.header=<font color="red"><b>
InternalError.title=Internal error
WEB-INF/classes/es/.../Messages.properties (y 2)
Login.loginName=Login name
Login.password=Password
Login.rememberMyPassword=Remember my password (cookies must be enabled)
Login.title=Portal-3 login form
MainPage.hello=Hello
MainPage.login=Login
MainPage.logout=Logout
MainPage.title=Portal-3 main page
MainPage.welcome=Welcome to Portal-3
Comentarios (1)
n
Messages.properties
n
Messages_xx.properties
n
n
en: Ingls
es: Espaol
gl: Gallego
Etc.
n
n
Comentarios (2)
n
es.udc.fbellas.j2ee.strutstutorial.portal3.model.userfacade.delegate
UserFacadeDelegate
+ UserFacadeDelegate()
+ login(loginName : String, password : String, passwordIsEncrypted : boolean) : void
es.udc.fbellas.j2ee.util.struts.action (1)
Action
(from action)
DefaultAction
+ perform(m : ActionMapping, f : ActionForm, rq : HttpServletRequest, rp : HttpServletResponse) : ActionForward
# doPerform(m : ActionMapping, f : ActionForm, rq : HttpServletRequest, rp : HttpServletResponse) : ActionForward
# doOnInternalError(m : ActionMapping, f : ActionForm, rq : HttpServletRequest, rp : HttpServletResponse) : ActionForward
PropertyValidator
es.udc.fbellas.j2ee.util.struts.action (y 2)
n
DefaultAction
n
Problema
n
PropertyValidator
n
es.udc.fbellas.j2ee.util.struts.action.DefaultAction (1)
package es.udc.fbellas.j2ee.util.struts.action;
import
import
import
import
import
import
import
import
import
import
import
java.io.IOException;
javax.servlet.ServletContext;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
javax.servlet.ServletException;
org.apache.struts.action.Action;
org.apache.struts.action.ActionMapping;
org.apache.struts.action.ActionForm;
org.apache.struts.action.ActionForward;
org.apache.struts.action.ActionError;
org.apache.struts.action.ActionErrors;
import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
es.udc.fbellas.j2ee.util.struts.action.DefaultAction (2)
public abstract class DefaultAction extends Action {
public ActionForward perform(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
try {
return doPerform(mapping, form, request, response);
} catch (InternalErrorException e) {
return doOnInternalErrorException(mapping, form, request,
response, e);
}
}
protected abstract ActionForward doPerform(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException, InternalErrorException;
es.udc.fbellas.j2ee.util.struts.action.DefaultAction (y 3)
protected ActionForward doOnInternalErrorException(
ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response,
InternalErrorException internalErrorException)
throws IOException, ServletException {
/*
* Log error, even with debug level <= 0, because it is a
* severe error.
*/
ServletContext servletContext =
servlet.getServletConfig().getServletContext();
servletContext.log(internalErrorException.getMessage(),
internalErrorException);
/* Redirect to input page. */
return mapping.findForward("InternalError");
}
}
es.udc.fbellas.j2ee.util.struts.action.PropertyValidator (1)
es.udc.fbellas.j2ee.util.struts.action.PropertyValidator (2)
try {
propertyValueAsLong =
new Long(propertyValue).longValue();
if ( (propertyValueAsLong < lowerValidLimit) ||
(propertyValueAsLong > upperValidLimit) ) {
propertyValueIsCorrect = false;
}
} catch (NumberFormatException e) {
propertyValueIsCorrect = false;
}
if (!propertyValueIsCorrect) {
errors.add(propertyName,
new ActionError(INCORRECT_VALUE));
}
}
return propertyValueAsLong;
}
es.udc.fbellas.j2ee.util.struts.action.PropertyValidator (y 3)
public final static boolean validateMandatory(ActionErrors errors,
String propertyName, String propertyValue) {
if ((propertyValue == null) || (propertyValue.length() == 0)) {
errors.add(propertyName, new ActionError(MANDATORY_FIELD));
return false;
} else {
return true;
}
}
Comentarios
n
org.apache.struts.action.ActionMapping
n
org.apache.struts.action.ActionErrors
n
Permite acceder a los valores configurados en strutsconfig.xml para la accin en ejecucin (inclusive a los
forwards globales)
Juega el papel del mapa de errores que hemos empleado en
apartado anteriores
El mensaje de error es un
org.apache.struts.action.ActionError, que
dispone de un constructor que permite especificar el
identificador del mensaje de error (en
Messages.properties)
org.apache.struts.action.ActionForward
n
n
es.udc.fbellas.j2ee.strutstutorial.portal3.http.view.actionforms.LoginForm (1)
es.udc.fbellas.j2ee.strutstutorial.portal3.http.view.actionforms.LoginForm (2)
es.udc.fbellas.j2ee.strutstutorial.portal3.http.view.actionforms.LoginForm (y 3)
public void reset(ActionMapping mapping, HttpServletRequest request) {
reset();
}
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
PropertyValidator.validateMandatory(errors, "loginName",loginName);
PropertyValidator.validateMandatory(errors, "password", password);
return errors;
}
private void reset() {
loginName = null;
password = null;
rememberMyPassword = false;
}
}
Comentarios
n
LoginForm
n
reset
n
validate
n
es.udc.fbellas.j2ee.strutstutorial.portal3.http.controller.actions
DefaultAction
(from action)
MainPageAction
<<use>>
LoginAction
<<use>>
LogoutAction
<<use>>
LoginManager
<<use>>
UserFacadeDelegate
(from delegate)
es.udc.fbellas.j2ee.strutstutorial.portal3.http.controller.actions.LoginAction (1)
public class LoginAction extends DefaultAction {
public ActionForward doPerform(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException, InternalErrorException {
/* Get data. */
LoginForm loginForm = (LoginForm) form;
String loginName = loginForm.getLoginName();
String password = loginForm.getPassword();
boolean rememberMyPassword = loginForm.getRememberMyPassword();
/* Do login. */
ActionErrors errors = new ActionErrors();
es.udc.fbellas.j2ee.strutstutorial.portal3.http.controller.actions.LoginAction (y 2)
try {
LoginManager.login(request, response, loginName, password,
rememberMyPassword);
} catch (InstanceNotFoundException e) {
errors.add("loginName", new ActionError(
"ErrorMessages.loginName.notFound"));
} catch (IncorrectPasswordException e) {
errors.add("password", new ActionError(
"ErrorMessages.password.incorrect"));
}
/* Return ActionForward. */
if (errors.empty()) {
return mapping.findForward("MainPage");
} else {
saveErrors(request, errors);
return new ActionForward(mapping.getInput());
}
}
}
es.udc.fbellas.j2ee.strutstutorial.portal3.http.controller.actions.LogoutAction
public class LogoutAction extends DefaultAction {
public ActionForward doPerform(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException, InternalErrorException {
/* Do logout. */
LoginManager.logout(request, response);
/* Return ActionForward. */
return mapping.findForward("MainPage");
}
}
Comentarios
n
MainPage.jsp (1)
<%@ taglib uri="/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/struts-html.tld" prefix="html" %>
<%@ taglib uri="/struts-logic.tld" prefix="logic" %>
<html>
<head>
<title><bean:message key="MainPage.title"/></title>
</head>
<body text="#000000" bgcolor="#ffffff" link="#000ee0" vlink="#551a8b"
alink="#000ee0">
MainPage.jsp (2)
<%-- Welcome --%>
<h1>
<logic:notPresent name="loginName" scope="session">
<bean:message key="MainPage.welcome"/>
</logic:notPresent>
<logic:present name="loginName" scope="session">
<bean:message key="MainPage.hello"/>
<bean:write name="loginName" scope="session"/>
</logic:present>
</h1>
<%-- Some <br>'s --%>
<br>
<br>
<br>
MainPage.jsp (y 3)
<%-- Links to Login or Logout --%>
<logic:notPresent name="loginName" scope="session">
<html:link href="Login.jsp">
<bean:message key="MainPage.login"/>
</html:link>
</logic:notPresent>
<logic:present name="loginName" scope="session">
<html:link href="Logout.do">
<bean:message key="MainPage.logout"/>
</html:link>
</logic:present>
</body>
</html>
Login.jsp (1)
<%@ taglib uri="/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/struts-html.tld" prefix="html" %>
<html>
<head>
<title><bean:message key="Login.title"/></title>
</head>
<body text="#000000" bgcolor="#ffffff">
<html:form action="Login.do">
<table width="100%" border="0" align="center" cellspacing="12">
<%-- Login name --%>
<tr>
<th align="right" width="50%">
<bean:message key="Login.loginName"/>
</th>
<td align="left">
<html:text property="loginName" size="16" maxlength="16"/>
<html:errors property="loginName"/>
</td>
</tr>
Login.jsp (2)
<%-- Password --%>
<tr>
<th align="right" width="50%">
<bean:message key="Login.password"/>
</th>
<td align="left">
<html:password property="password" size="16"
maxlength="16"/>
<html:errors property="password"/>
</td>
</tr>
<%-- Remember my password --%>
<tr>
<th align="right" width="50%">
<bean:message key="Login.rememberMyPassword"/>
</th>
<td align="left">
<html:checkbox property="rememberMyPassword"/>
</td>
</tr>
Login.jsp (y 3)
<%-- Login button --%>
<tr>
<td width="50%"></td>
<td align="left" width="50%">
<html:submit>
<bean:message key="Buttons.login"/>
</html:submit>
</td>
</tr>
</table>
</html:form>
</body>
</html>
Comentarios
n
html:errors
n
InternalError.jsp
<%@ taglib uri="/struts-bean.tld" prefix="bean" %>
<html>
<head>
<title><bean:message key="InternalError.title"/></title>
</head>
<body text="#000000" bgcolor="#ffffff">
<h3><div align="center"><font color="red">
<bean:message key="InternalError.title"/>.
<bean:message key="ErrorMessages.retry"/>
</font></div></h3>
</body>
</html>
Un pequeo problema
n
Situacin
n
n
n
En realidad es Index.jsp
Un solucin
n
Index.jsp
n
n
MainPageAction
n
LoginManager.getLoginName y forward a
/MainPage.jsp
Pgina de bienvenida
Hace un forward a /MainPage.do => se ejecuta
MainPageAction
es.udc.fbellas.j2ee.strutstutorial.portal3.http.controller.actions.MainPageAction
public class MainPageAction extends DefaultAction {
public ActionForward doPerform(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException, InternalErrorException {
/*
* "LoginManager.getLoginName" creates an appropriate session
* if the session had expired, or the user had not logged in,
* but he/she had selected "remember my password" in the last
* login.
*/
LoginManager.getLoginName(request);
/* Return ActionForward. */
return mapping.findForward("ShowMainPage");
}
}
Index.jsp
<jsp:forward page="MainPage.do"/>