SlideShare uma empresa Scribd logo
1 de 58
Baixar para ler offline
Struts
Struts By L N Rao Page 1
Day:1
14/09/12
Q) Explain about struts configuration file.
=>In this xml document the total flow control of the application is specified.
=>For each use-case relationship among view components and subcontroller component is specified in this
File.
=>ActionServlet uses this file as input to understand the flow control information of each use-case of the struts
application.
=>standard name for this file is struts-config.xml
=>only one* configuration file per struts application.
=>ActionServlet is able to act as a reusable front controller because of logical names given to application
components in this xml file.
Q)Explain about form beans of a Struts Application.
=>A form bean is a Struts Application is also known as action form(ActionForm).
=>A public java class that extends org.apache.struts.action.ActionForm is eligible to act as form bean in a Struts application.
=>An action form is a Java Bean.
=>ActionForm implements java.io.Serializable interface.
=>For each web form* of the application one action form class is developed which is a Java Bean and hence the name.
=>In a user defined form bean class as many instance variables are to be declared as there are input fields in the corresponding web
form.
=>form bean variable names should match with that of the corresponding user control's request parameters.
=>Form bean can have validate() and reset() methods in addition to the accessors and mutators.
-modification = mutation
=>form bean instance holds view data temporarily in object oriented manner which is going to be transferred to the Model layer by
controller layer i.e. In a Struts application, form bean just acts as a data container that holds View data and hence is considered as a
view component.
=>A form bean can not act as a Data Transfer Object in a web-enabled Java Enterprise Application as it is not a POJO (Plain Old Java
Object).
Note: - A java class is said to be a POJO if it does not inherit from any technology or framework specific
Library class or interface.
---form & form controls is always created using struts tags in struts project.
Day:-2
15/09/12
------------
Q)Explain about action classes of Struts.
=>An action class is a user defined java class that extends org.apache.struts.action.Action class.
=>For each use-case of struts application we develop an action class.
=>action class generally does the following duties -
1.) Capturing the user input from the form bean.(view layer data cptured by the controller for transferring to the
model)
2.) Invoking the business method of the model component for data processing.
3.) Storing the processed data received from the model into scope.
4.) Returning view mapping information to the ActionServlet(Front Controller).
=>Action classes are sub controllers.
=>struts developers consider action classes as mini servlets.
-b/c it has the code similar to that in servlets
-but it not at all servlets as it can not run by servlet engine neither it is configured in configuration File
=>Action classes are configured in struts configuration file and are given logical names(known as action path).
=>In struts application, input screens point to action classes.
=>An action class is a singleton similar to servlet.
- form beans are never singleton
Q)What are not the duties of the action class(sub controller).
=>duties of the front controller -
-validating the user input
-capturing the user input
-request dispatching
-generic flow control code is written into the front controller i.e. it is not specific to each use Cases.
Struts
Struts By L N Rao Page 2
------------------------------------------------------------------------------------------------------------------------------------------
Day:-3
17/09/12
------------
Q)Explain about ActionServlet.
=>ActionServlet is abuilt-in front-controller for a struts application.
=>For each client request framework funstionality entry point is ActionServlet.
=>ActionServlet does its duties in two phases.
1.)At the time of Struts Appplication deployment.
2.)when the client request comes.
=>To make a Java Web Application Struts-enabled, we need to do 3 things in web.xml.
1.)register ActionServlet
2.)instruct the container to pre-load & pre-initialize the ActionServlet.
3.)configure ActionServlet as front-controller.
=>As soon as the struts application is deployed , init() method of the ActionServlet is executed by servlet engine
and struts configuration file is loaded so that ActionServlet knows the entire application flow at the time of
deployment only.
=>When client request comes, ActionServlet does* the following things in general.
1.)Identifying the subcontroller based on the action path from the web form.
2.)creating the form bean instance* and populating its fields with the user input.
3.)validating the user input
4.)creating the instance* of action class.
5.)calling the execute method of action class.
6.)switching the control to the view component based on view mapping info received from the sub controller.
Note:- ActionServlet makes use of invisible work horse of the Struts 1.x to perform all the above duties.i.e. it
uses RequestProcessor.
Q) Explain about the jsps of the struts application.
=>jsps are used in two areas in struts appplications.
1.) input page development
2.) response page development
=>input jsp pages are created in struts applications using html tags & "struts html jsp tag library tags".
=>reponse page development time Struts 4 tag libraries* are to be used.
Day:-4
18/09/12
-----------
--in notebook
Day:-5
20/09/12
----------
Struts-config.xml
-----------------------
<struts-config>
<form-beans>
<form-bean name="loginform" type="com.nareshit.form.LoginForm"/>
</form-beans>
<action-mappings>
<action path="/login" name="loginform" type="com.nareshit.controller.LoginAction">
<forward name="ok" path="/welcome.jsp"/>
<forward name="notok" path="/loginfailed.jsp"/>
</action>
</action-mappings>
</struts-config>
LoginForm.java
--------------------
package com.nareshit.form;
import org.apache.struts.action.ActionForm;
Struts
Struts By L N Rao Page 3
public class loginForm extends ActionForm
{
private String username;
private String password;
public void setUsername(String username)
{
this.username = username;
}
public String getUsername()
{
return username;
}
public void setPassword(String password)
{
this.password = password;
}
public String getPassword()
{
return password;
}
}//Java Bean - form bean (action form)
welcome.jsp
---------------
<html>
<body bgcolor="yellow">
<h1>Welcome to www.nareshit.com</h1>
</body>
</html>
loginfailed.jsp
---------------
<html>
<body bgcolor="red">
<h1>Login failed. Invalid username or password</h1>
<!--<h1>Login failed. Invalid username or password <a href="login.jsp">Try Again</a></h1>-->
</body>
</html>
Problems - 1.one view is deciding which view to switch the control (but it's the work of co
2.we are hardcoding the original page name in one of the jsp
Logical name based linking should only be there.
------------------------------------------------------------------------------------------------------------------------------------------
Day:-6
21/09/12
------------
LoginModel.java
----------------------
pckage com.nareshit.service;
public class LoginModel
{
public boolean isAuthenticated(String user,String pwd)
{
boolean flag = false;
if(user.equals(pwd))
flag = true;
return flag;
}
}
LoginAction.java
----------------------
package com.nareshit.controller;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
Struts
Struts By L N Rao Page 4
import org.apache.struts.action.ActionForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.nareshit.form.LoginForm;
import com.nareshit.service.LoginModel;
public class LoginAction extends Action
{
LoginModel lm = new LoginModel();
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,
HttpServletResponse response)
{
ActionForward af = null;
LoginForm lf = (LoginForm)form;
String user = lf.getUsername();
String pwd = lf.getPassword();
boolean b = lm.isAuthenticated(user,pwd);
if(b)
af = mapping.findForward("ok");
else
af = mapping.findForward("notok");
return af;
}
}
Note:- Place two jar files into classpath before compiling the action class source code-
1.)servlet-api.jar
2.)struts related jars(struts-core-1.3.10.jar)
Place the following jar files into the lib folder:-
commons-beanutils-1.8.0.jar
commons-chain-1.2.jar
commons-digester-1.8.jar
commons-logging-1.0.4.jar
struts-core-1.3.10.jar
struts-taglib-1.3.10.jar
Day:-7
24/09/12
------------
Q)What happens in the background when the struts application(loginapplication) is deployed into J2EE web
container?
=>As soon as the struts application is deployed, web container reads web.xml and pre-initialize ActionServlet.
=>Within the init method of ActionServlet, code is implemented to read struts-config.xml and convert the xml Information into java
format. ActionServlet uses the digester API for this purpose.
=>At the time of application deployment only, ActionServlet knows the total application configuration
details (Struts related).
Q)What happens in the background when login.jsp is executed?
=>When the client request goes for the struts application with the specified url for eg.
http://localhost:8081/loginapplication, as login.jsp is configured as the homepage, jsp engine executes
login.jsp.
=><form> tag of Struts html JSP tag library is executed and does the following things.
1.) It generates html <form> tag
2.) ".do" extension is added to action attribute value
3.) session id is appended to the URL using URL rewriting
=>All struts tags generate HTML tags.
=>login.jsp produced dynamic web content (input page source code which is pure html content) is handed over to the web server.
=>Web server sends the input page to the client.
Q)What happens in the background when user submits the input page by entering the username and password?
=>ActionServlet (infact RequestProcessor) does the following things -
1.) "/login.do" is picked from the url, truncates ".do" extension.
2.) using "/login" identifies the use-case.
3.) creates appropriate form bean instance or retrieve its instance from the scope.
4.) populates from bean fields with user input.
Struts
Struts By L N Rao Page 5
5.) creates LoginAction class instance and calls execute method by supplying use-case information as the
first argument, LoginForm instance as the second argument and request & response arguments.
6.)logical name of the jsp URL is encapsulated into ActionForward object and is returned to
ActionServlet
7.)ActionServlet uses ActionForward object provided view mapping information to switch the control to the appropriate jsp.
Note:- Object Oriented representation of (encapsulation of) one action's forward is nothing but ActionForward object.
Day:-8
25/09/12
------------
Q)Modify the previous application so as to verify the user credentials against the database.
Model Layer files:-
----------------------
LoginModel.java
DBUtil.java
ojdbc14.jar(Driver jar file)
Table :-REGISTRATION(username,password,emailid)
DBUtil.java
--------------
package com.nareshit.service;
import java.sql.*;
public class DBUtil
{
static
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(Exception e)
{
System.out.println(e);
}
}
public static Connection getConnection()throws SQLException
{
return DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:server","nareshit","nareshit");
}
public static void close(Connection con,Statement st,ResultSet rs)
{
try
{
if(rs!=null)
rs.close();
if(st!=null)
st.close();
if(con!=null)
con.close();
}
catch(SQLException e)
{
}
}
}
LoginModel.java
----------------------
package com.nareshit.service;
public class LoginModel
{
public boolean isAuthenticated(String user,String pwd)
{
Struts
Struts By L N Rao Page 6
boolean flag = false;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
con = DBUtil.getConnection();
ps = con.prepareStatement("select * from registration where username=? and password=? ");
ps.setString(1,user);
ps.setString(2,pwd);
rs = ps.executeQuery();
if(rs.next())
flag = true;
}
catch(SQLException e)
{
e.printStackTrace();
}
finally
{
DBUtil.close(con,ps,rs);
}
return flag;
}
}
Note:- If model layer implementation is modified controller and view components are unaffected.
Q)Develop a Struts Application to implement the use-case of user registration.
4:- execute() method calling registerUser() of the model component.
public boolean registerUser(String user,String pwd,String mailId)
model layer files:-
--------------------
DBUtil.java
RegisterModel.java
ojdbc14.jar
configuration files:-
-----------------------
web.xml
struts-config.xml
view layer files
-------------------
register.jsp(input page)
success.jsp
registrationfailed.jsp
RegisterForm.java(form bean)
controller layer files
--------------------------
RegisterAction.java
web.xml:-
=>make register.jsp the home page
struts-config.xml
----------------------
<struts-config>
<form-beans>
<form-bean name="registerform" type="com.nareshit.form.RegisterForm"/>
</form-beans>
<action-mappings>
Struts
Struts By L N Rao Page 7
<action name="registerform" type="com.nareshit.controller.RegisterAction"
path="/register">
<forward name="success" path="/success.jsp"/>
<forward name="failure" path="/registrationfailed.jsp"/>
</action>
</action-mappings>
</struts-config>
## action path is the logical name of the action class.
register.jsp
------------
<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %>
<html>
<body bgcolor="cyan">
<center>
<h1>Register with www.nareshit.com</h1>
<html:form action="/register" method="POST">
UserName <html:text property="username"/>
<br><br>
Password <html:password property="password"/>
<br><br>
Email Id <html:text property="emailid"/>
<br><br>
<html:submit>register</html:submit>
</html:form>
</center>
</body>
</html>
RegisterForm.java
------------------------
package com.nareshit.form;
import org.apache.struts.action.ActionForm;
public class RegisterForm extends ActionForm
{
private String username;
private String password;
private String emailid;
//setters & getters
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------------
Day:-9
26/09/12
RegisterAction.java:-
--------------------------
package com.nareshit.controller;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.nareshit.form.RegisterForm;
import com.nareshit.service.RegisterModel;
public class RegisterAction extends Action
{
RegisterModel model = new RegisterModel();
Struts
Struts By L N Rao Page 8
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,
HttpServletResponse response)
{
RegisterForm rf = (RegisterForm)form;
String user = rf.getUsername();
String pwd = rf.getPassword();
String emailid = rf.getEmailid();
boolean flag = rm.registerUser(user,pwd,emailid);
if(flag)
return mapping.findForward("success");
else
return mapping.findForward("failure");
}
}
RegisterModel.java:-
package com.nareshit.service;
import java.sql.*;
public class RegisterModel
{
public boolean registerUser(String user,String pwd,String eid)
{
boolean flag = false;
Connection con = null;
PreparedStatement ps= null;
try
{
con = DBUtil.getConnection();
ps = con.prepareStatement("insert into registeration values(?,?,?)");
ps.setString(1,user);
ps.setString(2,pwd);
ps.setString(3,eid);
flag = true;
}
catch(SQLException e)
{
e.printStackTrace();
}
finally
{
DBUtil.close(con,ps,null);
}
return flag;
}
}
success.jsp:-
-----------------
<html>
<body bgcolor="cyan">
<h1>Successfully registered with www.nareshit.com</h1>
</body>
</html>
registrationfailed.jsp:-
------------------------------
<html>
<body bgcolor="red">
<h1>Couldn't register you now.Please try later</h1>
</body>
</html>
Q)What happens in the background when findForward() method is called on the ActionMapping object?
ActionForward af = mapping.findForward("ok");
=>action class last duty being a sub controller is to provide view mapping info to the front controller.
=>findForward() method takes logical name of the jsp path as argument and returns ActionForward object
reference.
Struts
Struts By L N Rao Page 9
=>As soon as the struts application is deployed, for each <forward> tag of the use-case one ActionForward
object is created and kept in HashMap object.That HashMap object reference is with ActionMapping object.
=>When findForward() method is called on ActionMapping object, internally it calls get method on HashMap,
retrives the already existing ActionForward object reference and returns to execute() method of action class.
------------------------------------------------------------------------------------------------------------------------------------------
Day:-10
27/09/12
------------
Q)Develop a struts application in which end-user should be able to enter account number into the web form and get
account details?
controller layer files:-
--------------------------
AccountAction.java
1.)End user entering the account nubmer into the web form produced by account.jsp and then submitting the form.
2.)ActionServlet capturing the account number.ActionServet populating the ActionForm fields with user inputs.
3.)ActionServlet instantiating AccountAction and calling its execute method
4.)execute() method is calling getAccountDetails() method of Model Component.
5.)getAccountDetails() method communicating with database.
6a.)getAccountDetails() method returning data transfer object i.e. Account object to execute() method.
6b.)getAccountDetails() method returning null to execute() method.
7a.)execute() method returning ActionForward object reference to ActionServlet encapsulating "success" logical
name after storing DTO(data transfer object) in request scope.
7b.)execute() method returning ActionForward object to ActionServlet encapsulating "failure" logical name.
8a.)ActionServlet through request dispatching forwarding the control to accountdetails.jsp.
9a.)accountdetails.jsp retriving DTO state from request scope and producing the response page for the client.
AccountAction.java
---------------------------
package com.nareshit.controller;
import org.apchae.struts.action.*;
import javax.servlet.http.*;
import com.nareshit.form.AccountForm;
import com.nareshit.service.AccountModel;
import com.nareshit.vo.Account;
public class AccountAction extends Action
{
AccountModel am = new AccountModel();
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,
HttpServletResponse response)
{
AccountForm af = (AccountForm)form;
int ano = af.getAccno();
Account acc = am.getAccountDetails(ano);
if(acc!=null)
{
request.setAttribute("account",acc);
return mapping.findForward("success");
}
else
return mapping.findForward("failure");
}//execute()
}
AccountForm.java
-------------------------
package com.nareshit.form;
import apache.struts.action.ActionForm;
public class AccountForm extends ActionForm
{
private int accno;
public void setAccno(int accno)
{
this.accno = accno;
Struts
Struts By L N Rao Page 10
}
public int getAccno()
{
return this.accno;
}
}
AccountModel.java
---------------------------
package com.nareshit.service;
import com.nareshit.vo.Account;
import java.sql.*;
public class AccountModel
{
public Account getAccountDetails(int accno)
{
Account acc = null;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
con = DBUtil.getConnection();
ps = con.prepareStatement("Select * from account where accno=?");
ps.setInt(1,accno);
rs = ps.executeQuery();
if(rs.next())
{
acc = new Account();
acc.setAccno(rs.getInt(1));
acc.setName(rs.getString(2));
acc.setBalance(rs.getFloat(3));
}
}//try
catch(SQLException e)
{
e.printStackTrace();
}
finally
{
DBUtil.close(con,ps,rs);
}
return acc;
}
}
Account.java
------------------
package com.nareshit.vo;
public class Account implements java.io.Serializable
{
private int accno;
private String name;
private Float balance;
//setters & getters
}//Value object class / Data Transfer Object class
Note:- Model class can be running in business tier and controller can be running in web tier.Therefore, DTO must implement
java.io.Serializable interface.
noaccount.jsp
-------------------
<html>
<body bgcolor="cyan">
Struts
Struts By L N Rao Page 11
<h1>Account Doesn't exists</h1>
</body>
<html>
account.jsp
----------------
<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %>
<html>
<body bgcolor="cyan">
<center>
<h1>Account Details retrived</h1>
<html:form action="account" method="POST">
Account Number <html:text property="accno" value=""/>
<br><br>
<html:submit>GetAccountDetails</html:submit>
</html:form>
</center>
</body>
</html>
accountdetails.jsp
------------------------
<%@ taglib prefix="bean" uri="http://struts.apache.org/tags-bean" %>
<html>
<body bgcolor="cyan">
<h1>Account Details</h1>
Account Number: <bean:write name="account" property="accno"/>
<br>
Name : <bean:write name="account" property="name"/>
<br>
Balance: <bean:write name="account" property="balance"/>
</body>
</html>
struts-config
----------------
<message-resources parameter="ApplicationResources"/>
=====================================================================
Day:-11
28/09/12
------------
struts-config.xml
-----------------
<struts-config>
<form-beans>
<form-bean name="accountForm" type="com.nareshit.form.AccountForm">
</form-bean>
</form-beans>
<action-mappings>
<action name="accountForm" type="com.nareshit.controller.AccountAction" path="/account">
<forward name="success" path="/accountdetails.jsp">
<forward name="failure" path="/noaccount.jsp">
</action>
</action-mappings>
<message-resources parameter="applicationResources"/> <!-- becuase bean library is used -->
</struts-config>
web.xml
Struts
Struts By L N Rao Page 12
-----------
Note:- make account.jsp a home page.
Q)Develop a Struts application that takes balance range as input and displays all the account details that
fall under that balance range.
accountsapplication
account.jsp
noaccount.jsp
accountdetails.jsp
WEB-INF
web.xml
struts-config.xml
src
DBUtil.java
AccountForm.java
AccountModel.java
Account.java
AccountAction.java
classes
*.class
lib
*.jar(7 jar files)
http://localhost:8081/accountsapplication
AccountForm.java
--------------------------
package com.nareshit.form;
import org.apache.struts.action.ActionForm;
public class AccountForm extends ActionForm
{
private String balanceRange;
//setters & getters
}
AccountAction.java
---------------------------
package com.nareshit.controller;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionModel;
import javax.servlet.http.*;
import java.util.List;
public class AccountAction extends Action
{
AccountModel am = new AccountModel();
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,
HttpServletResponse response)
{
AccountForm af = (AccountForm)form;
String br = af.getBalanceRange();
StringTokenizer st = new StringTokenizer(br,"-");
float lower = Float.parseFloat(st.nextToken());
float upper = Float.parseFloat(st.nextToken());
List<Account> accounts = am.getAccountsDetails(lower,upper);
if(accounts!=null)
Struts
Struts By L N Rao Page 13
{
request.setAttribute("accounts",accounts);
return mapping.findForward("success");
}
else
return mapping.findForward("failure");
}//execute()
}
Note:- web.xml,struts-config.xml,Account.java and DBUtil.java from the previous application.
account.jsp
-----------
<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html"%>
<html>
<body bgcolor="cyan">
<center>
<h1>Account Details Retrival</h1>
<html:form action="account" method="POST">
Balance Range(lower-upper)<html:text property="balancerange"/>
<br><br>
<html:submit>get accounts details</html:submit>
</html:form>
</center>
</body>
</html>
noaccount.jsp
-------------
<html>
<body bgcolor="cyan">
<center>
<h1>With this balance range no Account exists</h1>
</center>
</body>
</html>
accountdetails.jsp
-------------------------
<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html"%>
<%@ taglib prefix="bean" uri="http://struts.apache.org/tags-bean"%>
<%@ taglib prefix="logic" uri="http://struts.apache.org/tags-logic"%>
<html>
<body bgcolor="cyan">
<center>
<table border="1">
<tr>
<td>ACCNO</td>
<td>NAME</td>
<td>BALANCE</td>
</tr>
<logic:iterate name="accounts" id="account" scope="request">
<tr>
<td><bean:write name="account" property="accno"/></td>
<td><bean:write name="account" property="name"/></td>
<td><bean:write name="account" property="balance"/></td>
</tr>
</logic:iterate>
</table>
</center>
</body>
</html>
AccountModel.java
--------------------------
package com.nareshit.service;
import java.sql.*;
import java.util.List;
Struts
Struts By L N Rao Page 14
import java.util.ArrayList;
import com.nareshit.vo.Account;
public class AccountModel
{
public List<Account> getAccountsDetails(float lower,float upper)
{
List<Account> accounts = null;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
con = DBUtil.getConnection();
ps = con.prepareStatement("select * from Account where balance between ?
and ?");
ps.setFloat(1,lower);
ps.setFloat(2,upper);
rs = ps.executeQuery();
if(rs.next())
{
accounts = new ArrayList<Account>();
do
{
Account acc = new Account();
acc.setAccno(rs.getInt(1));
acc.setName(rs.getString(2));
acc.setBalance(rs.getFloat(3));
accounts.add(acc);
}while(rs.next());
}
}//try
catch(SQLException e)
{
e.printStackTrace();
}
finally
{
DBUtil.close(con,ps,rs);
}
return accounts;
}
}
Day:-12
02/10/12
------------
Q)Explain about Exception Handling in a struts application.
=>In view components exception handling is not required.
=>Even if exceptions are handled in model component, it does not come under exception handling in a
Struts application(UI layer/Presentation layer of web-enabled enterprise Java application).
=>Handling the exceptions in the controller component is nothing but exception handling in UI Layer.
=>If exception handling is not implemented in controller layer , wrong information may go to the end
user
=>Exception handling is not possible in controller layer unless the raised exception is propagated to
the controller by the model component.
=>Model components propagate exceptions to controller components when their business methods are
invokedin two scenarios.
a.)data accessing time exception raised
b.)communicating with database has not caused the exception i.e. data accessing time
exception is not raised but while processing data business rule is violated.
=>Always model components propagate user defined exceptions to sub controller components.
=>In a struts application, exception handling is nothing but dealing with exceptions in action classes
while they are communicating with model components.
Struts
Struts By L N Rao Page 15
Q)Modify the prototype of isAuthenticated() method of LoginModel when the method is performing database
operation.
=>public void isAuthenticated(String username,String password)throws LoginFailedException,
ProcessingException
Q)Modify the prototype of getAccountDetails() method of AccountModel of "accountapplication" so as to implement
exception handling.
=>public Account getAccountDetails(int accno)throws AccountNotFoundException,ProcessingException
------------------------------------------------------------------------------------------------------------------------------------------Day:-13
Day:-13
03/10/12
-----------
Q)Implement exception handling with UI layer of login application.
prgexcploginapplication
login.jsp
loginfailed.jsp
problem.jsp
welcome.jsp
WEB-INF
struts-config.xml
web.xml
src
LoginForm.java
LoginModel.java
LoginAction.java
DBUtil.java
processingException.java
LoginFailedException.java
=>"workFlow for loginapplication with exception 3-oct-12.bmp"
6a - isAuthenticated() method returning nothing to execute method indicating that authentication is successful.
6b - model component propagating LoginFailedException as no record is found in the database with that user
name and password.
6c - model component propagating ProcessingException to sub controller upon database communication caused
abnormal event.
7b - "failure" view mapping info passed to front controller
7c - "abnormal" view mapping info passed to front controller
problem.jsp
----------------
<html>
<body bgcolor="red">
<h1>Couldn't authenticate you right now.Please try later</h1>
</body>
</html>
LoginFailedException.java
-----------------------------------
package com.nareshit.exception;
public class LoginFailedException extends Exception
{
}
ProcessingException.java
----------------------------------
package com.nareshit.exception;
public class ProcessingException extends Exception
{
}
LoginModel.java
----------------------
package com.nareshit.service;
import com.nareshit.exception.ProcessingException;
import com.nareshit.exception.LoginFailedException;
import java.sql.*;
Struts
Struts By L N Rao Page 16
import javax.servlet.http.*;
public class LoginModel
{
public void isAuthenticated(String user,String pwd)throws ProcessingException,LoginFailedException
{
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
con = DBUtil.getConnection();
ps = con.prepareStatement("Select * from Registration where username=? and
password=?");
ps.setString(1,user);
ps.setString(1,pwd);
rs = ps.executeQuery();
if(!rs.next())
throw new LoginFailedException();
}
catch(SQLException e)
{
e.printStackTrace();
throw new ProcessingException();
}
finally
{
DBUtil.close(con,ps,rs);
}
}
}
struts-config.xml
-----------------------
we need to add the third forward within <action> tag.
<action ...>
...
<forward name="abnormal" path="/problem.jsp"/>
</action>
LoginAction.java
-----------------------
package com.nareshit.controller;
public class loginAction extends Action
{
LoginModel lm = new LoginModel();
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,
HttpServletResponse response)
{
String viewInfo = "ok";
LoginForm lf = (LoginForm)form;
String user = lf.getUsername();
String pwd = lf.getPassword();
try
{
lm.isAuthenticated(user,pwd);
}
catch(LoginFailedException e)
{
viewInfo="notok";
}
catch(ProcessingException e)
{
viewInfo = "abnormal";
}
Struts
Struts By L N Rao Page 17
return mapping.findForward(viewInfo);
}
}
Q)How is exception handling classified is a Struts Application?
=>There are 2 types of Exception Handling in a Struts Application.
1.)Programmatical Exception Handling
2.)Declarative Exception Handling
Q)What is Programmatical Exception Handling in a Struts Application?
=>Within the execute method of Action class, placing the model component method call in try block and
implementing correspoding exception handlers i.e. catch blocks, is nothing but Programmatical Exception
Handling.
=>In case of programmatical Exception Handling no support from Struts.
Day:-14
04/10/12
------------
Q)Modify the "accountapplication" so as to have programmatical exception handling implemented.
prgexpaccountapplication
account.jsp
accountdetails.jsp
noaccount.jsp
problem.jsp
WEB-INF
web.xml
struts-config.xml
src
AccountForm.java
AccountAction.java
AccountModel.java
Account.java (DTO)
DBUtil.java
AccountNotFoundException.java
ProcesssingException.java
classes
*.class
lib
*.jar
=>"prgexpaccountaplication 03-oct-12.bmp"
6a:- DBMS returning one account record
6b:- DBMS returning no record i.e. Jdbc Driver creates empty resultset object
6c:- DBMS causing exception to model component
7a:- getAccountDetails() method returning Account object(DTO/POJO/Domain object) to execute method.
7b:- model component propagating AccountNotFound Exception to subcontroller
7c:- model component propagating ProcessingException to action class
8c:- "abnormal" view mapping info passed to frontcontroller
problem.jsp
----------------
<html>
<body bgcolor="red">
<h1>Couldn't process request now.Please try after some time.</h1>
</body>
</html>
struts-config.xml
-----------------------
=>add one additional <forward> tag for "problem.jsp" similar to that of previous application.
AccountNotFoundException.java
--------------------------------------------
Struts
Struts By L N Rao Page 18
package com.nareshit.exception;
public class AccountNotFoundException extends Exception
{
}
AccountModel.java
--------------------------
try
{
.....
.....
if(rs.next())
{
....
....
}
else
throw new AccountNotFoundException();
}//try
catch(SQLException e)
{
e.printStackTrace();
throw new ProcessingException();
}
AccountAction.java
---------------------------
public class AccountAction extends Action
{
private static final String SUCCESS = "success";
private static final String FAILURE = "failure";
private static final String EXCEPTION = "abnormal";
AccountModel am = new AccountModel();
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,
HttpServletResponse response)
{
String viewInfo = SUCCESS;
AccountForm af = (AccountForm) form;
int ano = af.getAccno();
try
{
Account acc = am.getAccountDetails(ano);
request.setAttribute("account",acc);
}
catch(ProcessingException e)
{
viewInfo = EXCEPTION;
}
catch(AccountNotFoundException e)
{
viewInfo = FAILURE;
}
return mapping.findForward(viewInfo);
}//execute
}
Q)What is a Resource Bundle in a Struts Application?
=>Resource Bundle is properties file in a Struts Application whose standard name is
"ApplicationResources.properties"
=>In a Resource Bundle key,value pairs are specified according to Struts Application requirements.
=>Struts reads the content of the Resource Bundle at runtime and uses it in populating the jsps with
template text.
=>Resource Bundles are used in the implementation of declarative exception handling, declarative validation
and i18n in Struts application.
Q)How to make use of a Resource Bundle in a Struts Application.
Step 1:- Develop the properties file with some required key,value pairs
Step 2:- Place the properties file in application's classpath i.e. "classes" folder with the standard name
Struts
Struts By L N Rao Page 19
"ApplicationResources.properties"
Step 3:- Make the entry about the ResourceBundle in Struts configuration file.
<message-resources parameter="ApplicationResources">
</message-resources>
------------------------------------------------------------------------------------------------------------------------------------------
Day:-15
05/10/12
------------
Q)What are the limitations of the programmatical exception handling?
1.)No support for exception handling from framework.
2.)flow control code is polluted with exception handling code within the sub controller.
Note:- Declarative exception handling addresses these limitations.
Q)What is declarative exception handling in a Struts Application?
=>Instructing the Struts Framework through configuration file to provide exception handlers from the sub
controllers while they are invoking the business methods of the model components is nothing but declarative exceptiion handling.
Q)How to implement declarative exception handling in a struts application?
Step 1:- Develop a Resource Bundle with appropriate keys and corresponding messages(values).
Step 2:- Make use of <exception> tags as sub tags of <action> tag to indicate to the framework the exception handlers required for
that sub controller.
Step 3:- Ensure that sub controller's method has java.lang.Exception in its exception specification.
Step 4:- Make use of <html:errors /> tag in abnormal message displaying in jsps.
Q)Modify the "prgexpaccountapplication" so as to have declarative exception handling instead of programmatical
exception handling.
declexpaccountapplication
account.jsp
accountdetails.jsp
failure.jsp
WEB-INF
*.xml
src
*.java
classes
*.classes
lib
*.jar
http://localhost:8081/declexpaccountapplication
Note:-Model layer files are from the previous application.Form Bean,account.jsp,accountdetails.jsp & web.xml are also from the
previous application.
AccountAction.java
--------------------------
....
....
public class AccountAction extends Action
{
AccountModel am = new AccountModel();
public ActionForward execute()throws Exception
{
AccountFrom af = (AccountForm) form;
int ano = af.getAccno();
Account acc = am.getAccountDetails(ano);
request.setAttribute("account",acc);
return mapping.findForward("success");
}//execute()
Struts
Struts By L N Rao Page 20
}
....
ApplicationResources.properties
--------------------------------------------
db.search.failed=Account doesn't exist
db.operation.failed=Processing Error.Please try later
struts-config.xml
----------------------
<struts-config>
<form-beans>
<form-bean name="accountform" type="com.nareshit.form.AccountForm"/>
</form-beans>
<action-mappings>
<action name="accountform" type="com.nareshit.controller.AccountAction" path="/account">
<exception key="db.search.failed" type="com.nareshit.exception.AccountNotFoundException"
path="/failure.jsp">
</exception>
<exception key="db.operation.failed" type="com.nareshit.exception.ProcessingException"
path="/failure.jsp"/>
<forward name="success" path="/accountdetails.jsp"/>
</action>
</action-mappings>
<message-resources parameter="ApplicationResources"/>
</struts-config>
failure.jsp
--------------
<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %>
<html>
<body bgcolor="cyan">
<font color="red" size="5">
<html:errors />
</font>
</body>
</html>
------------------------------------------------------------------------------------------------------------------------------------------
Day:-16
06/10/12
------------
Q)Explain about the attributes of the <exception> tag?
key - this attribute is used to specify the resource bundle key.
type - used to specify to framework about the required exception handler.
path - if exception is raised, to which jsp control has to be switched is specified using this attribute.
Q)What happens in the background when model component method propagated exception to the sub-controller in
case of declarative exception handling?
=>framework provided exception handler does the following things-
1.)creates org.apache.struts.action.ActionMessage object. In this object resource bundle key is encapsulated.
2.)ActionMessage object is kept into scope(session/request).
3.)informs to the ActionServlet about the jsp to which the control has to be switched.
Q)Explain about the functionality of <html:errors /> tag?
=>Tag Handler of <html:errors> tag does the following things.
1.)retrieving the ActionMessage object from the scope
2.)Retrieving resource bundle key that is wrapped in ActionMessage object
3.)retrieving corresponding message from the resource bundle
4.)writing the resource bundle message to the browser stream
Q)What is dynamic form bean?
=>A form bean developed by Struts for the Struts Application at run time is known as dynamic form bean.
=>Our own developed form bean is known as a static form bean.
Struts
Struts By L N Rao Page 21
Q)How to make use of a dynamic form bean in a Struts Application?
Step 1:- Configure DynaActionForm class in form beans section of struts configuration file.
Step 2:- Specify the required fields using <form-property> tag.
Step 3:- In Action class typecast ActionForm reference to DynaActionForm and invoke get() methods to capture the user
input from the dynamic form bean instance.
Q)Struts Application on dynamic form bean usage.
dynafrombeanloginapplication
*.jsp
WEB-INF
*.xml
lib
*.jar
src
LoginModel.java
LoginAction.java
http://localhost:8081/dynaformbeanloginapplication
Note:- all files from the first struts application except action class and configuration file
struts-config.xml
----------------------
<struts-config>
<form-beans>
<form-bean name="loginform" type="org.apache.struts.action.DynaActionForm">
<form-property name="username" type="java.lang.String"/>
<form-property name="password" type="java.lang.String"/>
</form-bean>
</form-beans>
<action-mappings>
....
</action-mappings>
</struts-config>
LoginAction.java
----------------
...
import org.apache.struts.action.DynaActionForm;
public class LoginAction extends Action
{
LoginModel lm = new LoginModel();
public ActionForward execute(.....)
{
ActionForward af = null;
DynaActionForm daf = (DynaActionForm)form;
String user = (String)daf.get("username");
String pwd = (String)daf.get("password");
boolean b = lm.isAuthenticated(user,pwd);
if(b)
af = mapping.findForward("ok");
else
af = mapping.findForward("notok");
return af;
}
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------------
Day:-17
08/10/12
-------------
struts-config.xml
-----------------------
<struts-config>
<form-beans>
<form-bean name="accountform" type="org.apache.struts.action.DynaActionForm">
<form-property name="accno" type="java.lang.Integer"/>
</form-bean>
Struts
Struts By L N Rao Page 22
</form-beans>
.....
</struts-config>
AccountAction.java
-------------------------
import org.apache.struts.action.DynaActionForm;
public class AccountAction extends Action
{
AccountModel am = new AccountModel();
public ActionForward execute()
{
DynaActionForm daf = (DynaActionForm)form;
int accno = (Integer) daf.get("accno");
...........
}
}
Q)Why dynamic form bean?
=>Struts developer's developed form beans are known as static form bean.
=>Static form beans have the following limitations :-
1.)Developing form bean classes for all input pages of the application is a tedious task (and zero support from framework in
development).
2.)functional dependency between input page developers and form bean developers.
Q)What are global forwards?
=>In struts configuration file we have two kinds of forwards :-
1.)action specific forwards
2.)forwards that are common to all actions
=>Whenever same response for multiple use-cases is required to be given to the end-users, to reduce the amount
of xml configuration in struts-config.xml we use <forward> tags that are available to all the actions of the application known as
"global forwards".
=>If <forward> tag is placed within the <action> tag it is known as action specific forward and it is not
available to other actions.
=>Global forwards are configured as follows :-
<struts-config>
<form-beans>
<global-forwards>
<forward name="success" path="/welcome.jsp"/>
.......
</global-forwards>
</form-beans>
</struts-config>
Q)What are the global exceptions in a Struts Application?
=>During declarative exception handling if <exception> tag is placed within <action> tag, is known as action specific handler
configuration.
=>Limitation with this kind of configuration is that even if same exception handler is required for another action class, it is not
available. We need to configure the same to another action.
=>Exception handlers configured to make it available to all actions to reduce the amount of xml configuration is nothing but gloabl
exception handler.
For eg. -
<global-exceptions>
<exception key="" type="" path="">
</global-exceptions>
Struts
Struts By L N Rao Page 23
Q)Is form bean thread-safe?
=>In Struts Application, Form Bean instance is not a singleton. Therefore, thread saftey issue doesn't arise.
That too it is supplied as argument to execute() method of action class instance.
=>Yes, it is thread-safe.
Q)Is Action class thread-safe?
=>No. We need to take care.
=>Action class is a singleton in a Struts application. i.e. only one instance of action type is created by
ActionServlet.
Day:-18
09/10/12
------------
Q)How model component can possibly be decomposed?
Model Component
Q)Explain about form bean life cycle.
=>Form bean life cycle
Q)What is the purpose of reset() method in form bean class?
=>reset method need not be implemented in a static form bean if the scope is "request".
=>reset() method is designed for form bean in Struts to overcome the strange behaviour of checkbox.
=>In reset() method we make the boolean variable corresponding to a checkbox as false.
Q)how to deal with the above scenario in dynamic form bean?
<form-property name="isAgree" type="java.lang.Boolean" initial="false"/>
------------------------------------------------------------------------------------------------------------------------------------------
Day:-19
10/10/12
------------
Q)How is business logic and data access logic are seperated in a Java Enterprise Application?
=>using DAO design pattern
=>A universal solution for a recurring problem in an application is nothing but a Design Pattern.
Struts
Struts By L N Rao Page 24
=>"Data Access Object" is a Design Pattern. According to this design pattern a seperate object performs data accessing activity and
provides service to business component in abstraction.
~J2EE principle - clear seperation of concern
~concern - one task. For eg. getting user interaction
PL = V + C
input screen - V
capturing user input |
validating user input |
communication with data processing component |-flow control
exception handling |
switching the control to appropriate view |
producing the response page - V
MVC is presentation layer design pattern
data processing concern
M = BC + DAO
STRUTS-EJB Integeration
-----------------------------------
=>Enabling Struts Action classes communicating with Enterprise Java Beans of EJB technology.
=>"struts-ejb integration 1 10-oct-12.bmp"
Q)Develop a Model Component using EJB technology for the Struts "loginapplication".
ejbmodelcomponent
LoginModel.java(interface)
LoginModelImpl.java(session bean)
LoginModel.java
-----------------------
package com.nareshit.service;
public interface LoginModel
{
public abstract boolean isAuthenticated(String user,String pwd);
}//POJI (Plain Old Java Interface)
//contract created
LoginModelImpl.java
___________________
package com.nareshit.service;
import javax.ejb.Remote;
import javax.ejb.Stateless;
@Remote
@Stateless(mappedName="hello")
public class LoginModelImpl implements LoginModel
{
public boolean isAuthenticated(String user,String pwd)
{
boolean flag = false;
if(user.equals(pwd))
flag = true;
return flag;
}
}//POJO (Plain Old Java Object)
Note:- place weblogic.jar file into CLASSPATH before compiling the business interface and the
implementation class.
=>javac - d . *.java
=>jar cvf loginmodel.jar com
=>Once the above jar file is deployed into EJB container of weblogic application server, the container does the
following things.
1.)creates a proxy for the bean class (LoginModelImpl)
2.)creates stub and skeletons for the proxy
3.)registers the proxy stub with naming service with the name
"hello#com.nareshit.service.loginModel"
Day:-20
11/10/12
--------
Struts
Struts By L N Rao Page 25
.....
-not attended
____________________________________________________________________________________________________________
____
Day:-21
12/10/12
------------
STRUTS-SPRING INTEGRATION
-----------------------------------------
=>Enabling Struts Action classes communicate with Spring Beans is nothing but Struts-Spring Integration.
Q)Develop model component for Struts "loginapplication" using Spring.
springmodelcomponent
LoginModel.java
LoginModelImpl.java
Note:- LoginModel.java is an interface which is from EJB integration example.
LoginModelImpl.java is a Spring Bean class which is from EJB integration example but without annotations.
beans.xml
--------------
<beans>
<bean id="lm" class="com.nareshit.service.LoginModelImpl"/>
</beans>
Q)Modify the first Struts application(loginapplication) so as to use Spring Bean as model component.
springloginapplication
*.jsp
WEB-INF
web.xml
struts-config.xml
classes
LoginForm.class
LoginAction.class
LoginModel.class
LoginModelImpl.class
beans.xml
lib
6 struts jar files
spring.jar
http://localhost:8081/springloginapplication
LoginAction.java
-----------------------
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class LoginAction extends Action
{
LoginModel lm;
public LoginAction()
{
XmlBeanFactory springContainer = new XmlBeanFactory(new ClassPathResource("beans.xml"));
lm = (LoginModel)springContainer.getBean("lm");
}
Struts
Struts By L N Rao Page 26
.......
}//LoginAction
Note:- place 3 jar files into classpath before compiling the above action class.
1) spring.jar
2) servlet-api.jar
3) struts-core-1.3.10.jar
Q)How to integrate Spring with Struts?
Step 1:- place Spring Bean class file and corresponding interface if any in classes folder.
Step 2:- copy bean configuration file into "classes" folder.
Step 3:- place spring.jar file in lib folder.
Step 4:- In action class acquire the spring bean reference from the Spring Container.
Q)What is the limitation of LoginAction development in Struts-EJB and Struts-Spring integration applications?
=>Tight coupling with sub controller and model component.
=>Action class is aware of the model component details.
Note:- Business Delegate Design Pattern overcoms this limitation.
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------------Day:-22
13/10/12
-----------
Q)Explain about Business Delegate Design Pattern.
Context:- communication with business components.
Problem:- Tight coupling between presentation layer component and business component.
Solution:- Business Delegate
=>Business Delegate is Business Logic Layer(Service Layer) design pattern.
=>According to this solution(Design Pattern) a proxy class is created for the actual business component.
=>This proxy class abstracts the presentation layer component, the business business component specific
details while using its service.
=>Business component developer develops proxy class which is known as Business Delegate class.
=>In Business delegate class, every business method of the business component is dummily implemented.
It receives the business service request from presentation layer and delegates to the actual business component and hence the
name.
Q)Develop a business delegate class for LoginModelImpl (Spring Bean) whose business method may throw
LoginFailedException and ProcessingException.
LoginDelegate.java
---------------------
package com.nareshit.service;
....
public class LoginDelegate
{
LoginModel lm;
public LoginDelegate()
{
XmlBeanFactory springContainer = new XmlBeanFactory(new ClassPathResource("beans.xml"));
lm = (LoginModel)springContainer.getBean("lm");
}
public void isAuthenticated(String user,String pwd)throws ProcessingException,LoginFailedException
{
lm.isAuthenticated(user,pwd);//delegation to the business component
}//dummy implementation of the original method
}
Q)Develop LoginAction that uses the delegate in Struts-Spring integration application.
public class LoginAction extends Action
{
LoginDelegate lm = new LoginDelegate();
Struts
Struts By L N Rao Page 27
execute(....)throws Exception
{
.....
lm.isAuthenticated(user,pwd);
.....
}
}
Note:- Declarative exception handling is assumed.
-interface can also be used for business delegate class.
Q)Develop the Business Delegate for the EJB class.
package com.nareshit.service;
import javax.naming.InitialContext;
......
public class LoginDelegate
{
LoginModel lm;
public LoginDelegate
{
try
{
InitialContext ic = new InitialContext();
lm = (LoginModel)ic.lookup("hello#com.nareshit.service.LoginModel");
}
catch(Exception e)
{
System.out.println(e);
}
}//constructor
public void isAuthenticated(String user,String pwd)throws ProcessingException,LoginFailedException
{
lm.isAuthenticated(user,pwd);//delegation to the business component
}//dummy implementation of the original method
}
Q)Develop LoginAction that uses the above delegate class fro EJB communication.
=>Same as above.(that's why loose coupling)
Q)What are the duties of a controller in a web enabled Java Web Application that follows MVC design pattern?
1.)capturing the use input
2.)validating the user input
3.)communicating with model component
4.)handling the exception
5.)indentifying the view
6.)switching the control to the view
Note:- MVC design pattern doesn't seperate the reusable and common flow control tasks and non-reusable
varying flow control tasks.
MVC problem:-
-multiple entry points into the website(application).
-duplication of same flow control code for each use case(for multiple controller)
solution - Front Contoller Design Pattern
Note:- ActionServlet implementation is nothing but according to Front Controller Design Pattern only.
ActionServlet is built-in front controller.
____________________________________________________________________________________________________________
________
Day:-23
15/10/12
-----------
Validations in Struts Application
------------------------------------------
Struts
Struts By L N Rao Page 28
Q)Explain about validation in a Java Web Application?
=>Ensuring complete input and proper input into the web application through web froms is nothing but performing
validation in a web application(website).
=>We have two kinds of validations.
1.)client side validation
2.)server side validation
Q)What is Server Side Validation and Why is it required when client side validation is already applied?
=>Verifying the user input at web serverside for its completeness and correctness is known as server side
validation.
=>Server side validation is performed for two reasons.
1.)for security reasons
2.)assuming that clientside validation code is by-passed due to disabling of JavaScript or compatibility
of javascript code.
Q)What is server side validation in a Struts Application?
=>Verifying user input that is stored in form bean instance for its completeness and correctness is nothing but
server side validation in a Struts Application.
Q)How is validation classified in a Struts Application?
1.)Programmatical validation
2.)Declarative validation
Note:- Almost all the times declarative validation mechanism only used.
Q)What is programmatical validation ia Struts Application?
=>If user input verification code Struts Developer implements in static form bean class, it is known as
programmatical validation.
Q)How to implement programmatical validation in a Struts Application?
Step 1:- Develop a resource bundle with appropriate entries.
Step 2:- Override validate() method in static form bean instance and implement validation logic.
Step 3:- Enable validation and specify the input page (to Struts to execute in case of validation failure).
Step 4:- In the specified input page make use of <html:errors> tag.
Q)Develop a Struts application in which, programmatical validation is implemented.
prgvalidationloginapplication
login.jsp
welcome.jsp
loginfailed.jsp
WEB-INF
*.xml
classes
*.class
lib
*.jar
src
*.java
_____________________________________________________________________________________
Day:-24
16/10/12
------------
ApplicationResources.properties
-------------------------------
user.required=Username field can't be empty
pwd.required=Password field can't be empty
LoginForm.java
--------------
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMapping;
Struts
Struts By L N Rao Page 29
import javax.servlet.http.HttpServletRequest;
public class LoginForm extends ActionForm
{
private String username;
private String password;
public void setUsername(String username)
{
this.username = username;
}
public String getUsername()
{
return username;
}
public void setPassword(String password)
{
this.password = password;
}
public String getPassword()
{
return password;
}
public ActionErrors validate(ActionMapping mapping,HttpServletRequest request)
{
ActionErrors ae = new ActionErrors();
//validation logic
if(username.length()==0) //here NullPointerException will not be raised.why?
{
ae.add("username",new ActionMessage("user.required"));
}
if(password.length()==0)
{
ae.add("password",new ActionMessage("password.required"));
}
return ae;
}//validate
}//form bean(action form)
struts-config.xml
-----------------
<struts-config>
<form-beans>
<form-bean name="loginform" type="com.nareshit.form.LoginForm"/>
</form-beans>
<action-mappings>
<action path="/login" name="loginform" type="com.nareshit.controller.LoginAction"
validate="true" input="/login.jsp">
<forward name="ok" path="/welcome.jsp"/>
<forward name="notok" path="/loginfailed.jsp"/>
</action>
</action-mappings>
<message-resources parameter="ApplicationResources"/>
</struts-config>
login.jsp
---------
<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %>
<html>
<body bgcolor="cyan">
<center>
<h1>Login to www.nareshit.com</h1>
<html:form action="/login" method="POST">
UserName <html:text property="username"/>
Struts
Struts By L N Rao Page 30
<font color="red" size="5">
<html:errors property="username"/>
</font>
<br><br>
Password <html:password property="password"/>
<font color="red" size="5">
<html:errors property="password"/>
</font>
<br><br>
<html:submit>login</html:submit>
</html:form>
</center>
</body>
</html>
Q)How does ActionServlet know wether validation is failed or succeeded?
=>If ActionErrors object is empty or its reference is null, ActionServlet understands that validation is
successfull.
=>If ActionErrors object has at least one ActionMessage object it understands that validation is a failure
and it stores ActionErrors object into the scope and switches the contorl to the specified input page.
Q)Explain about ActionErrors?
=>Struts API class.
=>Struts collection class.
=>For each validation failure we need to store an ActionMessage object into this collection.
=>Its add method takes a String as the first argument indicating which field failed in validation.
____________________________________________________________________________________________________________
________
Day:-25
17/10/12
------------
Q)What are the limitations of programmatical validation in Struts Application?
1.)Validation logic, developer should write and zero support from framework.
2.)Validation logic written for on field is not resuable for same field of another form bean.
3.)Can't validate the user input in case of Dynamic form bean.
4)Can't use Javascript generation facility provided by the Struts Framework i.e. client side validation
logic also developers are responsible to develop.
Q)What is declarative validation in a Struts application?
=>Instead of Struts developer developing the server side validation logic for the user input, taking Struts
framework provided validation support by explaining the validation requirements through xml tags declaratively
is nothing but declarative validation in Struts Application.
=>Declrative validation overcomes all the limitations of programmatical validation.
=>Using validation sub framework in a Struts application for validations is nothing but implementing
declarative validation in a Struts Application.
Q)How to implement(make use of) declarative validation in a Struts Application for static form beans?
Step 1:- Develop the resource bundle with appropriate entries.
Step 2:- Develop the form bean class that extends org.apache.struts.validator.ValidatorForm.
=>Should not override validate method in form bean class.
Step 3:- Enable validation and specify the input page in Struts Configuration file.
Step 4:- Make use of <html:errors> tag in the specified input page to display the validation failure
messages to the end user.
Step 5:- Develop validation.xml and place it in the WEB-INF directory.
Step 6:- Place validator-rules.xml(built-in file as a part of framework) into WEB-INF.
Step 7:- Configure ValidatorPlugIn in Struts configuration file.
Step 8:- Place commons-validator-1.3.1.jar file into the application's lib folder.
Q)Develop a Struts Application in which declarative validation is used for static form bean.
declvalidationloginapplication
login.jsp
Struts
Struts By L N Rao Page 31
loginfailed.jsp
welcome.jsp
WEB-INF
web.xml
struts-config.xml
validation.xml
validator-rules.xml
lib
7 jar files
classes
*.class(3 class files)
ApplicationResources.properties
http://localhost:8081/declvalidationloginapplication
____________________________________________________________________________________________________________
________
Day:-26
18/10/12
------------
ApplicationResources.properties
-------------------------------
errors.required={0} should not be empty
errors.minlength={0} should have atleast {1} characters
our.usr=User Name
our.pwd=Password
our.eight=8
Note:- first two keys are predefined and taken from validator-rules.xml. We have taken only two keys because
we are using validator framework provided two validations only - 1)required validation 2)minlength
validation.
Other three keys and corresponding values are user defined. They have been taken for parametric
replacement.
=>Supplying values to place holders of the Resource Bundle messages is known as parametric replacement.
=>We can have any number of place holders in a message of the Resource Bundle.
For eg.
{0} {1} {2} etc.
=>parametric replacement provides flexibility in displaying the errors messages to the user.
LoginForm.java
--------------
package com.nareshit.form;
import org.apache.struts.validator.ValidatorForm;
public class LoginForm extends ValidatorForm
{
private String username;
private String password;
public void setUsername(String username)
{
this.username = username;
}
public String getUsername()
{
return username;
}
public void setPassword(String password)
{
this.password = password;
}
Struts
Struts By L N Rao Page 32
public String getPassword()
{
return password;
}
//never write(override) validate method here -- BLUNDER!!!
}//form bean (action form)
struts-config.xml
-----------------
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="loginform" type="com.nareshit.form.LoginForm"/>
</form-beans>
<action-mappings>
<action path="/login" name="loginform" type="com.nareshit.controller.LoginAction"
validate="true" input="/login.jsp">
<forward name="ok" path="/welcome.jsp"/>
<forward name="notok" path="/loginfailed.jsp"/>
</action>
</action-mappings>
<message-resources parameter="ApplicationResources"/>
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>
</struts-config>
Q)What is the significance of validate-rules.xml?
=>To make validator framework provided built-in validators available to the Strust application.
Q)What is the significance of validation.xml?
=>Strust developer expresses to the framework, application's validation requirements through this file.
login.jsp
---------
-from the previous application
____________________________________________________________________________________________________________
________
Day:-27
19/10/12
--------
validation.xml
--------------
<form-validation>
<formset>
<form name="loginform" >
<field property="username" depends="required">
<arg position="0" key="our.usr"/>
</field>
<field property="password" depends="required,minlength">
<arg position="0" key="our.pwd"/>
<arg position="1" key="8" resource="false"/>
<var>
<var-name>minlength</var-name>
<var-value>8</var-value>
</var>
</field>
</form>
</formset>
</form-validation>
Struts
Struts By L N Rao Page 33
Q)Explain about the tags of validation.xml?
=>name attribute's value of <form> tag should match with the logical name of the form bean specified in Struts
configuration file. For which form bean fields built-in validators required is specified using <form> tag.
=>We can have as many <form> tags as there are form beans in the application.
=>depends attribute of <field> tag takes the logical name the built in validator.
We can also specify multiple values with comma seperator. For which field those validators are to be applied
is specified using property attribute.
=><arg> tags are for parametric replacement.
=><var> tag is used to supply the argument to a built in validator.
Q)How to apply declarative validation for dynamic form bean?
Step 1:- Configure the following in struts-config.xml
<form-bean name="loginform" type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="username" type="java.lang.String"/>
<form-property name="password" type="java.lang.String"/>
</form-bean>
Step 2:- In action class typecast ActionForm reference to DynaValidatorForm before before capturing the user
input.
For eg.
DynaValidatorForm daf = (DynaValidatorForm)form;
String user = (String)daf.get("username");
String pwd = (String)daf.get("password");
Note:- Other 7 steps are from declarative validations applying to static form beans approach only.
____________________________________________________________________________________________________________
________
Day:-28
20/10/12
-------------
Q)How to make use of validator framework provided client side validation support?
Step 1:- Make use of <html:javascript> tag in the input page of the struts application.
Step 2:- Invoke a special JAvaScript function through event handling in the input page.
Q)How does Struts provided client side validation code function?
=>When the input jsp is executed, "javascript" tag of html library is executed. For this tag logical name of the
form bean should be supplied as value (to "formName" attribute).
=>Validator framework provided JavaScript functions code is appended in line by the tag handler of "javascript"
tag.
=>A specified JavaScript function also is generated and appended. That function name validateXXX(). "XXX" stands
for the logical name of the form bean. This method only calls the validation performing JavaScript functions.
=>When user clicks on the submit button, "onsubmit" event is raised and the special function is called. Internally
that function calls the JavaScript functions and client side validation is performed.
Q)Provide client side validation support also to "declvalidationloginapplication".
=>All the files are from this application only. "login.jsp" has to be modified in order to enable client side
validation support.
login.jsp
---------
<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html"%>
<HTML>
<HEAD>
<html:javascript formName="loginform"/>
</HEAD>
<BOdY BGCOLOR="yellow">
<CENTER>
<H1>Login Screen</H1>
<FONT SIZE="3" COLOR="red">
<html:errors/>
</FONT>
<html:form action="/login" method="POST" onsubmit="return validateloginform(this);">
Struts
Struts By L N Rao Page 34
Username <html:text property="username"/>
<BR>
Password <html:password property="password" />
<BR>
<html:submit>Login</html:submit>
</html:form>
</CENTER>
</BODY>
<HTML>
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Day:-29
22/10/12
-------------
Q)Modify the loginapplication so as to give same input page to the user if authentication is failed.
ApplicationResources.properties
-------------------------------
login.error=user name or password is wrong
struts-config.xml
-----------------
<action name="loginform" path="/login" type="com.nareshit.controller.LoginAction" input="/login.jsp">
<forward name="ok" path="/login.jsp"/>
</action>
login.jsp
---------
.....
<BODY>
<CENTER>
<FONT SIZE="5" COLOR="red">
<html:errors property="hello"/>
</FONT>
<H1>Welcome to Nareshit</H1>
<html:form action="/login" method="POST">
....
</CENTER>
</BODY>
LoginAction.java
----------------
public class LoginAction extends Action
{
LoginModel lm = new LoginModel();
public ActionForward execute(....)
{
.....
boolean = b = lm.isAuthenticated(user,pwd);
if(b)
{
mapping.findForward("ok");
}
else
{
ActionMessages am = new ActionMessages();
am.add("hello",new ActionMessage("login.error"));
addErrors(request,am); //programmatical validation like error
adding code
return mapping.getInputForward();
}
}
}
Struts
Struts By L N Rao Page 35
Day:-30
25/10/12
------------
Q)Develop a Struts Application that implements a virtual shopping cart.
virtualshoppingcartapplication
checkout.jsp
noitems.jsp
shoppage.jsp
visitagain.jsp
WEB-INF
web.xml
struts-config.xml
lib
*.jar(6 jar files)
struts-extras-1.3.10.jar
src
Product.java
ShoppingAction.java
ShoppingForm.java
ShoppingService.java
classes
*.classes
http://localhost:8081/virtualshoppingcartapplication
web.xml
-------
=>Make shopping.jsp as home page.
ShoppingService.java
--------------------
package com.nareshit.service;
import java.util.Map;
import java.util.Collection;
public class ShoppingService
{
public void addItem(Map m,Product p)
{
m.put(p.getPCode(),p);
}
public void removeItem(Map m,String pcode)
{
m.remove(pcode);
}
public Collection<Product> getAllItems(Map m)
{
Collection<Product> items = m.values();
return items;
}
}
=>"shoppingcartappflow.bmp"
1:- ASreceiving client request upon web from submission and capturing atleast one request parameter
(name & value).
2:- AS creating ShoppingForm instance and populating atleast one of its properties(pcode,quantity & submit).
3:- AS creating ShoppingAction instance and invoking its execute method.
4a:- execute() method calling addItem() or removeItem() business method of ShoppingService(model component).
4b:- execute method calling getAllItems() business method of model component.
5a:- either addItem() Or removeItem() of business component getting executed.
5b:- getAllItems() getting executed.
6a:- addItem() OR removeItem() returning nothing to execute() method.
6b2:- getAllItems() returning a collection of products to execute() method.
7a:- execute() method returning "shoppingpage" view mapping information to AS.
7b2:- execute() method returning "itemdetails" view mapping information to AS.
Struts
Struts By L N Rao Page 36
7b1:- execute() method returning "noitems" view mapping information to AS.
7:- execute() method returning "farewel" view mapping information to AS.
struts-config.xml
-----------------
<struts-config>
<form-beans>
<form-bean name="shoppingform" type="com.nareshit.view.ShoppingForm"/>
</form-beans>
<action-mappings>
<action path="/shopping" name="shoppingform" type="com.nareshit.controller.ShoppingAction">
<forward name="shoppingpage" path="/shoppage.jsp" redirect="true"/>
<forward name="noitems" path="/noitems.jsp"/>
<forward name="itemdetails" path="/checkout.jsp"/>
<forward name="farewel" path="/visitagain.jsp"/>
</action>
<action path="/shoppingpage" parameter="/shoppage.jsp"
type="org.apache.struts.actions.ForwardAction">
</action> <!-- to create hyperlink -->
</action-mappings>
<message-resources parameter="ApplicationResources"/>
</struts-config>
__________________________________________________________________________________________________________
Day:-31
26/10/12
------------
ShoppingForm.java
-----------------
package com.nareshit.view;
import org.apache.struts.action.ActionForm;
pbulic class ShoppingForm extends ActionForm
{
private String pcode;
private int quantity;
private String submit; //to hold submit button caption
//getters & setters
}
Product.java
-------------
package com.nareshit.service;
public class Product implements java.io.Serializable
{
private String pcode;
private int quantity;
//setters & getters
}//domain object(data transfer object)
ShoppingAction.java
-------------------
package com.nareshit.controller;
import org.apache.struts.action.*;
import javax.servlet.http.*;
import java.util.*;
import com.nareshit.service.Product;
import com.nareshit.service.ShoppingService;
Struts
Struts By L N Rao Page 37
import com.nareshit.view.ShoppingForm;
public class ShoppingAction extends Action
{
ShoppingService ss = new ShoppingService();
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,
HttpServletResponse response)
{
String responsePage = "shoppingpage";
ShoppingForm sf = (ShoppingForm) form;
String sb = sf.getSubmit();
HttpSession session = request.getSession(); //local variable is thread safe
//indivisual session for each user
Map cart = (Map) session.getAttribute("cart"); //local variable is thread safe
//unique cart for each user
if(cart==null)
{
cart = new HashMap();
session.setAttribute("cart",cart);
}
if(sb.equals("ADDITEM"))
{
Product p = new Product();
p.setPcode(sf.getPcode());
p.setQuantity(sf.getQuantity());
ss.addItem(cart,p); //business method call
}
else if(sb.equals("REMOVEITEM"))
{
ss.removeItem(cart,sf.getPcode());
}
else if(sb.equals("SHOWITEMS"))
{
Collection<Product> products = ss.getAllItems(cart); //business method call
if(products.size() == 0)
{
responsePage = "noitems";
}//inner if
else
{
request.setAttribute("products",products);
responsePage = "itemdetails";
}
}//if
else
{
session.invalidate();
responsePage = "farewel";
}
}
return mapping.findForward(responsePage);
}//execute()
Q)How to create a hyperlink in the jsps of a struts application?
Step 1:- configure a built-in action class in struts configuration file.
For eg.
<action path="/shoppingpage" parameter="/shoppage.jsp"
type="org.apache.struts.actions.ForwardAction"/>
Step 2:- Create the link using <html:link> tag.
For eg.
<html:link action="shoppingpage">Thank You. Visit Again to shop again </html:link>
Step 3:- Place additionally "struts-extras-1.3.10.jar" file into lib folder.
Struts
Struts By L N Rao Page 38
noitems.jsp
-----------
<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %>
<html>
<body bgcolor="cyan">
<h1>No items in your shopping cart</h1>
<html:link action="shoppingpage">Home</html:link>
</body>
</html>
visitagain.jsp
--------------
<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %>
<html>
<body bgcolor="cyan">
<html:link action="shoppingpage">Thank You. Visit again to shop more</html:link>
</body>
</html>
____________________________________________________________________________________________________________
________
Day:-32
27/10/12
------------
shoppage.jsp
------------
<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html"%>
<HTML>
<BODY BGCOLOR="wheat">
<CENTER>
<H2>Welcome to shopping Mall</H2>
<html:form action="shopping">
Select Product Type
<html:select property="pcode">
<html:option value="p101">p101</html:option>
<html:option value="p102">p102</html:option>
<html:option value="p103">p103</html:option>
<html:option value="p104">p104</html:option>
<html:option value="p105">p105</html:option>
</html:select>
<BR><BR>
Product Quantity
<html:text property="quantity" value=""/>
<BR><BR>
<html:submit property="submit" value="ADDITEM"/>
<html:submit property="submit" value="REMOVEITEM"/>
<html:submit property="submit" value="SHOWITEMS"/>
<html:submit property="submit" value="LOGOUT"/>
</html:form>
</CENTER>
<BODY>
</HTML>
checkout.jsp
------------
<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %>
<%@ taglib prefix="bean" uri="http://struts.apache.org/tags-bean" %>
<%@ taglib prefix="logic" uri="http://struts.apache.org/tags-logic" %>
<HTML>
Struts
Struts By L N Rao Page 39
<BODY BGCOLOR="yellow">
<H1>Your shopping cart item</H1>
<H2>
<logic:iterate scope="request" name="products" id="product">
Product Code: <bean:write name="product" property="pcode"/>
Quantity: <bean:write name="product" property="quantity"/>
<BR><BR>
</logic:iterate>
</H2>
<html:link action="shoppingpage">HOME</html:link>
</BODY>
</HTML>
Q)Develop a struts application in which user registration use-case is implemented in multiple request response
cycles.
registerapplication
register1.jsp
register2.jsp
failure.jsp
success.jsp
WEB-INF
*.xml
lib
*.jar(6 jar files)
src
Register1Action.java
Register2Action.java
RegisterForm.java
RegisterService.java
Registration.java
classes
*.class
http://localhost:8081/registerapplication
Register1Action.java
--------------------
public class Register1Action extends Action
{
public ActionForward execute(....)
{
return mapping.findForward("success");
}
}
Register2Action.java
--------------------
import org.apache.commons.beanutils.BeanUtils;
public class Register2Action extends Action
{
private static final String SUCCESS = "success";
private static final String FAILURE = "failure";
RegisterService registerService = new RegisterService();
public ActionForward execute(....)
{
RegisterForm registerForm = (RegisterForm)form;
String responseKey = FAILURE;
Registration registration = new Registration(); //domain object
BeanUtils.copyProperties(registration,registerForm);
boolean flag = registerService.doRegistration(registration);
if(flag)
responseKey = SUCCESS;
return mapping.findForward(responseKey);
Struts
Struts By L N Rao Page 40
}
}
register2.jsp
-------------
<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %>
<html>
<body bgcolor="pink">
<center>
<h1>
Please fill the following things
to complete the registration
</h1>
<html:form action="register2" method="post">
<html:hidden property="name" write="registerForm.name"/>
<html:hidden property="password" write="registerForm.password"/>
<html:hidden property="profession" write="registerForm.profession"/>
Cell : <html:text property="cell"/>
<br><br>
Gender : <html:radio property="gender" value="male">male</html:radio>
<html:radio property="gender" value="female">female</html:radio>
<br><br>
<html:checkbox property="agree"/>I agree the terms and conditions of the
registration
<br><br>
<html:submit>Complete Registration</html:submit>
</html:form>
</center>
</body>
</html>
____________________________________________________________________________________________________________
________
Day:-33
29/10/12
--------
success.jsp
-----------
<html>
<body bgcolor="yellow">
<h1>You have been successfully registered</h1>
</body>
</html>
register1.jsp
-------------
<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html"%>
<html>
<body bgcolor="cyan">
<center>
<h1>Welcome to register page</h1>
<html:form action="register1" method="post">
Name : <html:text property="name"/>
<br>
Password : <html:password property="password"/>
<br>
Profession :
<html:select property="profession">
<html:option value="Engineer">Engineer</html:option>
<html:option value="Businessman">Businessman</html:option>
<html:option value="Others">Others</html:option>
</html:select>
<br>
<html:submit>Register</html:submit>
Struts
Struts By L N Rao Page 41
</html:form>
</center>
</body>
</html>
failure.jsp
-----------
<html>
<body bgcolor="pink">
<h1>
Unable to register you. Please try after some time.
</h1>
</body>
</html>
web.xml
-------
=>Make register1.jsp the home page.
struts-config.xml
-----------------
<struts-config>
<form-beans>
<form-bean name="registerForm" type="com.nareshit.view.RegisterForm"/>
</form-beans>
<action-mappings>
<action path="/register1" name="registerForm" type="com.nareshit.controller.Register1Action">
<forward name="success" path="/register2.jsp"/>
</action>
<action path="/register2" name="registerForm" type="com.nareshit.controller.Register2Action">
<forward name="success" path="/success.jsp"/>
<forward name="failure" path="/failure.jsp"/>
</action>
</action-mappings>
</struts-config>
RegisterForm.java
-----------------
package com.nareshit.view;
import org.apache.struts.action.ActionForm;
public class RegisterForm extends ActionForm
{
private String cell;
private String profession;
private String name;
private String gender;
private String password;
private boolean agree; //boolean isAgree() & boolean getAgree() are same
//setters & getters
}
Registration.java
-----------------
=>It is a POJO and is similar to RegisterForm.java
RegisterService.java
--------------------
package com.nareshit.struts;
public class RegisterService
{
public boolean doRegistration(Registration registration)
Struts
Struts By L N Rao Page 42
{
boolean flag = false;
//using any data access mechanism persist registration object(state).
flag = registration.isAgree();
return flag;
}
}
______________________________________________
Tiles
Q)What are the drawbacks of jsp include mechanism?
=>JSP incluse mechanism is used to develop composite views in a Java Web Application.
=>JSP include mechanism promotes reusability of output generation code across pages of the website.
=>JSP include mechanism has the following limitations
1.)Page design is not reusable in developing different composite views of the website.
2.)As included page name is hardcoded in the including pages, it is error prone if included
page name is changed at later stage.
Q)How to overcome JSP include mechanism limitations in the jsps of a struts application?
=>Using Tiles concept of Struts.
Q)What is Tiles in the context of Struts?
=>Tiles is a sub framework of Struts.
=>Tiles is plugged into a Struts application to develop composite views.
=>Tiles overcomes all the limitations of JSP include mechanism.
=>Tiles ensures consistent look & feel of the web pages of the website.
_________________________________________________________________________________________________________
Day:-34
30/10/12
-----------
Q)How to make use of Tiles in a Struts application?
Step 1:- Develop layout page(s).
Step 2:- Develop content pages,
Step 3:- Develop tiles-defs.xml.
Step 4:- Enable tiles by plugging into the Struts Application.
Step 5:- place struts-tiles-1.3.10.jar file additionally into the lib folder.
Step 6:- specify the chain-config.xml as init parameter to ActionServlet in web.xml.
Step 7:- use the tiles definition.
Q)Develop a Struts Application in which, Tiles is used to create the composite views.
=>Refer to handout.
Q)What is the significance of tiles-defs.xml?
=>For each composite view of the application, one definition is mentioned in this xml file.
A logical name is given to each definition.
=>In each definition, layout page is specified and the actual jsps that are to be assembled
into one composite view are also specified.
=>When a tiles definition is used, Tiles subframework performs the assembling of all the
simple views(each tile) into a composite view around the layout page.
Q)What is the significance of chain-config.xml?
=>Earlier to Struts1.3, Tiles sub framework was using Request Processor while assembling the views.
In Struts 1.3.x, this xml file is assisting Tiles in creating the composite views.
____________________________________________________________________________________________________________
________
Day:-35
31/10/12
--------
Q)How to make use of a tiles definition?
1.)<tiles:insert definition="logical name"/>
2.)<forward name="logical name of the path to the view" path="logical name of the tiles definition"/>
Struts
Struts By L N Rao Page 43
3.)<action path="/actionpath" forward="logical name of the tiles definition"/>
=>Generally, if home page is the composite view, first one is used.
=>When user submitted the form, the response page has to be composite view means the second one is used.
=>When user clicked on the hyper link the target page has to have composite view means go for the third
style of using the tiles definition.
____________________________________________
Internationalization(i18n)
--------------------------
Q)What is i18n?
=>Providing multilingual support to the website without changing application's source code is nothing
but i18n(internationalization).
=>Once the Struts application is i18n enabled, based on user preferred language, web pages can be
displayed.
Q)How to implement i18n in a Struts Application?
Step 1:- Develop as many resource bundles as the number of languages that you want to support.
Resource Bundle keys are common. Only values will be in corresponding languages.
Step 2:- In JSPs don't write language specific template text. Instead, make use of bean library's
message tag that can retrieve language content from the appropriate resource bundle
based on user preferred language.
For eg.
<bean:message key="resource bundle key"/>
____________________________________________________________________________________________________
Day:-36
01/11/12
------------
Q)How does i18n .....
//to do
=>Browser sends user preferred language to the web server using Accept-langugage HTTP header.
=>Web server passes on that information to the servlet engine.
=>Encapsulation of (Object oriented representation of) user preferred language is nothing but
java.util.Locale object.
=>Container creates Locale object encapsulating user preferred language and stores it
(its reference ) into HttpServletRequest object.
=>HttpServletRequest has getlocale method that returns Local object.
Local local = request.getLocale();
=>Struts Framework gets Locale object and stores it into the session scope.
=>message tag of bean library selects the appropriate resource bundle based on Locale
object stored in session scope.
Q)What is the limitation in the above i18n application?
=>User has to change the browser's settings explicitely.
=>On the home page, language options should have been given for the user to select the
preferred language.
Q)How to make use of LocaleAction in a i18n Struts Application?
Step 1:- configure LocaleAction in struts-config.xml.
Step 2:- configure a special form bean to hold user specified locale details.
i.e. language,country,varient&page
Specify the logical name of this bean for LocaleAction configuration.
Step 3:- create links on home page that target LocaleAction class. specify the language and
page request parameters as part of query string.
Step 4:- copy struts-extras-1.3.10.jar in lib folder
Q)Develop an i18n enabled struts application that provides mutlti lingual support for the
end-users without the need of changing the browser settings.
Struts
Struts By L N Rao Page 44
=>Refer to the handout.(localeapplication page 11)
____________________________________________________________________________________________________________
________
Day:-37
02/11/12
-----------
Q)Explain about DispatchAction.
=>org.apache.struts.actions.DispatchAction is one of the built-in action classes provided by Struts
Framework.
=>Within a single action class to unify related multiple use-cases, this action class is used.
Note:- Normally, action classes are use-case specific. This built-in action class enables us to develop
domain object specific action classes rather than use-case specific action classes.
Q)How to make use of DispatchAction in a Struts application?
Step 1:- Develop a user defined action class that extends DispatchAction.
Step 2:- implements one user defined method per use-case within the action class.
User defined methods should have the prototype of execute() method.
For eg.
public ActionForward insertEmp(ActionMapping mapping,ActionForm form,HttpServletRequest request,
HttpServletResponse response)throws Exception
Step 3:- Configure the user defined action class in struts configuration file. Make use of "parameter"
attribute in <action> tag. Give any user defined name as value for that attribute.
For eg.
<action path="/both" .... parameter="admin"/>
Step 4:- develop use-case specific input pages as usual with the following additional things.
a.)all input screens should point to the same action class(path).
b.)request parameter name of each input page should be that of the name given as the value to the
"parameter" attribute of <action> tag.
For eg.
<html:submit property="admin">insert</html:submit>
<html:submit property="admin">delete</html:submit>
c.)request parameter value of the input screen i.e. caption of the submit button should be the user defined
method name given in action class.
Step 5:- struts-extras-1.3.10.jar place into classpath additionally and place into lib folder.
Q)Struts application in which two built-in action, ForwardAction & DispatchAction, functionality is used.
=>refer to the handout - forwarddispatchapplication page 3
Q)How does DispatchAction function?
=>When ActionServlet creates the user defined action class instance, it inherits execute method of
DispatchAction class.
=>ActionServlet calls the execute method.
=>Based on the submit button caption, execute method knows to call the corresponding user defined method.
____________________________________________________________________________________________________________
________
Day:-38
03/11/12
--------
Q)What are the limitations of DispatchAction?
1.)can't support i18n
2.)can't use different form beans for different use-cases.
Q)Explain about LookupDispatchAction.
=>org.apache.struts.actions.LookupDispatchAction is a sub class of DispatchAction.
=>Its purpose is same as that of DispatchAction only, with additional i18n support.
Q)How to make use of LookupDispatchAction in a Struts Application?
Step 1:- Develop resource bundle with appropriate key,value pairs.
Step 2:- develop a Java class that extends LookupDispatchAction.
Step 3:- implement as many user defined methods as there are use-cases to unify.
Method prototype should be that of execute method except name.
Note:- should not override execute() method like in DispatchAction.
Struts by l n rao
Struts by l n rao
Struts by l n rao
Struts by l n rao
Struts by l n rao
Struts by l n rao
Struts by l n rao
Struts by l n rao
Struts by l n rao
Struts by l n rao
Struts by l n rao
Struts by l n rao
Struts by l n rao
Struts by l n rao

