12.11.08 1 basic struts architecture client server database request response control view model...
TRANSCRIPT
12.11.08 1
Basic Struts Architecture
Client ServerDatabase
Request
Response
Control
View
Model
Server
Struts Framework
12.11.08 2
Struts 2 flow (a bird eye view)
source: www.coreservlets.com; Jakarta Struts: Processing Requests with Action Objects Struts 1.2 Version
Request …/blah.action
Struts.xml
12.11.08 3
Struts 2 Lifecycle
Source: http://static.raibledesigns.com/repository/presentations/MigratingFromStruts1ToStruts2.pdf
12.11.08 4
Struts 2 – Behind the scenes
12.11.08 5
Struts 2 – Behind the scenes (Cont…)HttpServletRequest – Request goes to servlet container
Filters - various filters are applied
FilterDispatcher – required filter dispacher is called
ActionMapper –dispatcher consults mapper to invoke action or not
ActionProxy – control is passed to proxy and it consults configuration manager for appropriate action and settings and then creates invocation
ActionInvocation – calls interceptors before calling the Action
Interceptors – interceptors do preActions
ActionExecution – Action method is called
ResultsPreparation – result is rendered depending upon the action method response
Interceptors – interceptors are called in reverse order for postActions
Filters – response is passed through filters
HttpServletResponse – response is given to client
12.11.08 6
Hello World!
One time configuration Web.xml
Three steps process Create view (JSP) Create Action Class Map Action and view
12.11.08 7
Web.xml
Placed in WEB-INF folder
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" 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">
<display-name>Struts Example</display-name>
<filter>
<filter-name>defaultDispatcher</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>defaultDispatcher</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
12.11.08 8
Welcome.jsp
<%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>Welcome</title> </head>
<body> <s:property value="message"/></b> </body> </html>
Creating Welcome Page
12.11.08 9
Welcome.java package example; import com.opensymphony.xwork2.ActionSupport;
public class Welcome extends ActionSupport{
private String message = "default String";
public String getMessage() { return message;
}
public void setMessage(String message) { this.message = message;
}
public String execute() throws Exception { message = “Hello World! My First App is running"; return SUCCESS; // String SUCCESS = “success”
} }
Creating Welcome Page
12.11.08 10
Welcome.java Either implement ActionSupport Or extend Action Or neither
Do provide execute method Framework will search for execute method through Reflection
Default execute method returns SUCCESS Execute is the default entry point for Action class Some return strings constants are already provided
SUCCESS=“success” INPUT=“input” NONE=“none” ERROR=“error” LOGIN=“login”
SUCCESS is the default return string Also returned by default execute method
12.11.08 11
Struts.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration
2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value=“false" />
<constant name="struts.devMode" value="false" /><include name=“someFile.xml” />
<package name="StrutsExample" extends="struts-default"> <action name="Welcome" class="example.Welcome"> <result>/jsp/welcome.jsp</result> </action> </package>
</struts>
Creating Welcome Page
12.11.08 12
<s:property value="message"/>
welcome.jsp Welcome.javaprivate String message =
"default String";public String getMessage() {return message;}public void setMessage
(String message) {this.message = message;}
<action name="Welcome" class="example.Welcome">
url= http://localhost:8081/struts2/Welcome.action
Welcome Page
12.11.08 13
Behind the scenes
Source: http://struts.apache.org/2.x/docs/big-picture.html
12.11.08 14
Struts 2 features
Struts Tag Library Wildcard mappings Validation Localization OGNL expression language Interceptors Dynamic Method Invocation Profiling Debugging Annotations Type Conversion Result Types Dependency Injection Development Mode
12.11.08 15
Struts Tag Library
<%@ page contentType="text/html; charset=UTF-8" %><%@ taglib prefix="s" uri="/struts-tags" %><html><head> <title>Welcome</title></head>
<body><s:form action="Login"><s:property value="errorMessage"/><s:textfield name="username" label="User Name"/><s:password name="password" label="Password" /><s:submit></s:submit></s:form></body></html>
Creating Login PageLogin.jsp
12.11.08 16
Struts Tag Librarypackage example;import com.opensymphony.xwork2.*;
public class Login extends ActionSupport {private String username = "default";private String password = "";private String errorMessage = "";
public String getUsername() { return username; }public void setUsername (String username) { this.username = username;}public String getPassword () { return password;}public String getErrorMessage () { return errorMessage; }public void setErrorMessage (String errorMessage) {this.errorMessage =
errorMessage;}public void setPassword (String password) {this.password = password;}
public String execute () throws Exception {if (isValid(getUsername()) && isValid(getPassword())){ return
SUCCESS; }errorMessage = "invalid input";return "inputError";}
public boolean isValid(String field){return field.length()!=0?true:false;
}}
Creating Login PageLogin.java
12.11.08 17
Struts Tag Library<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value=“false" /> <constant name="struts.devMode" value="false" />
<action name="Login" class="example.Login"> <result>/jsp/success.jsp</result> <result name="inputError">/jsp/login.jsp</result></action>
<package name="StrutsExample" extends="struts-default"> <action name="Welcome" class="example.Welcome"> <result>/jsp/welcome.jsp</result> </action> </package>
</struts>
Creating Welcome PageStruts.xml
12.11.08 18
Struts Tag Library
<%@ page contentType="text/html; charset=UTF-8" %><%@ taglib prefix="s" uri="/struts-tags" %><html><head> <title>Welcome</title></head>
<body>
<b>s:property value="message"/></b><p><a href="<s:url action="Login"/>">Login</a>
<s:url id=“someID" action="Welcome"><s:param name="param1">value1</s:param>
</s:url><p><s:a href=“%{someID}">Welcome</s:a></body></html>
Adding links for Login Pagewelcome.jsp
12.11.08 19
Wildcard mappings
Provides generic mappings GuestLogin and PremierLogin can both be mapped to *Login
Calls EditUser & EditRegistration for /editUser & /editRegistration respectively
Returns /jsp/User.jsp & /jsp/Registration.jsp respectively
<action name="edit*" class="example.Edit{1}">
<result name="failure" path="/mainMenu.jsp"/>
<result path="/jsp/{1}.jsp"/>
</action>
12.11.08 20
Validation
Define configuration file *-validation.xml or use annotations className-validation.xml
Place in the directory where .class file is placed example.Login should have Login-validation.xml
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd"><validators> <field name="username"> <field-validator type="requiredstring"> <message>Username is required</message> </field-validator> </field> <field name="password"> <field-validator type="requiredstring"> <message>Password is required</message> </field-validator> </field></validators>
12.11.08 21
Localization
Get message from resource bundles Generalizes the messages Reusable messages Create <classname>.properties file for specific class and place in
the class path Create package.properties file for specific package Searches for properties file in order
ActionClass.properties BaseClass.properties Interface.properties (every interface and sub-interface) ModelDriven's model (if implements ModelDriven), for the model object
repeat from 1 package.properties (of the directory where class is located and every parent
directory all the way to the root directory) search up the i18n message key hierarchy itself global resource properties
12.11.08 22
Localization
user.required=User Name is required password.required=Password is required
Login.properties
<validators> <field name="username"> <field-validator type="requiredstring"> <message key="username.required"/> </field-validator> </field> <field name="password"> <field-validator type="requiredstring"> <message key="password.required"/> </field-validator> </field></validators>
Login-validation.xml
12.11.08 23
Localization cont…
Use either of <s:property value="getText('some.key')" />
for accessing properties from JSP or Java file <s:text name="some.key" /> <s:text name="some.invalid.key" > The Default Message
That Will Be Displayed </s:text>
12.11.08 24
Interceptors
Can execute code before and after execution Are thread-safe Can be used for
Validation Pre populating fields Double-submit prevention Session control Authentication Type conversion