Professional Documents
Culture Documents
0, JSTL y Apache
Struts
Lenguaje de expresiones
Documentos JSP
JSP 2.0 (y 2)
Ejemplo
Ejemplo
Expresiones y literales
Ejemplos
${user.firstName} = user.getFirstName()
${user.address.city} = user.getAddress().getCity()
${user.preferencesMap["shipping"]} =
user.getPreferencesMap().get("shipping")
${user.preferencesList[0]} = user.getPreferencesList().get(0)
${user.firstName} es
equivalente a ${user["firstName"]}
${user.preferencesMap["shipping"]} es equivalente a
${user.preferencesMap.shipping}
${user.preferencesMap["book.fiction"]} es equivalente
user.getPreferencesMap().get("book.fiction")
${user.preferencesMap[product.category]} es equivalente
user.getPreferencesMap().get(product.getCategory())
Objetos implcitos
Entre otros
pageScope (Map)
requestScope (Map)
sessionScope (Map)
applicationScope (Map)
param (Map que mapea nombres de parmetros univaluados a
String)
paramValues (Map que mapea nombres de parmetros
multivaluados a String[])
Ejemplo
Lenguaje de expresiones (y 5)
Literales
Operadores
Ejemplos
JSTL (1)
JSTL (2)
Tags en JSTL
Core
I18n (internacionalizacin)
Control de flujo
Soporte para URLs
Soporte para internacionalizacin: establecimiento del Locale,
generacin de mensajes, formateo de nmeros, cantidades
monetarias, fechas, etc.
XML
JSTL (y 3)
Acceso a BDs
Funciones
Qu es Struts ?
Qu proporciona Struts ?
org.apache.struts.action.ActionServlet
0..n
# doGet
# doPost
org.apache.struts.action.Action
+ execute
<<use>> <<instantiate>>
org.apache.struts.action.ActionForm
+ reset
+ validate
ActionForm1
Action1
...
...
ActionFormN
<<use>>
ActionN
ActionServlet
Clases ActionForm
Fichero de configuracin
Bean
Logic
HTML
Tiles
Reemplaza a Template
Modelo
Controlador
Vista
Clic en Logout
Terminar y lanzar el navegador dos das ms tarde
CSS
Demo Portal-3 (y 5)
CSS (cont)
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 (1)
Documentos JSP
WEB-INF/Struts
Comentarios (y 2)
WEB-INF/lib
Internacionalizacin de mensajes
WEB-INF/web.xml (1)
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<distributable/>
<!-- =============== Standard TagLibs configuration ============= -->
<context-param>
<param-name>javax.servlet.jsp.jstl.fmt.localizationContext
</param-name>
<param-value>es.udc.fbellas.j2ee.strutstutorial.portal3.http.
view.messages.Messages</param-value>
</context-param>
WEB-INF/web.xml (2)
<!-- ================= Front controller configuration =========== -->
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet
</servlet-class>
<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 (y 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.jspx</welcome-file>
</welcome-file-list>
</web-app>
Comentarios (1)
context-param
Comentarios (2)
Servlet org.apache.struts.actions.ActionServlet
init-param
load-on-startup
Comentarios (y 3)
Servlet org.apache.struts.actions.ActionServlet
Parmetros de inicializacin
config
detail
debug
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.2//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_2.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.jspx"
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.jspx"/>
</action>
<action path="/Login"
type="es.udc.fbellas.j2ee.strutstutorial.portal3.http.
controller.actions.LoginAction"
name="loginForm" scope="request" input="/Login.jspx"
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-mappings>
<!-- ============ Message Resources Definitions =================== -->
<message-resources parameter="es.udc.fbellas.j2ee.strutstutorial.
portal3.http.view.messages.Messages"/>
</struts-config>
Comentarios (1)
Comentarios (2)
Comentarios (3)
action
En general, request
En general, true
Comentarios (y 4)
message-resources
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=</span>
errors.header=<span class="errorMessage">
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)
Messages.properties
Messages_xx.properties
en: Ingls
es: Espaol
gl: Gallego
Etc
Comentarios (y 2)
es.udc.fbellas.j2ee.strutstutorial.portal3.model.userfacade.delegate
UserFac adeDelegate
+ UserFacadeDelegate()
+ login(l oginNam e : S tring, password : S t ri ng, pas swordIsE ncrypte d : boo lean) : void
es.udc.fbellas.j2ee.util.struts.action
A ction
(from action)
Def aul tA ct io n
+ execute(actionM apping, actionForm , request, response) : A ctionForward
# doE xecute(actionMapping, actionForm , request, response) : A ctionForward
# doOnInternalE rror(actionM apping, actionForm , request, response, internalE rrorE xception) : A ctionForw...
P rope rt yV alidat or
Comentarios
DefaultAction
Problema
PropertyValidator
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
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;
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 execute(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
try {
return doExecute(mapping, form, request, response);
} catch (Exception e) {// Any exception thrown by "doExecute",
// including instances of
// "RuntimeException".
return doOnException(mapping, form, request,
response, e);
}
}
protected abstract ActionForward doExecute(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException, InternalErrorException;
es.udc.fbellas.j2ee.util.struts.action.DefaultAction (y 3)
protected ActionForward doOnException(
ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response,
Exception exception)
throws IOException, ServletException {
/*
* Log error, even with debug level <= 0, because it is a
* severe error.
*/
ServletContext servletContext =
servlet.getServletConfig().getServletContext();
servletContext.log(exception.getMessage(), exception);
/* 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 ActionMessage(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 ActionMessage(MANDATORY_FIELD));
return false;
} else {
return true;
}
}
private final static boolean validateMandatory(ActionErrors errors,
String propertyName, String propertyValue, boolean mandatory) {
if (mandatory) {
return validateMandatory(errors, propertyName,
propertyValue);
} else {
return true;
}
}
// Resto de mtodos validateXXX => Anlogos ...
}
Comentarios
org.apache.struts.action.ActionMapping
Permite acceder a los valores configurados en strutsconfig.xml para la accin en ejecucin (inclusive a los forwards
globales)
org.apache.struts.action.ActionErrors
org.apache.struts.action.ActionForward
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
LoginForm
reset
validate
es.udc.fbellas.j2ee.strutstutorial.portal3.http.controller.actions
Defaul tAc tion
(from ac tion)
M ai nP ageA c t ion
LoginA c t ion
LogoutA c tion
LoginM anager
<< us e>>
Us erFacadeDelegate
(from delegate)
es.udc.fbellas.j2ee.strutstutorial.portal3.http.controller.actions.LoginAction (1)
public class LoginAction extends DefaultAction {
public ActionForward doExecute(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. */
ActionMessages errors = new ActionMessages();
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 ActionMessage(
"ErrorMessages.loginName.notFound"));
} catch (IncorrectPasswordException e) {
errors.add("password", new ActionMessage(
"ErrorMessages.password.incorrect"));
}
/* Return ActionForward. */
if (errors.isEmpty()) {
return mapping.findForward("MainPage");
} else {
saveErrors(request, errors);
return new ActionForward(mapping.getInput());
}
}
}
Comentarios
es.udc.fbellas.j2ee.strutstutorial.portal3.http.controller.actions.LogoutAction
public class LogoutAction extends DefaultAction {
public ActionForward doExecute(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException, InternalErrorException {
/* Do logout. */
LoginManager.logout(request, response);
/* Return ActionForward. */
return mapping.findForward("MainPage");
}
}
MainPage.jspx (1)
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:fmt="http://java.sun.com/jsp/jstl/fmt"
xmlns:html="http://struts.apache.org/tags-html"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<jsp:output doctype-root-element="html"
doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN"
doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
omit-xml-declaration="true" />
<jsp:directive.page contentType="text/html; charset=iso-8859-1" />
<head>
<title><fmt:message key="MainPage.title" /></title>
<c:url var="stylesURL" value="/css/styles.css" />
<link rel="StyleSheet" href="${stylesURL}"
type="text/css" media="all" />
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1" />
</head>
<body>
MainPage.jspx (2)
<!-- Welcome -->
<div id="header">
<c:choose>
<c:when test="${empty sessionScope.loginName}">
<fmt:message key="MainPage.welcome" />
</c:when>
<c:otherwise>
<fmt:message key="MainPage.hello" />
<c:out value=" ${sessionScope.loginName}" />
</c:otherwise>
</c:choose>
</div>
MainPage.jspx (y 3)
<!-- Links to Login or Logout -->
<p>
<c:choose>
<c:when test="${empty sessionScope.loginName}">
<c:url var="loginURL" value="Login.jspx" />
<a href="${loginURL}">
<fmt:message key="MainPage.login" />
</a>
</c:when>
<c:otherwise>
<html:link action="Logout.do">
<fmt:message key="MainPage.logout" />
</html:link>
</c:otherwise>
</c:choose>
</p>
</body>
</html>
Comentarios (1)
http://java.sun.com/JSP/Page (jsp)
http://java.sun.com/jsp/jstl/fmt (fmt)
http://struts.apache.org/tags-html (html)
http://java.sun.com/jsp/jstl/core (c)
Comentarios (2)
Comentarios (3)
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:fmt="http://java.sun.com/jsp/jstl/fmt"
xmlns:html="http://struts.apache.org/tags-html"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<html xmlns="http://www.w3.org/1999/xhtml">
Comentarios (4)
En MainPage.jspx se utiliza
<jsp:output doctype-root-element="html"
doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN"
doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
omit-xml-declaration="true" />
Comentarios (5)
Tags jsp:directive.XXX
Comentarios (6)
En el ejemplo se usa
Usar
Comentarios (7)
Usar
Comentarios (y 8)
html:link
Login.jspx (1)
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:fmt="http://java.sun.com/jsp/jstl/fmt"
xmlns:html="http://struts.apache.org/tags-html"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<jsp:output doctype-root-element="html"
doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN"
doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
omit-xml-declaration="true" />
<jsp:directive.page contentType="text/html; charset=iso-8859-1" />
<head>
<title><fmt:message key="Login.title" /></title>
<c:url var="stylesURL" value="/css/styles.css" />
<link rel="StyleSheet" href="${stylesURL}"
type="text/css" media="all" />
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1" />
</head>
<body>
Login.jspx (2)
<!-- Struts tags must render XHML -->
<html:xhtml/>
<!-- Print login form -->
<html:form action="Login.do">
<!-- Login name -->
<div class="field">
<span class="label">
<fmt:message key="Login.loginName" />
</span>
<span class="entry">
<html:text property="loginName" size="16" maxlength="16" />
<html:errors property="loginName" />
</span>
</div>
Login.jspx (3)
<!-- Password -->
<div class="field">
<span class="label">
<fmt:message key="Login.password" />
</span>
<span class="entry">
<html:password property="password" size="16"
maxlength="16" />
<html:errors property="password" />
</span>
</div>
<!-- Remember my password -->
<div class="field">
<span class="label">
<fmt:message key="Login.rememberMyPassword" />
</span>
<span class="entry">
<html:checkbox property="rememberMyPassword" />
</span>
</div>
Login.jspx (y 4)
<!-- Login button -->
<div class="button">
<html:submit><fmt:message key="Buttons.login" /></html:submit>
</div>
</html:form>
</body>
</html>
Comentarios (1)
html:xhtml
Comentarios (y 2)
html:errors
InternalError.jspx (1)
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:fmt="http://java.sun.com/jsp/jstl/fmt"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<jsp:output doctype-root-element="html"
doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN"
doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
omit-xml-declaration="true" />
<jsp:directive.page contentType="text/html; charset=iso-8859-1" />
<head>
<title><fmt:message key="InternalError.title" /></title>
<c:url var="stylesURL" value="/css/styles.css" />
<link rel="StyleSheet" href="${stylesURL}"
type="text/css" media="all" />
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1" />
</head>
<body>
InternalError.jspx (y 2)
<p>
<fmt:message key="InternalError.title" />.
<fmt:message key="ErrorMessages.retry" />
</p>
</body>
</html>
Un pequeo problema
Situacin
En realidad es Index.jspx
Se ejecuta MainPage.jspx
Una solucin
Index.jspx
MainPageAction
LoginManager.getLoginName y forward a
/MainPage.jspx
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 doExecute(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.jspx
<jsp:forward xmlns:jsp="http://java.sun.com/JSP/Page"
page="MainPage.do" />