Mais conteúdo relacionado

Mais procurados

Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu   (obscure) tools of the trade for tuning oracle sq lsTony Jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
InSync Conference
 

Mais procurados (19)

Oracle DBA interview_questions
Oracle DBA interview_questionsOracle DBA interview_questions
Oracle DBA interview_questions
 
Relational Database Management System
Relational Database Management SystemRelational Database Management System
Relational Database Management System
 
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu   (obscure) tools of the trade for tuning oracle sq lsTony Jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
 
Not so blind SQL Injection
Not so blind SQL InjectionNot so blind SQL Injection
Not so blind SQL Injection
 
Oracle database 12c sql worshop 2 student guide vol 2
Oracle database 12c sql worshop 2 student guide vol 2Oracle database 12c sql worshop 2 student guide vol 2
Oracle database 12c sql worshop 2 student guide vol 2
 
1z0 034 exam-upgrade oracle9i10g oca to oracle database 11g ocp
1z0 034 exam-upgrade oracle9i10g oca to oracle database 11g ocp1z0 034 exam-upgrade oracle9i10g oca to oracle database 11g ocp
1z0 034 exam-upgrade oracle9i10g oca to oracle database 11g ocp
 
Sql interview-book
Sql interview-bookSql interview-book
Sql interview-book
 
Jdbc tutorial
Jdbc tutorialJdbc tutorial
Jdbc tutorial
 
AJP
AJPAJP
AJP
 
Adbms lab manual
Adbms lab manualAdbms lab manual
Adbms lab manual
 
Untangling Healthcare With Spark and Dataflow - PhillyETE 2016
Untangling Healthcare With Spark and Dataflow - PhillyETE 2016Untangling Healthcare With Spark and Dataflow - PhillyETE 2016
Untangling Healthcare With Spark and Dataflow - PhillyETE 2016
 
JPA 2.1 performance tuning tips
JPA 2.1 performance tuning tipsJPA 2.1 performance tuning tips
JPA 2.1 performance tuning tips
 
Oracle 9i
Oracle 9iOracle 9i
Oracle 9i
 
JDBC Part - 2
JDBC Part - 2JDBC Part - 2
JDBC Part - 2
 
Sql full tutorial
Sql full tutorialSql full tutorial
Sql full tutorial
 
SetFocus Portfolio
SetFocus PortfolioSetFocus Portfolio
SetFocus Portfolio
 
Jdbc ja
Jdbc jaJdbc ja
Jdbc ja
 
Data access
Data accessData access
Data access
 
SQL Injection Tutorial
SQL Injection TutorialSQL Injection Tutorial
SQL Injection Tutorial
 

Semelhante a Struts by l n rao

What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2
Santosh Singh Paliwal
 
Apachecon 2002 Struts
Apachecon 2002 StrutsApachecon 2002 Struts
Apachecon 2002 Struts
yesprakash
 

Semelhante a Struts by l n rao (20)

Struts
StrutsStruts
Struts
 
Struts
StrutsStruts
Struts
 
What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2
 
Struts framework
Struts frameworkStruts framework
Struts framework
 
Struts2 notes
Struts2 notesStruts2 notes
Struts2 notes
 
Struts framework
Struts frameworkStruts framework
Struts framework
 
Skillwise Struts.x
Skillwise Struts.xSkillwise Struts.x
Skillwise Struts.x
 
Apache Struts 2 Framework
Apache Struts 2 FrameworkApache Struts 2 Framework
Apache Struts 2 Framework
 
Apachecon 2002 Struts
Apachecon 2002 StrutsApachecon 2002 Struts
Apachecon 2002 Struts
 
Struts2 in a nutshell
Struts2 in a nutshellStruts2 in a nutshell
Struts2 in a nutshell
 
Struts2.x
Struts2.xStruts2.x
Struts2.x
 
Struts
StrutsStruts
Struts
 
Struts ppt 1
Struts ppt 1Struts ppt 1
Struts ppt 1
 
Struts2.0basic
Struts2.0basicStruts2.0basic
Struts2.0basic
 
Your tuning arsenal: AWR, ADDM, ASH, Metrics and Advisors
Your tuning arsenal: AWR, ADDM, ASH, Metrics and AdvisorsYour tuning arsenal: AWR, ADDM, ASH, Metrics and Advisors
Your tuning arsenal: AWR, ADDM, ASH, Metrics and Advisors
 
Struts2 - 101
Struts2 - 101Struts2 - 101
Struts2 - 101
 
Ibm
IbmIbm
Ibm
 
Struts
StrutsStruts
Struts
 
Struts Ppt 1
Struts Ppt 1Struts Ppt 1
Struts Ppt 1
 
Lecture 05 web_applicationframeworks
Lecture 05 web_applicationframeworksLecture 05 web_applicationframeworks
Lecture 05 web_applicationframeworks
 

Último

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Último (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 

Struts by l n rao

  • 1. Struts Struts By L N Rao Page 1 Day:1 14/09/12 Q) Explain about struts configuration file. =>In this xml document the total flow control of the application is specified. =>For each use-case relationship among view components and subcontroller component is specified in this File. =>ActionServlet uses this file as input to understand the flow control information of each use-case of the struts application. =>standard name for this file is struts-config.xml =>only one* configuration file per struts application. =>ActionServlet is able to act as a reusable front controller because of logical names given to application components in this xml file. Q)Explain about form beans of a Struts Application. =>A form bean is a Struts Application is also known as action form(ActionForm). =>A public java class that extends org.apache.struts.action.ActionForm is eligible to act as form bean in a Struts application. =>An action form is a Java Bean. =>ActionForm implements java.io.Serializable interface. =>For each web form* of the application one action form class is developed which is a Java Bean and hence the name. =>In a user defined form bean class as many instance variables are to be declared as there are input fields in the corresponding web form. =>form bean variable names should match with that of the corresponding user control's request parameters. =>Form bean can have validate() and reset() methods in addition to the accessors and mutators. -modification = mutation =>form bean instance holds view data temporarily in object oriented manner which is going to be transferred to the Model layer by controller layer i.e. In a Struts application, form bean just acts as a data container that holds View data and hence is considered as a view component. =>A form bean can not act as a Data Transfer Object in a web-enabled Java Enterprise Application as it is not a POJO (Plain Old Java Object). Note: - A java class is said to be a POJO if it does not inherit from any technology or framework specific Library class or interface. ---form & form controls is always created using struts tags in struts project. Day:-2 15/09/12 ------------ Q)Explain about action classes of Struts. =>An action class is a user defined java class that extends org.apache.struts.action.Action class. =>For each use-case of struts application we develop an action class. =>action class generally does the following duties - 1.) Capturing the user input from the form bean.(view layer data cptured by the controller for transferring to the model) 2.) Invoking the business method of the model component for data processing. 3.) Storing the processed data received from the model into scope. 4.) Returning view mapping information to the ActionServlet(Front Controller). =>Action classes are sub controllers. =>struts developers consider action classes as mini servlets. -b/c it has the code similar to that in servlets -but it not at all servlets as it can not run by servlet engine neither it is configured in configuration File =>Action classes are configured in struts configuration file and are given logical names(known as action path). =>In struts application, input screens point to action classes. =>An action class is a singleton similar to servlet. - form beans are never singleton Q)What are not the duties of the action class(sub controller). =>duties of the front controller - -validating the user input -capturing the user input -request dispatching -generic flow control code is written into the front controller i.e. it is not specific to each use Cases.
  • 2. Struts Struts By L N Rao Page 2 ------------------------------------------------------------------------------------------------------------------------------------------ Day:-3 17/09/12 ------------ Q)Explain about ActionServlet. =>ActionServlet is abuilt-in front-controller for a struts application. =>For each client request framework funstionality entry point is ActionServlet. =>ActionServlet does its duties in two phases. 1.)At the time of Struts Appplication deployment. 2.)when the client request comes. =>To make a Java Web Application Struts-enabled, we need to do 3 things in web.xml. 1.)register ActionServlet 2.)instruct the container to pre-load & pre-initialize the ActionServlet. 3.)configure ActionServlet as front-controller. =>As soon as the struts application is deployed , init() method of the ActionServlet is executed by servlet engine and struts configuration file is loaded so that ActionServlet knows the entire application flow at the time of deployment only. =>When client request comes, ActionServlet does* the following things in general. 1.)Identifying the subcontroller based on the action path from the web form. 2.)creating the form bean instance* and populating its fields with the user input. 3.)validating the user input 4.)creating the instance* of action class. 5.)calling the execute method of action class. 6.)switching the control to the view component based on view mapping info received from the sub controller. Note:- ActionServlet makes use of invisible work horse of the Struts 1.x to perform all the above duties.i.e. it uses RequestProcessor. Q) Explain about the jsps of the struts application. =>jsps are used in two areas in struts appplications. 1.) input page development 2.) response page development =>input jsp pages are created in struts applications using html tags & "struts html jsp tag library tags". =>reponse page development time Struts 4 tag libraries* are to be used. Day:-4 18/09/12 ----------- --in notebook Day:-5 20/09/12 ---------- Struts-config.xml ----------------------- <struts-config> <form-beans> <form-bean name="loginform" type="com.nareshit.form.LoginForm"/> </form-beans> <action-mappings> <action path="/login" name="loginform" type="com.nareshit.controller.LoginAction"> <forward name="ok" path="/welcome.jsp"/> <forward name="notok" path="/loginfailed.jsp"/> </action> </action-mappings> </struts-config> LoginForm.java -------------------- package com.nareshit.form; import org.apache.struts.action.ActionForm;
  • 3. Struts Struts By L N Rao Page 3 public class loginForm extends ActionForm { private String username; private String password; public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } }//Java Bean - form bean (action form) welcome.jsp --------------- <html> <body bgcolor="yellow"> <h1>Welcome to www.nareshit.com</h1> </body> </html> loginfailed.jsp --------------- <html> <body bgcolor="red"> <h1>Login failed. Invalid username or password</h1> <!--<h1>Login failed. Invalid username or password <a href="login.jsp">Try Again</a></h1>--> </body> </html> Problems - 1.one view is deciding which view to switch the control (but it's the work of co 2.we are hardcoding the original page name in one of the jsp Logical name based linking should only be there. ------------------------------------------------------------------------------------------------------------------------------------------ Day:-6 21/09/12 ------------ LoginModel.java ---------------------- pckage com.nareshit.service; public class LoginModel { public boolean isAuthenticated(String user,String pwd) { boolean flag = false; if(user.equals(pwd)) flag = true; return flag; } } LoginAction.java ---------------------- package com.nareshit.controller; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping;
  • 4. Struts Struts By L N Rao Page 4 import org.apache.struts.action.ActionForm; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.nareshit.form.LoginForm; import com.nareshit.service.LoginModel; public class LoginAction extends Action { LoginModel lm = new LoginModel(); public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request, HttpServletResponse response) { ActionForward af = null; LoginForm lf = (LoginForm)form; String user = lf.getUsername(); String pwd = lf.getPassword(); boolean b = lm.isAuthenticated(user,pwd); if(b) af = mapping.findForward("ok"); else af = mapping.findForward("notok"); return af; } } Note:- Place two jar files into classpath before compiling the action class source code- 1.)servlet-api.jar 2.)struts related jars(struts-core-1.3.10.jar) Place the following jar files into the lib folder:- commons-beanutils-1.8.0.jar commons-chain-1.2.jar commons-digester-1.8.jar commons-logging-1.0.4.jar struts-core-1.3.10.jar struts-taglib-1.3.10.jar Day:-7 24/09/12 ------------ Q)What happens in the background when the struts application(loginapplication) is deployed into J2EE web container? =>As soon as the struts application is deployed, web container reads web.xml and pre-initialize ActionServlet. =>Within the init method of ActionServlet, code is implemented to read struts-config.xml and convert the xml Information into java format. ActionServlet uses the digester API for this purpose. =>At the time of application deployment only, ActionServlet knows the total application configuration details (Struts related). Q)What happens in the background when login.jsp is executed? =>When the client request goes for the struts application with the specified url for eg. http://localhost:8081/loginapplication, as login.jsp is configured as the homepage, jsp engine executes login.jsp. =><form> tag of Struts html JSP tag library is executed and does the following things. 1.) It generates html <form> tag 2.) ".do" extension is added to action attribute value 3.) session id is appended to the URL using URL rewriting =>All struts tags generate HTML tags. =>login.jsp produced dynamic web content (input page source code which is pure html content) is handed over to the web server. =>Web server sends the input page to the client. Q)What happens in the background when user submits the input page by entering the username and password? =>ActionServlet (infact RequestProcessor) does the following things - 1.) "/login.do" is picked from the url, truncates ".do" extension. 2.) using "/login" identifies the use-case. 3.) creates appropriate form bean instance or retrieve its instance from the scope. 4.) populates from bean fields with user input.
  • 5. Struts Struts By L N Rao Page 5 5.) creates LoginAction class instance and calls execute method by supplying use-case information as the first argument, LoginForm instance as the second argument and request & response arguments. 6.)logical name of the jsp URL is encapsulated into ActionForward object and is returned to ActionServlet 7.)ActionServlet uses ActionForward object provided view mapping information to switch the control to the appropriate jsp. Note:- Object Oriented representation of (encapsulation of) one action's forward is nothing but ActionForward object. Day:-8 25/09/12 ------------ Q)Modify the previous application so as to verify the user credentials against the database. Model Layer files:- ---------------------- LoginModel.java DBUtil.java ojdbc14.jar(Driver jar file) Table :-REGISTRATION(username,password,emailid) DBUtil.java -------------- package com.nareshit.service; import java.sql.*; public class DBUtil { static { try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch(Exception e) { System.out.println(e); } } public static Connection getConnection()throws SQLException { return DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:server","nareshit","nareshit"); } public static void close(Connection con,Statement st,ResultSet rs) { try { if(rs!=null) rs.close(); if(st!=null) st.close(); if(con!=null) con.close(); } catch(SQLException e) { } } } LoginModel.java ---------------------- package com.nareshit.service; public class LoginModel { public boolean isAuthenticated(String user,String pwd) {
  • 6. Struts Struts By L N Rao Page 6 boolean flag = false; Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try { con = DBUtil.getConnection(); ps = con.prepareStatement("select * from registration where username=? and password=? "); ps.setString(1,user); ps.setString(2,pwd); rs = ps.executeQuery(); if(rs.next()) flag = true; } catch(SQLException e) { e.printStackTrace(); } finally { DBUtil.close(con,ps,rs); } return flag; } } Note:- If model layer implementation is modified controller and view components are unaffected. Q)Develop a Struts Application to implement the use-case of user registration. 4:- execute() method calling registerUser() of the model component. public boolean registerUser(String user,String pwd,String mailId) model layer files:- -------------------- DBUtil.java RegisterModel.java ojdbc14.jar configuration files:- ----------------------- web.xml struts-config.xml view layer files ------------------- register.jsp(input page) success.jsp registrationfailed.jsp RegisterForm.java(form bean) controller layer files -------------------------- RegisterAction.java web.xml:- =>make register.jsp the home page struts-config.xml ---------------------- <struts-config> <form-beans> <form-bean name="registerform" type="com.nareshit.form.RegisterForm"/> </form-beans> <action-mappings>
  • 7. Struts Struts By L N Rao Page 7 <action name="registerform" type="com.nareshit.controller.RegisterAction" path="/register"> <forward name="success" path="/success.jsp"/> <forward name="failure" path="/registrationfailed.jsp"/> </action> </action-mappings> </struts-config> ## action path is the logical name of the action class. register.jsp ------------ <%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %> <html> <body bgcolor="cyan"> <center> <h1>Register with www.nareshit.com</h1> <html:form action="/register" method="POST"> UserName <html:text property="username"/> <br><br> Password <html:password property="password"/> <br><br> Email Id <html:text property="emailid"/> <br><br> <html:submit>register</html:submit> </html:form> </center> </body> </html> RegisterForm.java ------------------------ package com.nareshit.form; import org.apache.struts.action.ActionForm; public class RegisterForm extends ActionForm { private String username; private String password; private String emailid; //setters & getters } -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------- Day:-9 26/09/12 RegisterAction.java:- -------------------------- package com.nareshit.controller; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionForward; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.nareshit.form.RegisterForm; import com.nareshit.service.RegisterModel; public class RegisterAction extends Action { RegisterModel model = new RegisterModel();
  • 8. Struts Struts By L N Rao Page 8 public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request, HttpServletResponse response) { RegisterForm rf = (RegisterForm)form; String user = rf.getUsername(); String pwd = rf.getPassword(); String emailid = rf.getEmailid(); boolean flag = rm.registerUser(user,pwd,emailid); if(flag) return mapping.findForward("success"); else return mapping.findForward("failure"); } } RegisterModel.java:- package com.nareshit.service; import java.sql.*; public class RegisterModel { public boolean registerUser(String user,String pwd,String eid) { boolean flag = false; Connection con = null; PreparedStatement ps= null; try { con = DBUtil.getConnection(); ps = con.prepareStatement("insert into registeration values(?,?,?)"); ps.setString(1,user); ps.setString(2,pwd); ps.setString(3,eid); flag = true; } catch(SQLException e) { e.printStackTrace(); } finally { DBUtil.close(con,ps,null); } return flag; } } success.jsp:- ----------------- <html> <body bgcolor="cyan"> <h1>Successfully registered with www.nareshit.com</h1> </body> </html> registrationfailed.jsp:- ------------------------------ <html> <body bgcolor="red"> <h1>Couldn't register you now.Please try later</h1> </body> </html> Q)What happens in the background when findForward() method is called on the ActionMapping object? ActionForward af = mapping.findForward("ok"); =>action class last duty being a sub controller is to provide view mapping info to the front controller. =>findForward() method takes logical name of the jsp path as argument and returns ActionForward object reference.
  • 9. Struts Struts By L N Rao Page 9 =>As soon as the struts application is deployed, for each <forward> tag of the use-case one ActionForward object is created and kept in HashMap object.That HashMap object reference is with ActionMapping object. =>When findForward() method is called on ActionMapping object, internally it calls get method on HashMap, retrives the already existing ActionForward object reference and returns to execute() method of action class. ------------------------------------------------------------------------------------------------------------------------------------------ Day:-10 27/09/12 ------------ Q)Develop a struts application in which end-user should be able to enter account number into the web form and get account details? controller layer files:- -------------------------- AccountAction.java 1.)End user entering the account nubmer into the web form produced by account.jsp and then submitting the form. 2.)ActionServlet capturing the account number.ActionServet populating the ActionForm fields with user inputs. 3.)ActionServlet instantiating AccountAction and calling its execute method 4.)execute() method is calling getAccountDetails() method of Model Component. 5.)getAccountDetails() method communicating with database. 6a.)getAccountDetails() method returning data transfer object i.e. Account object to execute() method. 6b.)getAccountDetails() method returning null to execute() method. 7a.)execute() method returning ActionForward object reference to ActionServlet encapsulating "success" logical name after storing DTO(data transfer object) in request scope. 7b.)execute() method returning ActionForward object to ActionServlet encapsulating "failure" logical name. 8a.)ActionServlet through request dispatching forwarding the control to accountdetails.jsp. 9a.)accountdetails.jsp retriving DTO state from request scope and producing the response page for the client. AccountAction.java --------------------------- package com.nareshit.controller; import org.apchae.struts.action.*; import javax.servlet.http.*; import com.nareshit.form.AccountForm; import com.nareshit.service.AccountModel; import com.nareshit.vo.Account; public class AccountAction extends Action { AccountModel am = new AccountModel(); public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request, HttpServletResponse response) { AccountForm af = (AccountForm)form; int ano = af.getAccno(); Account acc = am.getAccountDetails(ano); if(acc!=null) { request.setAttribute("account",acc); return mapping.findForward("success"); } else return mapping.findForward("failure"); }//execute() } AccountForm.java ------------------------- package com.nareshit.form; import apache.struts.action.ActionForm; public class AccountForm extends ActionForm { private int accno; public void setAccno(int accno) { this.accno = accno;
  • 10. Struts Struts By L N Rao Page 10 } public int getAccno() { return this.accno; } } AccountModel.java --------------------------- package com.nareshit.service; import com.nareshit.vo.Account; import java.sql.*; public class AccountModel { public Account getAccountDetails(int accno) { Account acc = null; Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try { con = DBUtil.getConnection(); ps = con.prepareStatement("Select * from account where accno=?"); ps.setInt(1,accno); rs = ps.executeQuery(); if(rs.next()) { acc = new Account(); acc.setAccno(rs.getInt(1)); acc.setName(rs.getString(2)); acc.setBalance(rs.getFloat(3)); } }//try catch(SQLException e) { e.printStackTrace(); } finally { DBUtil.close(con,ps,rs); } return acc; } } Account.java ------------------ package com.nareshit.vo; public class Account implements java.io.Serializable { private int accno; private String name; private Float balance; //setters & getters }//Value object class / Data Transfer Object class Note:- Model class can be running in business tier and controller can be running in web tier.Therefore, DTO must implement java.io.Serializable interface. noaccount.jsp ------------------- <html> <body bgcolor="cyan">
  • 11. Struts Struts By L N Rao Page 11 <h1>Account Doesn't exists</h1> </body> <html> account.jsp ---------------- <%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %> <html> <body bgcolor="cyan"> <center> <h1>Account Details retrived</h1> <html:form action="account" method="POST"> Account Number <html:text property="accno" value=""/> <br><br> <html:submit>GetAccountDetails</html:submit> </html:form> </center> </body> </html> accountdetails.jsp ------------------------ <%@ taglib prefix="bean" uri="http://struts.apache.org/tags-bean" %> <html> <body bgcolor="cyan"> <h1>Account Details</h1> Account Number: <bean:write name="account" property="accno"/> <br> Name : <bean:write name="account" property="name"/> <br> Balance: <bean:write name="account" property="balance"/> </body> </html> struts-config ---------------- <message-resources parameter="ApplicationResources"/> ===================================================================== Day:-11 28/09/12 ------------ struts-config.xml ----------------- <struts-config> <form-beans> <form-bean name="accountForm" type="com.nareshit.form.AccountForm"> </form-bean> </form-beans> <action-mappings> <action name="accountForm" type="com.nareshit.controller.AccountAction" path="/account"> <forward name="success" path="/accountdetails.jsp"> <forward name="failure" path="/noaccount.jsp"> </action> </action-mappings> <message-resources parameter="applicationResources"/> <!-- becuase bean library is used --> </struts-config> web.xml
  • 12. Struts Struts By L N Rao Page 12 ----------- Note:- make account.jsp a home page. Q)Develop a Struts application that takes balance range as input and displays all the account details that fall under that balance range. accountsapplication account.jsp noaccount.jsp accountdetails.jsp WEB-INF web.xml struts-config.xml src DBUtil.java AccountForm.java AccountModel.java Account.java AccountAction.java classes *.class lib *.jar(7 jar files) http://localhost:8081/accountsapplication AccountForm.java -------------------------- package com.nareshit.form; import org.apache.struts.action.ActionForm; public class AccountForm extends ActionForm { private String balanceRange; //setters & getters } AccountAction.java --------------------------- package com.nareshit.controller; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionModel; import javax.servlet.http.*; import java.util.List; public class AccountAction extends Action { AccountModel am = new AccountModel(); public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request, HttpServletResponse response) { AccountForm af = (AccountForm)form; String br = af.getBalanceRange(); StringTokenizer st = new StringTokenizer(br,"-"); float lower = Float.parseFloat(st.nextToken()); float upper = Float.parseFloat(st.nextToken()); List<Account> accounts = am.getAccountsDetails(lower,upper); if(accounts!=null)
  • 13. Struts Struts By L N Rao Page 13 { request.setAttribute("accounts",accounts); return mapping.findForward("success"); } else return mapping.findForward("failure"); }//execute() } Note:- web.xml,struts-config.xml,Account.java and DBUtil.java from the previous application. account.jsp ----------- <%@ taglib prefix="html" uri="http://struts.apache.org/tags-html"%> <html> <body bgcolor="cyan"> <center> <h1>Account Details Retrival</h1> <html:form action="account" method="POST"> Balance Range(lower-upper)<html:text property="balancerange"/> <br><br> <html:submit>get accounts details</html:submit> </html:form> </center> </body> </html> noaccount.jsp ------------- <html> <body bgcolor="cyan"> <center> <h1>With this balance range no Account exists</h1> </center> </body> </html> accountdetails.jsp ------------------------- <%@ taglib prefix="html" uri="http://struts.apache.org/tags-html"%> <%@ taglib prefix="bean" uri="http://struts.apache.org/tags-bean"%> <%@ taglib prefix="logic" uri="http://struts.apache.org/tags-logic"%> <html> <body bgcolor="cyan"> <center> <table border="1"> <tr> <td>ACCNO</td> <td>NAME</td> <td>BALANCE</td> </tr> <logic:iterate name="accounts" id="account" scope="request"> <tr> <td><bean:write name="account" property="accno"/></td> <td><bean:write name="account" property="name"/></td> <td><bean:write name="account" property="balance"/></td> </tr> </logic:iterate> </table> </center> </body> </html> AccountModel.java -------------------------- package com.nareshit.service; import java.sql.*; import java.util.List;
  • 14. Struts Struts By L N Rao Page 14 import java.util.ArrayList; import com.nareshit.vo.Account; public class AccountModel { public List<Account> getAccountsDetails(float lower,float upper) { List<Account> accounts = null; Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try { con = DBUtil.getConnection(); ps = con.prepareStatement("select * from Account where balance between ? and ?"); ps.setFloat(1,lower); ps.setFloat(2,upper); rs = ps.executeQuery(); if(rs.next()) { accounts = new ArrayList<Account>(); do { Account acc = new Account(); acc.setAccno(rs.getInt(1)); acc.setName(rs.getString(2)); acc.setBalance(rs.getFloat(3)); accounts.add(acc); }while(rs.next()); } }//try catch(SQLException e) { e.printStackTrace(); } finally { DBUtil.close(con,ps,rs); } return accounts; } } Day:-12 02/10/12 ------------ Q)Explain about Exception Handling in a struts application. =>In view components exception handling is not required. =>Even if exceptions are handled in model component, it does not come under exception handling in a Struts application(UI layer/Presentation layer of web-enabled enterprise Java application). =>Handling the exceptions in the controller component is nothing but exception handling in UI Layer. =>If exception handling is not implemented in controller layer , wrong information may go to the end user =>Exception handling is not possible in controller layer unless the raised exception is propagated to the controller by the model component. =>Model components propagate exceptions to controller components when their business methods are invokedin two scenarios. a.)data accessing time exception raised b.)communicating with database has not caused the exception i.e. data accessing time exception is not raised but while processing data business rule is violated. =>Always model components propagate user defined exceptions to sub controller components. =>In a struts application, exception handling is nothing but dealing with exceptions in action classes while they are communicating with model components.
  • 15. Struts Struts By L N Rao Page 15 Q)Modify the prototype of isAuthenticated() method of LoginModel when the method is performing database operation. =>public void isAuthenticated(String username,String password)throws LoginFailedException, ProcessingException Q)Modify the prototype of getAccountDetails() method of AccountModel of "accountapplication" so as to implement exception handling. =>public Account getAccountDetails(int accno)throws AccountNotFoundException,ProcessingException ------------------------------------------------------------------------------------------------------------------------------------------Day:-13 Day:-13 03/10/12 ----------- Q)Implement exception handling with UI layer of login application. prgexcploginapplication login.jsp loginfailed.jsp problem.jsp welcome.jsp WEB-INF struts-config.xml web.xml src LoginForm.java LoginModel.java LoginAction.java DBUtil.java processingException.java LoginFailedException.java =>"workFlow for loginapplication with exception 3-oct-12.bmp" 6a - isAuthenticated() method returning nothing to execute method indicating that authentication is successful. 6b - model component propagating LoginFailedException as no record is found in the database with that user name and password. 6c - model component propagating ProcessingException to sub controller upon database communication caused abnormal event. 7b - "failure" view mapping info passed to front controller 7c - "abnormal" view mapping info passed to front controller problem.jsp ---------------- <html> <body bgcolor="red"> <h1>Couldn't authenticate you right now.Please try later</h1> </body> </html> LoginFailedException.java ----------------------------------- package com.nareshit.exception; public class LoginFailedException extends Exception { } ProcessingException.java ---------------------------------- package com.nareshit.exception; public class ProcessingException extends Exception { } LoginModel.java ---------------------- package com.nareshit.service; import com.nareshit.exception.ProcessingException; import com.nareshit.exception.LoginFailedException; import java.sql.*;
  • 16. Struts Struts By L N Rao Page 16 import javax.servlet.http.*; public class LoginModel { public void isAuthenticated(String user,String pwd)throws ProcessingException,LoginFailedException { Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try { con = DBUtil.getConnection(); ps = con.prepareStatement("Select * from Registration where username=? and password=?"); ps.setString(1,user); ps.setString(1,pwd); rs = ps.executeQuery(); if(!rs.next()) throw new LoginFailedException(); } catch(SQLException e) { e.printStackTrace(); throw new ProcessingException(); } finally { DBUtil.close(con,ps,rs); } } } struts-config.xml ----------------------- we need to add the third forward within <action> tag. <action ...> ... <forward name="abnormal" path="/problem.jsp"/> </action> LoginAction.java ----------------------- package com.nareshit.controller; public class loginAction extends Action { LoginModel lm = new LoginModel(); public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request, HttpServletResponse response) { String viewInfo = "ok"; LoginForm lf = (LoginForm)form; String user = lf.getUsername(); String pwd = lf.getPassword(); try { lm.isAuthenticated(user,pwd); } catch(LoginFailedException e) { viewInfo="notok"; } catch(ProcessingException e) { viewInfo = "abnormal"; }
  • 17. Struts Struts By L N Rao Page 17 return mapping.findForward(viewInfo); } } Q)How is exception handling classified is a Struts Application? =>There are 2 types of Exception Handling in a Struts Application. 1.)Programmatical Exception Handling 2.)Declarative Exception Handling Q)What is Programmatical Exception Handling in a Struts Application? =>Within the execute method of Action class, placing the model component method call in try block and implementing correspoding exception handlers i.e. catch blocks, is nothing but Programmatical Exception Handling. =>In case of programmatical Exception Handling no support from Struts. Day:-14 04/10/12 ------------ Q)Modify the "accountapplication" so as to have programmatical exception handling implemented. prgexpaccountapplication account.jsp accountdetails.jsp noaccount.jsp problem.jsp WEB-INF web.xml struts-config.xml src AccountForm.java AccountAction.java AccountModel.java Account.java (DTO) DBUtil.java AccountNotFoundException.java ProcesssingException.java classes *.class lib *.jar =>"prgexpaccountaplication 03-oct-12.bmp" 6a:- DBMS returning one account record 6b:- DBMS returning no record i.e. Jdbc Driver creates empty resultset object 6c:- DBMS causing exception to model component 7a:- getAccountDetails() method returning Account object(DTO/POJO/Domain object) to execute method. 7b:- model component propagating AccountNotFound Exception to subcontroller 7c:- model component propagating ProcessingException to action class 8c:- "abnormal" view mapping info passed to frontcontroller problem.jsp ---------------- <html> <body bgcolor="red"> <h1>Couldn't process request now.Please try after some time.</h1> </body> </html> struts-config.xml ----------------------- =>add one additional <forward> tag for "problem.jsp" similar to that of previous application. AccountNotFoundException.java --------------------------------------------
  • 18. Struts Struts By L N Rao Page 18 package com.nareshit.exception; public class AccountNotFoundException extends Exception { } AccountModel.java -------------------------- try { ..... ..... if(rs.next()) { .... .... } else throw new AccountNotFoundException(); }//try catch(SQLException e) { e.printStackTrace(); throw new ProcessingException(); } AccountAction.java --------------------------- public class AccountAction extends Action { private static final String SUCCESS = "success"; private static final String FAILURE = "failure"; private static final String EXCEPTION = "abnormal"; AccountModel am = new AccountModel(); public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request, HttpServletResponse response) { String viewInfo = SUCCESS; AccountForm af = (AccountForm) form; int ano = af.getAccno(); try { Account acc = am.getAccountDetails(ano); request.setAttribute("account",acc); } catch(ProcessingException e) { viewInfo = EXCEPTION; } catch(AccountNotFoundException e) { viewInfo = FAILURE; } return mapping.findForward(viewInfo); }//execute } Q)What is a Resource Bundle in a Struts Application? =>Resource Bundle is properties file in a Struts Application whose standard name is "ApplicationResources.properties" =>In a Resource Bundle key,value pairs are specified according to Struts Application requirements. =>Struts reads the content of the Resource Bundle at runtime and uses it in populating the jsps with template text. =>Resource Bundles are used in the implementation of declarative exception handling, declarative validation and i18n in Struts application. Q)How to make use of a Resource Bundle in a Struts Application. Step 1:- Develop the properties file with some required key,value pairs Step 2:- Place the properties file in application's classpath i.e. "classes" folder with the standard name
  • 19. Struts Struts By L N Rao Page 19 "ApplicationResources.properties" Step 3:- Make the entry about the ResourceBundle in Struts configuration file. <message-resources parameter="ApplicationResources"> </message-resources> ------------------------------------------------------------------------------------------------------------------------------------------ Day:-15 05/10/12 ------------ Q)What are the limitations of the programmatical exception handling? 1.)No support for exception handling from framework. 2.)flow control code is polluted with exception handling code within the sub controller. Note:- Declarative exception handling addresses these limitations. Q)What is declarative exception handling in a Struts Application? =>Instructing the Struts Framework through configuration file to provide exception handlers from the sub controllers while they are invoking the business methods of the model components is nothing but declarative exceptiion handling. Q)How to implement declarative exception handling in a struts application? Step 1:- Develop a Resource Bundle with appropriate keys and corresponding messages(values). Step 2:- Make use of <exception> tags as sub tags of <action> tag to indicate to the framework the exception handlers required for that sub controller. Step 3:- Ensure that sub controller's method has java.lang.Exception in its exception specification. Step 4:- Make use of <html:errors /> tag in abnormal message displaying in jsps. Q)Modify the "prgexpaccountapplication" so as to have declarative exception handling instead of programmatical exception handling. declexpaccountapplication account.jsp accountdetails.jsp failure.jsp WEB-INF *.xml src *.java classes *.classes lib *.jar http://localhost:8081/declexpaccountapplication Note:-Model layer files are from the previous application.Form Bean,account.jsp,accountdetails.jsp & web.xml are also from the previous application. AccountAction.java -------------------------- .... .... public class AccountAction extends Action { AccountModel am = new AccountModel(); public ActionForward execute()throws Exception { AccountFrom af = (AccountForm) form; int ano = af.getAccno(); Account acc = am.getAccountDetails(ano); request.setAttribute("account",acc); return mapping.findForward("success"); }//execute()
  • 20. Struts Struts By L N Rao Page 20 } .... ApplicationResources.properties -------------------------------------------- db.search.failed=Account doesn't exist db.operation.failed=Processing Error.Please try later struts-config.xml ---------------------- <struts-config> <form-beans> <form-bean name="accountform" type="com.nareshit.form.AccountForm"/> </form-beans> <action-mappings> <action name="accountform" type="com.nareshit.controller.AccountAction" path="/account"> <exception key="db.search.failed" type="com.nareshit.exception.AccountNotFoundException" path="/failure.jsp"> </exception> <exception key="db.operation.failed" type="com.nareshit.exception.ProcessingException" path="/failure.jsp"/> <forward name="success" path="/accountdetails.jsp"/> </action> </action-mappings> <message-resources parameter="ApplicationResources"/> </struts-config> failure.jsp -------------- <%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %> <html> <body bgcolor="cyan"> <font color="red" size="5"> <html:errors /> </font> </body> </html> ------------------------------------------------------------------------------------------------------------------------------------------ Day:-16 06/10/12 ------------ Q)Explain about the attributes of the <exception> tag? key - this attribute is used to specify the resource bundle key. type - used to specify to framework about the required exception handler. path - if exception is raised, to which jsp control has to be switched is specified using this attribute. Q)What happens in the background when model component method propagated exception to the sub-controller in case of declarative exception handling? =>framework provided exception handler does the following things- 1.)creates org.apache.struts.action.ActionMessage object. In this object resource bundle key is encapsulated. 2.)ActionMessage object is kept into scope(session/request). 3.)informs to the ActionServlet about the jsp to which the control has to be switched. Q)Explain about the functionality of <html:errors /> tag? =>Tag Handler of <html:errors> tag does the following things. 1.)retrieving the ActionMessage object from the scope 2.)Retrieving resource bundle key that is wrapped in ActionMessage object 3.)retrieving corresponding message from the resource bundle 4.)writing the resource bundle message to the browser stream Q)What is dynamic form bean? =>A form bean developed by Struts for the Struts Application at run time is known as dynamic form bean. =>Our own developed form bean is known as a static form bean.
  • 21. Struts Struts By L N Rao Page 21 Q)How to make use of a dynamic form bean in a Struts Application? Step 1:- Configure DynaActionForm class in form beans section of struts configuration file. Step 2:- Specify the required fields using <form-property> tag. Step 3:- In Action class typecast ActionForm reference to DynaActionForm and invoke get() methods to capture the user input from the dynamic form bean instance. Q)Struts Application on dynamic form bean usage. dynafrombeanloginapplication *.jsp WEB-INF *.xml lib *.jar src LoginModel.java LoginAction.java http://localhost:8081/dynaformbeanloginapplication Note:- all files from the first struts application except action class and configuration file struts-config.xml ---------------------- <struts-config> <form-beans> <form-bean name="loginform" type="org.apache.struts.action.DynaActionForm"> <form-property name="username" type="java.lang.String"/> <form-property name="password" type="java.lang.String"/> </form-bean> </form-beans> <action-mappings> .... </action-mappings> </struts-config> LoginAction.java ---------------- ... import org.apache.struts.action.DynaActionForm; public class LoginAction extends Action { LoginModel lm = new LoginModel(); public ActionForward execute(.....) { ActionForward af = null; DynaActionForm daf = (DynaActionForm)form; String user = (String)daf.get("username"); String pwd = (String)daf.get("password"); boolean b = lm.isAuthenticated(user,pwd); if(b) af = mapping.findForward("ok"); else af = mapping.findForward("notok"); return af; } } -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------- Day:-17 08/10/12 ------------- struts-config.xml ----------------------- <struts-config> <form-beans> <form-bean name="accountform" type="org.apache.struts.action.DynaActionForm"> <form-property name="accno" type="java.lang.Integer"/> </form-bean>
  • 22. Struts Struts By L N Rao Page 22 </form-beans> ..... </struts-config> AccountAction.java ------------------------- import org.apache.struts.action.DynaActionForm; public class AccountAction extends Action { AccountModel am = new AccountModel(); public ActionForward execute() { DynaActionForm daf = (DynaActionForm)form; int accno = (Integer) daf.get("accno"); ........... } } Q)Why dynamic form bean? =>Struts developer's developed form beans are known as static form bean. =>Static form beans have the following limitations :- 1.)Developing form bean classes for all input pages of the application is a tedious task (and zero support from framework in development). 2.)functional dependency between input page developers and form bean developers. Q)What are global forwards? =>In struts configuration file we have two kinds of forwards :- 1.)action specific forwards 2.)forwards that are common to all actions =>Whenever same response for multiple use-cases is required to be given to the end-users, to reduce the amount of xml configuration in struts-config.xml we use <forward> tags that are available to all the actions of the application known as "global forwards". =>If <forward> tag is placed within the <action> tag it is known as action specific forward and it is not available to other actions. =>Global forwards are configured as follows :- <struts-config> <form-beans> <global-forwards> <forward name="success" path="/welcome.jsp"/> ....... </global-forwards> </form-beans> </struts-config> Q)What are the global exceptions in a Struts Application? =>During declarative exception handling if <exception> tag is placed within <action> tag, is known as action specific handler configuration. =>Limitation with this kind of configuration is that even if same exception handler is required for another action class, it is not available. We need to configure the same to another action. =>Exception handlers configured to make it available to all actions to reduce the amount of xml configuration is nothing but gloabl exception handler. For eg. - <global-exceptions> <exception key="" type="" path=""> </global-exceptions>
  • 23. Struts Struts By L N Rao Page 23 Q)Is form bean thread-safe? =>In Struts Application, Form Bean instance is not a singleton. Therefore, thread saftey issue doesn't arise. That too it is supplied as argument to execute() method of action class instance. =>Yes, it is thread-safe. Q)Is Action class thread-safe? =>No. We need to take care. =>Action class is a singleton in a Struts application. i.e. only one instance of action type is created by ActionServlet. Day:-18 09/10/12 ------------ Q)How model component can possibly be decomposed? Model Component Q)Explain about form bean life cycle. =>Form bean life cycle Q)What is the purpose of reset() method in form bean class? =>reset method need not be implemented in a static form bean if the scope is "request". =>reset() method is designed for form bean in Struts to overcome the strange behaviour of checkbox. =>In reset() method we make the boolean variable corresponding to a checkbox as false. Q)how to deal with the above scenario in dynamic form bean? <form-property name="isAgree" type="java.lang.Boolean" initial="false"/> ------------------------------------------------------------------------------------------------------------------------------------------ Day:-19 10/10/12 ------------ Q)How is business logic and data access logic are seperated in a Java Enterprise Application? =>using DAO design pattern =>A universal solution for a recurring problem in an application is nothing but a Design Pattern.
  • 24. Struts Struts By L N Rao Page 24 =>"Data Access Object" is a Design Pattern. According to this design pattern a seperate object performs data accessing activity and provides service to business component in abstraction. ~J2EE principle - clear seperation of concern ~concern - one task. For eg. getting user interaction PL = V + C input screen - V capturing user input | validating user input | communication with data processing component |-flow control exception handling | switching the control to appropriate view | producing the response page - V MVC is presentation layer design pattern data processing concern M = BC + DAO STRUTS-EJB Integeration ----------------------------------- =>Enabling Struts Action classes communicating with Enterprise Java Beans of EJB technology. =>"struts-ejb integration 1 10-oct-12.bmp" Q)Develop a Model Component using EJB technology for the Struts "loginapplication". ejbmodelcomponent LoginModel.java(interface) LoginModelImpl.java(session bean) LoginModel.java ----------------------- package com.nareshit.service; public interface LoginModel { public abstract boolean isAuthenticated(String user,String pwd); }//POJI (Plain Old Java Interface) //contract created LoginModelImpl.java ___________________ package com.nareshit.service; import javax.ejb.Remote; import javax.ejb.Stateless; @Remote @Stateless(mappedName="hello") public class LoginModelImpl implements LoginModel { public boolean isAuthenticated(String user,String pwd) { boolean flag = false; if(user.equals(pwd)) flag = true; return flag; } }//POJO (Plain Old Java Object) Note:- place weblogic.jar file into CLASSPATH before compiling the business interface and the implementation class. =>javac - d . *.java =>jar cvf loginmodel.jar com =>Once the above jar file is deployed into EJB container of weblogic application server, the container does the following things. 1.)creates a proxy for the bean class (LoginModelImpl) 2.)creates stub and skeletons for the proxy 3.)registers the proxy stub with naming service with the name "hello#com.nareshit.service.loginModel" Day:-20 11/10/12 --------
  • 25. Struts Struts By L N Rao Page 25 ..... -not attended ____________________________________________________________________________________________________________ ____ Day:-21 12/10/12 ------------ STRUTS-SPRING INTEGRATION ----------------------------------------- =>Enabling Struts Action classes communicate with Spring Beans is nothing but Struts-Spring Integration. Q)Develop model component for Struts "loginapplication" using Spring. springmodelcomponent LoginModel.java LoginModelImpl.java Note:- LoginModel.java is an interface which is from EJB integration example. LoginModelImpl.java is a Spring Bean class which is from EJB integration example but without annotations. beans.xml -------------- <beans> <bean id="lm" class="com.nareshit.service.LoginModelImpl"/> </beans> Q)Modify the first Struts application(loginapplication) so as to use Spring Bean as model component. springloginapplication *.jsp WEB-INF web.xml struts-config.xml classes LoginForm.class LoginAction.class LoginModel.class LoginModelImpl.class beans.xml lib 6 struts jar files spring.jar http://localhost:8081/springloginapplication LoginAction.java ----------------------- import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class LoginAction extends Action { LoginModel lm; public LoginAction() { XmlBeanFactory springContainer = new XmlBeanFactory(new ClassPathResource("beans.xml")); lm = (LoginModel)springContainer.getBean("lm"); }
  • 26. Struts Struts By L N Rao Page 26 ....... }//LoginAction Note:- place 3 jar files into classpath before compiling the above action class. 1) spring.jar 2) servlet-api.jar 3) struts-core-1.3.10.jar Q)How to integrate Spring with Struts? Step 1:- place Spring Bean class file and corresponding interface if any in classes folder. Step 2:- copy bean configuration file into "classes" folder. Step 3:- place spring.jar file in lib folder. Step 4:- In action class acquire the spring bean reference from the Spring Container. Q)What is the limitation of LoginAction development in Struts-EJB and Struts-Spring integration applications? =>Tight coupling with sub controller and model component. =>Action class is aware of the model component details. Note:- Business Delegate Design Pattern overcoms this limitation. -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------Day:-22 13/10/12 ----------- Q)Explain about Business Delegate Design Pattern. Context:- communication with business components. Problem:- Tight coupling between presentation layer component and business component. Solution:- Business Delegate =>Business Delegate is Business Logic Layer(Service Layer) design pattern. =>According to this solution(Design Pattern) a proxy class is created for the actual business component. =>This proxy class abstracts the presentation layer component, the business business component specific details while using its service. =>Business component developer develops proxy class which is known as Business Delegate class. =>In Business delegate class, every business method of the business component is dummily implemented. It receives the business service request from presentation layer and delegates to the actual business component and hence the name. Q)Develop a business delegate class for LoginModelImpl (Spring Bean) whose business method may throw LoginFailedException and ProcessingException. LoginDelegate.java --------------------- package com.nareshit.service; .... public class LoginDelegate { LoginModel lm; public LoginDelegate() { XmlBeanFactory springContainer = new XmlBeanFactory(new ClassPathResource("beans.xml")); lm = (LoginModel)springContainer.getBean("lm"); } public void isAuthenticated(String user,String pwd)throws ProcessingException,LoginFailedException { lm.isAuthenticated(user,pwd);//delegation to the business component }//dummy implementation of the original method } Q)Develop LoginAction that uses the delegate in Struts-Spring integration application. public class LoginAction extends Action { LoginDelegate lm = new LoginDelegate();
  • 27. Struts Struts By L N Rao Page 27 execute(....)throws Exception { ..... lm.isAuthenticated(user,pwd); ..... } } Note:- Declarative exception handling is assumed. -interface can also be used for business delegate class. Q)Develop the Business Delegate for the EJB class. package com.nareshit.service; import javax.naming.InitialContext; ...... public class LoginDelegate { LoginModel lm; public LoginDelegate { try { InitialContext ic = new InitialContext(); lm = (LoginModel)ic.lookup("hello#com.nareshit.service.LoginModel"); } catch(Exception e) { System.out.println(e); } }//constructor public void isAuthenticated(String user,String pwd)throws ProcessingException,LoginFailedException { lm.isAuthenticated(user,pwd);//delegation to the business component }//dummy implementation of the original method } Q)Develop LoginAction that uses the above delegate class fro EJB communication. =>Same as above.(that's why loose coupling) Q)What are the duties of a controller in a web enabled Java Web Application that follows MVC design pattern? 1.)capturing the use input 2.)validating the user input 3.)communicating with model component 4.)handling the exception 5.)indentifying the view 6.)switching the control to the view Note:- MVC design pattern doesn't seperate the reusable and common flow control tasks and non-reusable varying flow control tasks. MVC problem:- -multiple entry points into the website(application). -duplication of same flow control code for each use case(for multiple controller) solution - Front Contoller Design Pattern Note:- ActionServlet implementation is nothing but according to Front Controller Design Pattern only. ActionServlet is built-in front controller. ____________________________________________________________________________________________________________ ________ Day:-23 15/10/12 ----------- Validations in Struts Application ------------------------------------------
  • 28. Struts Struts By L N Rao Page 28 Q)Explain about validation in a Java Web Application? =>Ensuring complete input and proper input into the web application through web froms is nothing but performing validation in a web application(website). =>We have two kinds of validations. 1.)client side validation 2.)server side validation Q)What is Server Side Validation and Why is it required when client side validation is already applied? =>Verifying the user input at web serverside for its completeness and correctness is known as server side validation. =>Server side validation is performed for two reasons. 1.)for security reasons 2.)assuming that clientside validation code is by-passed due to disabling of JavaScript or compatibility of javascript code. Q)What is server side validation in a Struts Application? =>Verifying user input that is stored in form bean instance for its completeness and correctness is nothing but server side validation in a Struts Application. Q)How is validation classified in a Struts Application? 1.)Programmatical validation 2.)Declarative validation Note:- Almost all the times declarative validation mechanism only used. Q)What is programmatical validation ia Struts Application? =>If user input verification code Struts Developer implements in static form bean class, it is known as programmatical validation. Q)How to implement programmatical validation in a Struts Application? Step 1:- Develop a resource bundle with appropriate entries. Step 2:- Override validate() method in static form bean instance and implement validation logic. Step 3:- Enable validation and specify the input page (to Struts to execute in case of validation failure). Step 4:- In the specified input page make use of <html:errors> tag. Q)Develop a Struts application in which, programmatical validation is implemented. prgvalidationloginapplication login.jsp welcome.jsp loginfailed.jsp WEB-INF *.xml classes *.class lib *.jar src *.java _____________________________________________________________________________________ Day:-24 16/10/12 ------------ ApplicationResources.properties ------------------------------- user.required=Username field can't be empty pwd.required=Password field can't be empty LoginForm.java -------------- import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMapping;
  • 29. Struts Struts By L N Rao Page 29 import javax.servlet.http.HttpServletRequest; public class LoginForm extends ActionForm { private String username; private String password; public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } public ActionErrors validate(ActionMapping mapping,HttpServletRequest request) { ActionErrors ae = new ActionErrors(); //validation logic if(username.length()==0) //here NullPointerException will not be raised.why? { ae.add("username",new ActionMessage("user.required")); } if(password.length()==0) { ae.add("password",new ActionMessage("password.required")); } return ae; }//validate }//form bean(action form) struts-config.xml ----------------- <struts-config> <form-beans> <form-bean name="loginform" type="com.nareshit.form.LoginForm"/> </form-beans> <action-mappings> <action path="/login" name="loginform" type="com.nareshit.controller.LoginAction" validate="true" input="/login.jsp"> <forward name="ok" path="/welcome.jsp"/> <forward name="notok" path="/loginfailed.jsp"/> </action> </action-mappings> <message-resources parameter="ApplicationResources"/> </struts-config> login.jsp --------- <%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %> <html> <body bgcolor="cyan"> <center> <h1>Login to www.nareshit.com</h1> <html:form action="/login" method="POST"> UserName <html:text property="username"/>
  • 30. Struts Struts By L N Rao Page 30 <font color="red" size="5"> <html:errors property="username"/> </font> <br><br> Password <html:password property="password"/> <font color="red" size="5"> <html:errors property="password"/> </font> <br><br> <html:submit>login</html:submit> </html:form> </center> </body> </html> Q)How does ActionServlet know wether validation is failed or succeeded? =>If ActionErrors object is empty or its reference is null, ActionServlet understands that validation is successfull. =>If ActionErrors object has at least one ActionMessage object it understands that validation is a failure and it stores ActionErrors object into the scope and switches the contorl to the specified input page. Q)Explain about ActionErrors? =>Struts API class. =>Struts collection class. =>For each validation failure we need to store an ActionMessage object into this collection. =>Its add method takes a String as the first argument indicating which field failed in validation. ____________________________________________________________________________________________________________ ________ Day:-25 17/10/12 ------------ Q)What are the limitations of programmatical validation in Struts Application? 1.)Validation logic, developer should write and zero support from framework. 2.)Validation logic written for on field is not resuable for same field of another form bean. 3.)Can't validate the user input in case of Dynamic form bean. 4)Can't use Javascript generation facility provided by the Struts Framework i.e. client side validation logic also developers are responsible to develop. Q)What is declarative validation in a Struts application? =>Instead of Struts developer developing the server side validation logic for the user input, taking Struts framework provided validation support by explaining the validation requirements through xml tags declaratively is nothing but declarative validation in Struts Application. =>Declrative validation overcomes all the limitations of programmatical validation. =>Using validation sub framework in a Struts application for validations is nothing but implementing declarative validation in a Struts Application. Q)How to implement(make use of) declarative validation in a Struts Application for static form beans? Step 1:- Develop the resource bundle with appropriate entries. Step 2:- Develop the form bean class that extends org.apache.struts.validator.ValidatorForm. =>Should not override validate method in form bean class. Step 3:- Enable validation and specify the input page in Struts Configuration file. Step 4:- Make use of <html:errors> tag in the specified input page to display the validation failure messages to the end user. Step 5:- Develop validation.xml and place it in the WEB-INF directory. Step 6:- Place validator-rules.xml(built-in file as a part of framework) into WEB-INF. Step 7:- Configure ValidatorPlugIn in Struts configuration file. Step 8:- Place commons-validator-1.3.1.jar file into the application's lib folder. Q)Develop a Struts Application in which declarative validation is used for static form bean. declvalidationloginapplication login.jsp
  • 31. Struts Struts By L N Rao Page 31 loginfailed.jsp welcome.jsp WEB-INF web.xml struts-config.xml validation.xml validator-rules.xml lib 7 jar files classes *.class(3 class files) ApplicationResources.properties http://localhost:8081/declvalidationloginapplication ____________________________________________________________________________________________________________ ________ Day:-26 18/10/12 ------------ ApplicationResources.properties ------------------------------- errors.required={0} should not be empty errors.minlength={0} should have atleast {1} characters our.usr=User Name our.pwd=Password our.eight=8 Note:- first two keys are predefined and taken from validator-rules.xml. We have taken only two keys because we are using validator framework provided two validations only - 1)required validation 2)minlength validation. Other three keys and corresponding values are user defined. They have been taken for parametric replacement. =>Supplying values to place holders of the Resource Bundle messages is known as parametric replacement. =>We can have any number of place holders in a message of the Resource Bundle. For eg. {0} {1} {2} etc. =>parametric replacement provides flexibility in displaying the errors messages to the user. LoginForm.java -------------- package com.nareshit.form; import org.apache.struts.validator.ValidatorForm; public class LoginForm extends ValidatorForm { private String username; private String password; public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public void setPassword(String password) { this.password = password; }
  • 32. Struts Struts By L N Rao Page 32 public String getPassword() { return password; } //never write(override) validate method here -- BLUNDER!!! }//form bean (action form) struts-config.xml ----------------- <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"> <struts-config> <form-beans> <form-bean name="loginform" type="com.nareshit.form.LoginForm"/> </form-beans> <action-mappings> <action path="/login" name="loginform" type="com.nareshit.controller.LoginAction" validate="true" input="/login.jsp"> <forward name="ok" path="/welcome.jsp"/> <forward name="notok" path="/loginfailed.jsp"/> </action> </action-mappings> <message-resources parameter="ApplicationResources"/> <plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/> </plug-in> </struts-config> Q)What is the significance of validate-rules.xml? =>To make validator framework provided built-in validators available to the Strust application. Q)What is the significance of validation.xml? =>Strust developer expresses to the framework, application's validation requirements through this file. login.jsp --------- -from the previous application ____________________________________________________________________________________________________________ ________ Day:-27 19/10/12 -------- validation.xml -------------- <form-validation> <formset> <form name="loginform" > <field property="username" depends="required"> <arg position="0" key="our.usr"/> </field> <field property="password" depends="required,minlength"> <arg position="0" key="our.pwd"/> <arg position="1" key="8" resource="false"/> <var> <var-name>minlength</var-name> <var-value>8</var-value> </var> </field> </form> </formset> </form-validation>
  • 33. Struts Struts By L N Rao Page 33 Q)Explain about the tags of validation.xml? =>name attribute's value of <form> tag should match with the logical name of the form bean specified in Struts configuration file. For which form bean fields built-in validators required is specified using <form> tag. =>We can have as many <form> tags as there are form beans in the application. =>depends attribute of <field> tag takes the logical name the built in validator. We can also specify multiple values with comma seperator. For which field those validators are to be applied is specified using property attribute. =><arg> tags are for parametric replacement. =><var> tag is used to supply the argument to a built in validator. Q)How to apply declarative validation for dynamic form bean? Step 1:- Configure the following in struts-config.xml <form-bean name="loginform" type="org.apache.struts.validator.DynaValidatorForm"> <form-property name="username" type="java.lang.String"/> <form-property name="password" type="java.lang.String"/> </form-bean> Step 2:- In action class typecast ActionForm reference to DynaValidatorForm before before capturing the user input. For eg. DynaValidatorForm daf = (DynaValidatorForm)form; String user = (String)daf.get("username"); String pwd = (String)daf.get("password"); Note:- Other 7 steps are from declarative validations applying to static form beans approach only. ____________________________________________________________________________________________________________ ________ Day:-28 20/10/12 ------------- Q)How to make use of validator framework provided client side validation support? Step 1:- Make use of <html:javascript> tag in the input page of the struts application. Step 2:- Invoke a special JAvaScript function through event handling in the input page. Q)How does Struts provided client side validation code function? =>When the input jsp is executed, "javascript" tag of html library is executed. For this tag logical name of the form bean should be supplied as value (to "formName" attribute). =>Validator framework provided JavaScript functions code is appended in line by the tag handler of "javascript" tag. =>A specified JavaScript function also is generated and appended. That function name validateXXX(). "XXX" stands for the logical name of the form bean. This method only calls the validation performing JavaScript functions. =>When user clicks on the submit button, "onsubmit" event is raised and the special function is called. Internally that function calls the JavaScript functions and client side validation is performed. Q)Provide client side validation support also to "declvalidationloginapplication". =>All the files are from this application only. "login.jsp" has to be modified in order to enable client side validation support. login.jsp --------- <%@ taglib prefix="html" uri="http://struts.apache.org/tags-html"%> <HTML> <HEAD> <html:javascript formName="loginform"/> </HEAD> <BOdY BGCOLOR="yellow"> <CENTER> <H1>Login Screen</H1> <FONT SIZE="3" COLOR="red"> <html:errors/> </FONT> <html:form action="/login" method="POST" onsubmit="return validateloginform(this);">
  • 34. Struts Struts By L N Rao Page 34 Username <html:text property="username"/> <BR> Password <html:password property="password" /> <BR> <html:submit>Login</html:submit> </html:form> </CENTER> </BODY> <HTML> --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Day:-29 22/10/12 ------------- Q)Modify the loginapplication so as to give same input page to the user if authentication is failed. ApplicationResources.properties ------------------------------- login.error=user name or password is wrong struts-config.xml ----------------- <action name="loginform" path="/login" type="com.nareshit.controller.LoginAction" input="/login.jsp"> <forward name="ok" path="/login.jsp"/> </action> login.jsp --------- ..... <BODY> <CENTER> <FONT SIZE="5" COLOR="red"> <html:errors property="hello"/> </FONT> <H1>Welcome to Nareshit</H1> <html:form action="/login" method="POST"> .... </CENTER> </BODY> LoginAction.java ---------------- public class LoginAction extends Action { LoginModel lm = new LoginModel(); public ActionForward execute(....) { ..... boolean = b = lm.isAuthenticated(user,pwd); if(b) { mapping.findForward("ok"); } else { ActionMessages am = new ActionMessages(); am.add("hello",new ActionMessage("login.error")); addErrors(request,am); //programmatical validation like error adding code return mapping.getInputForward(); } } }
  • 35. Struts Struts By L N Rao Page 35 Day:-30 25/10/12 ------------ Q)Develop a Struts Application that implements a virtual shopping cart. virtualshoppingcartapplication checkout.jsp noitems.jsp shoppage.jsp visitagain.jsp WEB-INF web.xml struts-config.xml lib *.jar(6 jar files) struts-extras-1.3.10.jar src Product.java ShoppingAction.java ShoppingForm.java ShoppingService.java classes *.classes http://localhost:8081/virtualshoppingcartapplication web.xml ------- =>Make shopping.jsp as home page. ShoppingService.java -------------------- package com.nareshit.service; import java.util.Map; import java.util.Collection; public class ShoppingService { public void addItem(Map m,Product p) { m.put(p.getPCode(),p); } public void removeItem(Map m,String pcode) { m.remove(pcode); } public Collection<Product> getAllItems(Map m) { Collection<Product> items = m.values(); return items; } } =>"shoppingcartappflow.bmp" 1:- ASreceiving client request upon web from submission and capturing atleast one request parameter (name & value). 2:- AS creating ShoppingForm instance and populating atleast one of its properties(pcode,quantity & submit). 3:- AS creating ShoppingAction instance and invoking its execute method. 4a:- execute() method calling addItem() or removeItem() business method of ShoppingService(model component). 4b:- execute method calling getAllItems() business method of model component. 5a:- either addItem() Or removeItem() of business component getting executed. 5b:- getAllItems() getting executed. 6a:- addItem() OR removeItem() returning nothing to execute() method. 6b2:- getAllItems() returning a collection of products to execute() method. 7a:- execute() method returning "shoppingpage" view mapping information to AS. 7b2:- execute() method returning "itemdetails" view mapping information to AS.
  • 36. Struts Struts By L N Rao Page 36 7b1:- execute() method returning "noitems" view mapping information to AS. 7:- execute() method returning "farewel" view mapping information to AS. struts-config.xml ----------------- <struts-config> <form-beans> <form-bean name="shoppingform" type="com.nareshit.view.ShoppingForm"/> </form-beans> <action-mappings> <action path="/shopping" name="shoppingform" type="com.nareshit.controller.ShoppingAction"> <forward name="shoppingpage" path="/shoppage.jsp" redirect="true"/> <forward name="noitems" path="/noitems.jsp"/> <forward name="itemdetails" path="/checkout.jsp"/> <forward name="farewel" path="/visitagain.jsp"/> </action> <action path="/shoppingpage" parameter="/shoppage.jsp" type="org.apache.struts.actions.ForwardAction"> </action> <!-- to create hyperlink --> </action-mappings> <message-resources parameter="ApplicationResources"/> </struts-config> __________________________________________________________________________________________________________ Day:-31 26/10/12 ------------ ShoppingForm.java ----------------- package com.nareshit.view; import org.apache.struts.action.ActionForm; pbulic class ShoppingForm extends ActionForm { private String pcode; private int quantity; private String submit; //to hold submit button caption //getters & setters } Product.java ------------- package com.nareshit.service; public class Product implements java.io.Serializable { private String pcode; private int quantity; //setters & getters }//domain object(data transfer object) ShoppingAction.java ------------------- package com.nareshit.controller; import org.apache.struts.action.*; import javax.servlet.http.*; import java.util.*; import com.nareshit.service.Product; import com.nareshit.service.ShoppingService;
  • 37. Struts Struts By L N Rao Page 37 import com.nareshit.view.ShoppingForm; public class ShoppingAction extends Action { ShoppingService ss = new ShoppingService(); public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request, HttpServletResponse response) { String responsePage = "shoppingpage"; ShoppingForm sf = (ShoppingForm) form; String sb = sf.getSubmit(); HttpSession session = request.getSession(); //local variable is thread safe //indivisual session for each user Map cart = (Map) session.getAttribute("cart"); //local variable is thread safe //unique cart for each user if(cart==null) { cart = new HashMap(); session.setAttribute("cart",cart); } if(sb.equals("ADDITEM")) { Product p = new Product(); p.setPcode(sf.getPcode()); p.setQuantity(sf.getQuantity()); ss.addItem(cart,p); //business method call } else if(sb.equals("REMOVEITEM")) { ss.removeItem(cart,sf.getPcode()); } else if(sb.equals("SHOWITEMS")) { Collection<Product> products = ss.getAllItems(cart); //business method call if(products.size() == 0) { responsePage = "noitems"; }//inner if else { request.setAttribute("products",products); responsePage = "itemdetails"; } }//if else { session.invalidate(); responsePage = "farewel"; } } return mapping.findForward(responsePage); }//execute() Q)How to create a hyperlink in the jsps of a struts application? Step 1:- configure a built-in action class in struts configuration file. For eg. <action path="/shoppingpage" parameter="/shoppage.jsp" type="org.apache.struts.actions.ForwardAction"/> Step 2:- Create the link using <html:link> tag. For eg. <html:link action="shoppingpage">Thank You. Visit Again to shop again </html:link> Step 3:- Place additionally "struts-extras-1.3.10.jar" file into lib folder.
  • 38. Struts Struts By L N Rao Page 38 noitems.jsp ----------- <%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %> <html> <body bgcolor="cyan"> <h1>No items in your shopping cart</h1> <html:link action="shoppingpage">Home</html:link> </body> </html> visitagain.jsp -------------- <%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %> <html> <body bgcolor="cyan"> <html:link action="shoppingpage">Thank You. Visit again to shop more</html:link> </body> </html> ____________________________________________________________________________________________________________ ________ Day:-32 27/10/12 ------------ shoppage.jsp ------------ <%@ taglib prefix="html" uri="http://struts.apache.org/tags-html"%> <HTML> <BODY BGCOLOR="wheat"> <CENTER> <H2>Welcome to shopping Mall</H2> <html:form action="shopping"> Select Product Type <html:select property="pcode"> <html:option value="p101">p101</html:option> <html:option value="p102">p102</html:option> <html:option value="p103">p103</html:option> <html:option value="p104">p104</html:option> <html:option value="p105">p105</html:option> </html:select> <BR><BR> Product Quantity <html:text property="quantity" value=""/> <BR><BR> <html:submit property="submit" value="ADDITEM"/> <html:submit property="submit" value="REMOVEITEM"/> <html:submit property="submit" value="SHOWITEMS"/> <html:submit property="submit" value="LOGOUT"/> </html:form> </CENTER> <BODY> </HTML> checkout.jsp ------------ <%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %> <%@ taglib prefix="bean" uri="http://struts.apache.org/tags-bean" %> <%@ taglib prefix="logic" uri="http://struts.apache.org/tags-logic" %> <HTML>
  • 39. Struts Struts By L N Rao Page 39 <BODY BGCOLOR="yellow"> <H1>Your shopping cart item</H1> <H2> <logic:iterate scope="request" name="products" id="product"> Product Code: <bean:write name="product" property="pcode"/> Quantity: <bean:write name="product" property="quantity"/> <BR><BR> </logic:iterate> </H2> <html:link action="shoppingpage">HOME</html:link> </BODY> </HTML> Q)Develop a struts application in which user registration use-case is implemented in multiple request response cycles. registerapplication register1.jsp register2.jsp failure.jsp success.jsp WEB-INF *.xml lib *.jar(6 jar files) src Register1Action.java Register2Action.java RegisterForm.java RegisterService.java Registration.java classes *.class http://localhost:8081/registerapplication Register1Action.java -------------------- public class Register1Action extends Action { public ActionForward execute(....) { return mapping.findForward("success"); } } Register2Action.java -------------------- import org.apache.commons.beanutils.BeanUtils; public class Register2Action extends Action { private static final String SUCCESS = "success"; private static final String FAILURE = "failure"; RegisterService registerService = new RegisterService(); public ActionForward execute(....) { RegisterForm registerForm = (RegisterForm)form; String responseKey = FAILURE; Registration registration = new Registration(); //domain object BeanUtils.copyProperties(registration,registerForm); boolean flag = registerService.doRegistration(registration); if(flag) responseKey = SUCCESS; return mapping.findForward(responseKey);
  • 40. Struts Struts By L N Rao Page 40 } } register2.jsp ------------- <%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %> <html> <body bgcolor="pink"> <center> <h1> Please fill the following things to complete the registration </h1> <html:form action="register2" method="post"> <html:hidden property="name" write="registerForm.name"/> <html:hidden property="password" write="registerForm.password"/> <html:hidden property="profession" write="registerForm.profession"/> Cell : <html:text property="cell"/> <br><br> Gender : <html:radio property="gender" value="male">male</html:radio> <html:radio property="gender" value="female">female</html:radio> <br><br> <html:checkbox property="agree"/>I agree the terms and conditions of the registration <br><br> <html:submit>Complete Registration</html:submit> </html:form> </center> </body> </html> ____________________________________________________________________________________________________________ ________ Day:-33 29/10/12 -------- success.jsp ----------- <html> <body bgcolor="yellow"> <h1>You have been successfully registered</h1> </body> </html> register1.jsp ------------- <%@ taglib prefix="html" uri="http://struts.apache.org/tags-html"%> <html> <body bgcolor="cyan"> <center> <h1>Welcome to register page</h1> <html:form action="register1" method="post"> Name : <html:text property="name"/> <br> Password : <html:password property="password"/> <br> Profession : <html:select property="profession"> <html:option value="Engineer">Engineer</html:option> <html:option value="Businessman">Businessman</html:option> <html:option value="Others">Others</html:option> </html:select> <br> <html:submit>Register</html:submit>
  • 41. Struts Struts By L N Rao Page 41 </html:form> </center> </body> </html> failure.jsp ----------- <html> <body bgcolor="pink"> <h1> Unable to register you. Please try after some time. </h1> </body> </html> web.xml ------- =>Make register1.jsp the home page. struts-config.xml ----------------- <struts-config> <form-beans> <form-bean name="registerForm" type="com.nareshit.view.RegisterForm"/> </form-beans> <action-mappings> <action path="/register1" name="registerForm" type="com.nareshit.controller.Register1Action"> <forward name="success" path="/register2.jsp"/> </action> <action path="/register2" name="registerForm" type="com.nareshit.controller.Register2Action"> <forward name="success" path="/success.jsp"/> <forward name="failure" path="/failure.jsp"/> </action> </action-mappings> </struts-config> RegisterForm.java ----------------- package com.nareshit.view; import org.apache.struts.action.ActionForm; public class RegisterForm extends ActionForm { private String cell; private String profession; private String name; private String gender; private String password; private boolean agree; //boolean isAgree() & boolean getAgree() are same //setters & getters } Registration.java ----------------- =>It is a POJO and is similar to RegisterForm.java RegisterService.java -------------------- package com.nareshit.struts; public class RegisterService { public boolean doRegistration(Registration registration)
  • 42. Struts Struts By L N Rao Page 42 { boolean flag = false; //using any data access mechanism persist registration object(state). flag = registration.isAgree(); return flag; } } ______________________________________________ Tiles Q)What are the drawbacks of jsp include mechanism? =>JSP incluse mechanism is used to develop composite views in a Java Web Application. =>JSP include mechanism promotes reusability of output generation code across pages of the website. =>JSP include mechanism has the following limitations 1.)Page design is not reusable in developing different composite views of the website. 2.)As included page name is hardcoded in the including pages, it is error prone if included page name is changed at later stage. Q)How to overcome JSP include mechanism limitations in the jsps of a struts application? =>Using Tiles concept of Struts. Q)What is Tiles in the context of Struts? =>Tiles is a sub framework of Struts. =>Tiles is plugged into a Struts application to develop composite views. =>Tiles overcomes all the limitations of JSP include mechanism. =>Tiles ensures consistent look & feel of the web pages of the website. _________________________________________________________________________________________________________ Day:-34 30/10/12 ----------- Q)How to make use of Tiles in a Struts application? Step 1:- Develop layout page(s). Step 2:- Develop content pages, Step 3:- Develop tiles-defs.xml. Step 4:- Enable tiles by plugging into the Struts Application. Step 5:- place struts-tiles-1.3.10.jar file additionally into the lib folder. Step 6:- specify the chain-config.xml as init parameter to ActionServlet in web.xml. Step 7:- use the tiles definition. Q)Develop a Struts Application in which, Tiles is used to create the composite views. =>Refer to handout. Q)What is the significance of tiles-defs.xml? =>For each composite view of the application, one definition is mentioned in this xml file. A logical name is given to each definition. =>In each definition, layout page is specified and the actual jsps that are to be assembled into one composite view are also specified. =>When a tiles definition is used, Tiles subframework performs the assembling of all the simple views(each tile) into a composite view around the layout page. Q)What is the significance of chain-config.xml? =>Earlier to Struts1.3, Tiles sub framework was using Request Processor while assembling the views. In Struts 1.3.x, this xml file is assisting Tiles in creating the composite views. ____________________________________________________________________________________________________________ ________ Day:-35 31/10/12 -------- Q)How to make use of a tiles definition? 1.)<tiles:insert definition="logical name"/> 2.)<forward name="logical name of the path to the view" path="logical name of the tiles definition"/>
  • 43. Struts Struts By L N Rao Page 43 3.)<action path="/actionpath" forward="logical name of the tiles definition"/> =>Generally, if home page is the composite view, first one is used. =>When user submitted the form, the response page has to be composite view means the second one is used. =>When user clicked on the hyper link the target page has to have composite view means go for the third style of using the tiles definition. ____________________________________________ Internationalization(i18n) -------------------------- Q)What is i18n? =>Providing multilingual support to the website without changing application's source code is nothing but i18n(internationalization). =>Once the Struts application is i18n enabled, based on user preferred language, web pages can be displayed. Q)How to implement i18n in a Struts Application? Step 1:- Develop as many resource bundles as the number of languages that you want to support. Resource Bundle keys are common. Only values will be in corresponding languages. Step 2:- In JSPs don't write language specific template text. Instead, make use of bean library's message tag that can retrieve language content from the appropriate resource bundle based on user preferred language. For eg. <bean:message key="resource bundle key"/> ____________________________________________________________________________________________________ Day:-36 01/11/12 ------------ Q)How does i18n ..... //to do =>Browser sends user preferred language to the web server using Accept-langugage HTTP header. =>Web server passes on that information to the servlet engine. =>Encapsulation of (Object oriented representation of) user preferred language is nothing but java.util.Locale object. =>Container creates Locale object encapsulating user preferred language and stores it (its reference ) into HttpServletRequest object. =>HttpServletRequest has getlocale method that returns Local object. Local local = request.getLocale(); =>Struts Framework gets Locale object and stores it into the session scope. =>message tag of bean library selects the appropriate resource bundle based on Locale object stored in session scope. Q)What is the limitation in the above i18n application? =>User has to change the browser's settings explicitely. =>On the home page, language options should have been given for the user to select the preferred language. Q)How to make use of LocaleAction in a i18n Struts Application? Step 1:- configure LocaleAction in struts-config.xml. Step 2:- configure a special form bean to hold user specified locale details. i.e. language,country,varient&page Specify the logical name of this bean for LocaleAction configuration. Step 3:- create links on home page that target LocaleAction class. specify the language and page request parameters as part of query string. Step 4:- copy struts-extras-1.3.10.jar in lib folder Q)Develop an i18n enabled struts application that provides mutlti lingual support for the end-users without the need of changing the browser settings.
  • 44. Struts Struts By L N Rao Page 44 =>Refer to the handout.(localeapplication page 11) ____________________________________________________________________________________________________________ ________ Day:-37 02/11/12 ----------- Q)Explain about DispatchAction. =>org.apache.struts.actions.DispatchAction is one of the built-in action classes provided by Struts Framework. =>Within a single action class to unify related multiple use-cases, this action class is used. Note:- Normally, action classes are use-case specific. This built-in action class enables us to develop domain object specific action classes rather than use-case specific action classes. Q)How to make use of DispatchAction in a Struts application? Step 1:- Develop a user defined action class that extends DispatchAction. Step 2:- implements one user defined method per use-case within the action class. User defined methods should have the prototype of execute() method. For eg. public ActionForward insertEmp(ActionMapping mapping,ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception Step 3:- Configure the user defined action class in struts configuration file. Make use of "parameter" attribute in <action> tag. Give any user defined name as value for that attribute. For eg. <action path="/both" .... parameter="admin"/> Step 4:- develop use-case specific input pages as usual with the following additional things. a.)all input screens should point to the same action class(path). b.)request parameter name of each input page should be that of the name given as the value to the "parameter" attribute of <action> tag. For eg. <html:submit property="admin">insert</html:submit> <html:submit property="admin">delete</html:submit> c.)request parameter value of the input screen i.e. caption of the submit button should be the user defined method name given in action class. Step 5:- struts-extras-1.3.10.jar place into classpath additionally and place into lib folder. Q)Struts application in which two built-in action, ForwardAction & DispatchAction, functionality is used. =>refer to the handout - forwarddispatchapplication page 3 Q)How does DispatchAction function? =>When ActionServlet creates the user defined action class instance, it inherits execute method of DispatchAction class. =>ActionServlet calls the execute method. =>Based on the submit button caption, execute method knows to call the corresponding user defined method. ____________________________________________________________________________________________________________ ________ Day:-38 03/11/12 -------- Q)What are the limitations of DispatchAction? 1.)can't support i18n 2.)can't use different form beans for different use-cases. Q)Explain about LookupDispatchAction. =>org.apache.struts.actions.LookupDispatchAction is a sub class of DispatchAction. =>Its purpose is same as that of DispatchAction only, with additional i18n support. Q)How to make use of LookupDispatchAction in a Struts Application? Step 1:- Develop resource bundle with appropriate key,value pairs. Step 2:- develop a Java class that extends LookupDispatchAction. Step 3:- implement as many user defined methods as there are use-cases to unify. Method prototype should be that of execute method except name. Note:- should not override execute() method like in DispatchAction.