Your SlideShare is downloading. ×
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
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
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
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
Struts by l n rao
Struts by l n rao
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Struts by l n rao

2,449

Published on

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,449
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
137
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 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.
  • 45. Struts Struts By L N Rao Page 45 Step 4:- implement getKeyMethodMap() in the user defined action class. In this method create HashMap object, store resource bundle key as the key and user defined method name as the value into it and return that object. Number of entries in the HashMap are equal to the number of user defined methods implemented in the action class. Step 5:- configure the action class in struts-config.xml with "parameter" as additional attribute in <action> tag. Give any user defined name as the value to that attribute. Step 6:- observe the following in the input page development a.)all input screens should point to the same action class(path). b.)request parameter name of the each input page should be that of the name given as value to the "parameter" attribute of the <action> tag. c.)give caption to the submit button using <bean:message> Q)How does LookupDispatchAction work? =>Its execute method performs the following things. 1.)captures the submit button caption. 2.)perform the reverse lookup in the appropriate resourse bundle to get the key corresponding to submit button caption. 3.)calls getKeyMethodMap() method and seraches for the user defined Java method in Map object by using resource bundle key as search criteria. 4.)invokes the user defined method of user defined action class. Q)Struts application in which, LookupDispatchAction is used. =>Refer to the handout for source code(lookupdispatchapplication - page 17). --to be added to the lookdispatchapplication in handout(page 17) ApplicationResources.properties(_en is default) ------------------------------- ApplicationResources_en.properties ---------------------------------- insert=CreateEmployee delete=FireEmployee __________________________________________________________________________________________________________ Day:-39 05/11/12 ------------ Q)Struts application on MappingDispatchAction. =>RTH (mappingdispatchapplication page no 20) =>org.apache.struts.actions.MappingDispatchAction is one of the built-in action classes provided by Struts and is the sub class of DispatchAction whose purpose is same as that of its super class. =>Following steps are involved in using this action class. Step 1:- Develop a user defined action class that extends MappingDispatchAction. Step 2:- Don't override execute() method. Instead, for each use-case one user defined method should be implemented which is similar to that of DispatchAction. Step 3:- Configure the action class as many times in struts-config.xml as there are unified use cases. Make use of "parameter" attribute of <action> tag and give the user defined method name as its value. Step 4:- Input page request parameter value i.e. submit button caption should be user defined method name. Note:- We can use different form beans if required for each use-case. Directly submit button caption is mapped to the user defined method of action class and hence the name. This action doesn't support i18n. __________________________________ Q)Explain about ValidatorActionForm. =>static form bean, declarative validation, multiple input pages usnig same form bean, don't want form bean based declarative validation, requires action based validation, go for org.apache.struts.validator.ValidatorActionForm.
  • 46. Struts Struts By L N Rao Page 46 Q)Explain about DynaValidatorActionForm. =>dynamic form bean, declarative validation, multiple input pages usnig same form bean, don't want form bean based declarative validation, requires action based validation, go for org.apache.struts.validator.DynaValidatorActionForm. Q)Example on ValidatorActionForm. -register.jsp with username,password and emailid fileds. -login.jsp with username and password fields. UserForm.java ------------- public class UserForm extends ValidatorActionForm { private String username; private String password; private String emailid; //setters and getters } validation.xml -------------- <form-validation> <formset> <form name="/register"> <field property="username" depends="required"> <arg position="0" key="our.usr"/> </field> <field property="password" depends="required"> <arg position="0" key="our.pwd"/> </field> <field property="emaild" depends="required"> <arg position="0" key="our.mail"/> </field> </form> <form name="/login"> <field property="username" depends="required"> <arg position="0" key="our.usr"/> </field> <field property="password" depends="required"> <arg position="0" key="our.pwd"/> </field> </form> </formset> </form-validation> --same validator.xml for DynaValidatorActionForm also. Note:- We need to place additionally struts-extras-1.3.10.jar into the CLASSPATH before compiling the form bean and place it in lib folder as well. Q)Example on DynaValidatorActionForm. <struts-config> <form-beans> <form-bean name="userform" type="org.apache.struts.validator.DynaValidatorActionForm"> <form-property name="username" type="java.lang.String"/> <form-property name="password" type="java.lang.String"/> <form-property name="emailid" type="java.lang.String"/> </form-bean> </form-beans> <action-mappings> <action path="/login" name="userform" ....> .... </action> <action path="/register" name="userform" ....>
  • 47. Struts Struts By L N Rao Page 47 ..... </action> </action-mappings> </struts-config> validation.xml -------------- =>from previous application LoginAction.java & RegisterAction.java -------------------------------------- =>Typecast ActionForm reference to DynaValidatorActionForm while retrieving user input. _____________________________________________________________________________________ Day:-40 07/11/12 ------------ Q)Explain about EventDispatchAction. =>One of the built-in action classes. =>org.apache.actions.EventDispatchAction is used to unify the multiple use-cases in a single action class. =>It supports i18n and different form beans usage for different use-cases. =>Following steps are involved in using EventDispatchAction in a Struts application. Step 1:- develop a user defined class that extends EventDispatchAction Step 2:- For each use-cases develop a user defined method with execute prototype but method name. Step 3:- register the action class(any number of times) with parameter attribute whose value is the user defined method name. For eg. <action path="/both" parameter="insert,delete=remove" type="MyEventDispatchAction" name="someform1"> <action path="/omit" parameter="remove" type="MyEventDispatchAction" name="someform2"> Note:- insert and remove are the user defined methods in user defined action class MyEventDispatchAction. Step 4:- submit button caption(request parameter value) can be any thing. But submit button name(request) parameter name) should be the specified value in <action> tag i.e. user defined method name or alias name. DispatchAction no i18n,different form bean LookupDispatchAction i18n support can't use different form bean MappingDispatchAction no i18n but can use different form bean EventDispatchAction i18n + diff form bean --eventdispatchactionapplication is not given in the handout Q)Explain about IncludeAction. =>org.apache.struts.actions.IncludeAction is used to include some jsp into another jsp in logical name based manner. =>The following steps are involved in using IncludeAction. Step 1:- <action name="/footer" type="org.apache.struts.actions.IncludeAction" paremeter="/footer.jsp"/> Step 2:- including pages make the following entry. <jsp:include page="/footer.do"/> Note:- This built-in action is seldom used. Q)Explain about modularising the Struts Application. =>Dividing a master struts application into discrete modules is nothing but modularising the struts application. =>Each module has its own jsps, form beans, action classes and configuration file. =>To support project modules, modularisation concept is given in struts. It provides development convenience. Q)What are the steps involved in modularising a Struts Application? =>The following steps are used to modularise a Struts Application. Step 1:- Develop a configuration file per module. For eg.
  • 48. Struts Struts By L N Rao Page 48 struts-config.xml(default module) struts-config-user.xml(user module) struts-config-admin.xml(admin module) =>Configure the jsps, form-beans, action classes of each module in each configuration file. Step 2:- Supply configuration files to ActionServlet as init parameters. For eg. <servlet> <servlet-name>frontcontroller</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <init-param> <param-name>config/admin</param-name> <param-value>/WEB-INF/struts-config-admin.xml</param-value> </init-param> <init-param> <param-name>config/user</param-name> <param-value>/WEB-INF/struts-config-user.xml</param-value> </init-param> </servlet> Step 3:- Whenever necessary, create module specific urls in jsps. protocol://ipaddress:port/applicationname/moduleprefix/logicalname ________________________________________________________________________________________________________ Day:-41 08/11/12 ------------ Q)How does modularisation work in the background? =>As soon as the application is deployed, within the init method of ActionServlet, each configuration file is converted into ModuleConfig object and is stoted into the application scope. Each ModuleConfig object is stored in ServletContext with module prefix (appended to some constant used by the framework) as attribute name. =>Whenever client request comes, based on the module prefix, appropriate ModuleConfig object is retrieved from the application scope to provide support for the use-case functionality. Q)Explain about SwitchAction. =>It is one of the built in Struts action classes. =>It is similar to that of ForwardAction except linking to the jsp of other module. =>SwitchAction takes the module prefix from the query string of the link and switches the module before switching the control to the target page. Q)How can a servlet handle both GET and POST requests? public class MyServlet extends HttpServlet { public void doGet(....)throws SE,IOE { process(request,response); } public void doGet(....)throws SE,IOE { process(request,response); } private void process(HttpServletRequest request,HttpServletResponse response)throws SE,IOE { //actual task of the servlet }//user defined method }//user defined servlet
  • 49. Struts Struts By L N Rao Page 49 Q)How does Struts work in the background? =>"struts in background 07-nov-12.bmp" Q)Explain about ModuleConfig? =>object oriented representation of Struts configuration file is nothing but ModuleConfig object. =>Each tag of Struts configuration file is converted into Java object and the references of all those Java objects are stored in ModuleConfig object. =>Framework uses ModuleConfig object to deal with the MVC functionality of the application. =>ModuleConfig object is the meta information repository of the Struts application. ___________________________________________________________________________________________________________ Day:-42 09/11/12 ------------ Q)What is the general structure of ActionServlet? public class ActionServlet extends HttpServlet { public void init(ServletConfig config) { /* 1.)reading the configuration file 2.)converting xml into ModuleConfig object using digester API and storing the same into application scope 3.)instantiating and initializing plug-ins if any */ }//init() public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException { process(request,response); } public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException { process(request,response); } public void process(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException { ModuleConfig mconfig = getModuleConfig(); RequestProcessor rp = getRequestProcessorForModule(mconfig); rp.process(request,response); } } Q)Explain about RequestProcessor. =>RequestProcessor is the work horse of Struts for each client request. =>RequestProcessor is a normal java class.It is not a web component. =>For each use-case of the Struts application, framework functionality is performed by RequestProcessor. =>RequestProcessor does a.)form bean instantiation b.)populating the bean fields c.)invoking the validation logic d.)creating action class instance e.)invoking the execute method etc. =>RequestProcessor has methods to do each task. These methods are processXXX methods. For eg. a.)processActionForm() b.)processPopulate() c.)processValidate() d.)processActionCreate() e.)processActionPerform() etc. Q)How to have user defined RP for a Struts Application? =>For almost all the requirements built-in RP is sufficient. Very rarely to interface in framework's
  • 50. Struts Struts By L N Rao Page 50 functionality we need to have our own RP. Step 1:- Develop a Java class tthat extends RP. Step 2:- Override the required method of RP whose functionality we want to modify. Step 3:- Specify the user defined RP in configuration file using <controller> tag. Q)Develop a Struts Application in which the following things are used. 1.) user defined request processor(RequestProcessor). 2.) user defined plug in(PlugIn). =>Refer to handout (page 23 - requestprocessorapplication) Q)Explain about plug-in in a Struts Application. =>A java class that implements org.apache.struts.action.PlugIn interface is nothing but a plug-in in a struts application. =>Whatever resources required to the struts application at the time of its deployment can be provided through plugin class. =>PlugIn is instantiated with ActionServlet and destroyed ActionServlet. =>There are two kinds of Plug-ins. 1.)built-in plugins (validator and tiles) 2.)user defined plug in Q)How to make use of a user defined plugin in a Struts application? Step 1:- Develop a Java class that implements PlugIn interface. Step 2:- override init() method & destroy() methods of PlugIn intreface. Step 3:- If we want to supply any values through struts-config.xml, declare a private variable for each property in plugin class and define one setter method. Step 4:- Configure the user defined PlugIn class in Struts configuration file using <plug-in> tag. __________________________________________________________________________________________________________ Day:-43 10/11/12 ------------ Q)Explain about processPreprocess() method of RequestProcessor. =>This is the entry point into the struts functionality. This method returns boolean. By default, RequestProcessor implemented this method to return true. =>We can override this method and write any code that has to be executed before any use case functionality is executed. For eg. security logic. =>If this method returns false, no more processing of the request further takes place. --while using pure html tag ".do" must be added. Q)Explain about the double submit issue in a struts application. =>User may submit the same web form twice which is nothing but double submission. =>Double submission of the web form some times irritating for the end-user and some times has serious consequences. =>Struts developer should address this issue. Even though the form is double submitted, we should ensure that there is no side effect on the application(application's data). Q)How to prevent the dangers caused by double submission of the form in a struts application. =>org.apache.struts.action.Action class has three methods to deal with double submission of the web form. 1.)saveToken(request):- This method generates a unique number called a token and stores into session scope. 2.)resetToken(request):- This method destroys the token stored in session object. 3.)isTokenValid(request) : - This method captures the incoming token from the client(as hidden form field) and compares it with already stored token in the session scope. If it is matched, it returns true otherwise false. =><html:form> tag's tag handler is responsible to retrieve the token from the session scope and converts it into hidden form field. Q)Struts Application that deals with double submit issue. =>RTH
  • 51. Struts Struts By L N Rao Page 51 Q)What is file uploading? =>Sending a file from client machine to web server machine is nothing but file uploading. Q)How to perform the file uploading in a Struts Application? Step 1:- Develop the form bean with org.apache.struts.upload.FormFile field. Object oriented representation of user uploaded file is nothing but "FormFile" object. Step 2:- In execute method of action class, get the file details(name, content, size etc.) from FormFile object and implement I/O logic to store the file into the web server machine. Step 3:- create user input page with the following 1.) HTTP request method is POST 2.) user control type is "file" 3.) make use of the following attribute with the specified value of form tag. enctype="multipart/form-data" Step 4:- Additionally place "commons-fileupload.jar" into the lib folder. Q)Struts Application on file uploading. =>Refer to handout. -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------------ Day:-44 12/11/12 ----------- Q)How to implement pagination in a Struts Application? =>Using a third party "display tag library" or by writing our own logic. =>For the example application refer to RTH. Q)How to deploy a Struts Application into JBoss Application Server? Step 1:- Create war file. Step 2:- Start JBOSS and invoke admin console. http://localhost:8080/admin-console Step 3:- Specify struts application's war file and deploy graphically. _________________________________________________________________________________________________________ Day:-45 15/11/12 ------------ Q)How to make use of SwitchAction in a Struts Application? Step 1:- Configure this built-in action class in the struts-config.xml. <action path="./switchmodule" type="org.apache.struts.actions.SwitchAction"/> Step 2:- Create hyperlink as follows. <A href=./switchmodule.do?prefix=/admin&page=/some.do>Click Here</A> OR <html:link action="/switchmodule?prefix=/admin&page=/some.do">Click Here</html:link> Develop a Struts 1.x Project using Myeclipse --------------------------------------------------------- Steps to develop Struts Application using MyEclipse - Step 1:- create a web project Step 2:- response page development Step 3:- Model class development Step 4:- Add Struts capabilities Right click on the project -> Myeclipse -> Add Struts capabilities Step 5:- imput page, form bean & action class development right click on the project -> new -> other -> enter "struts" into the text box of the wizard Configuring Tomcat in Myeclipse -------------------------------------------- window -> preferences -> type tomcat into the wizard -> select tomcat 6 -> enable radio button -> specify tomcat location by clicking browse button -> select JDK under tomcat 6.x -> Add -> specify the location
  • 52. Struts Struts By L N Rao Page 52 of jdk -> OK ********************************************* __________________________________________________________________________________________________________ Day:-46 16/11/12 ------------ html library used web form creation error link creation client side struts provided validation code embedding bean library in memory data retrieval resourse bundle data logic __________________________________________________________________________________________________________ Day:-47 19/11/12 ------------ Struts 2.x ------------- Q)What are the similarities between Struts 1.x and Struts 2.x ? =>MVC based Java web application frameworks. =>Both are action based. i.e. action classes are the sub controllers. =>have front controller Q)What are the differences between Struts 1.x and 2.x ? Struts 1.x Struts 2.x ---------- ---------- 1)a servlet is the front controller. 1)a servlet filter is the front controller. i.e. ActionServlet. i.e. FilterDispatcher 2)RequestProcessor is the main client 2)no RequestProcessor request handler. Interceptors replaced RequestProcessor. 3)form bean acts as data container for 3)action instance acts like form bean instance the data that is heading from view to model via controller. 4)action class is not a POJO 4)can be a POJO 5)action class is a singleton and hence 5)is thread safe as it is not a singleton thread safety issues have to be handled. 6)execute method has servlet dependencies6)execute() is non-parameterised and hence testability and therefore testability is complex. improves. 7)struts-config.xml 7)struts.xml
  • 53. Struts Struts By L N Rao Page 53 8)no annotations support 8)to some extent 9)processing is relatively heavy weight 9)light weight ***************************************************************************************** Q)What is the architecture of struts 2? =>"struts2 architecture 19-nov-12.bmp" ________ _____________________________ __________________________________________________________________ Day:-48 20/11/12 ------------ Q)How to develop a struts 2 application? Step 1:- Develop view components(jsps mostly) Step 2:- Develop the action class Step 3:- Develop struts.xml Step 4:- Struts 2-enable the application by configuring FilterDispatcher as front controller in web.xml Note:- place struts 2 jar files into the lib folder and place struts.xml into the "classes" folder. Q)Develop a struts 2 application to implement the use-case of user authentication. loginapplication login.jsp loginfailed.jsp welcome.jsp WEB-INF web.xml src LoginAction.java LoginModel.java classes *.class struts.xml lib *.jar http://localhost:8081/loginapplication Note:- LoginModel.java, loginfailed.jsp and welcome.jsp from Struts 1 "loginapplication". LoginAction.java ---------------------- package com.nareshit.controller; import com.nareshit.service.LoginModel; public class LoginAction { private String username; private String password; //setters & getters public String execute()
  • 54. Struts Struts By L N Rao Page 54 { boolean flag = new LoginModel().isAuthenticated(username,password); if(flag) return "success"; else return "failure"; } } struts.xml ------------- <struts> <package name="mypack" extends="struts-default"> <action name="login" class="com.nareshit.controller.LoginAction"> <result name="success">/welcome.jsp</result> <result name="failure">/loginfailed.jsp</result> </action> </package> </struts> web.xml ----------- <web-app> <filter> <filter-name>frontcontroller</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>frontcontroller</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> </web-app> login.jsp ----------- <%@ taglib uri="/struts-tags" prefix="s" %> <html> <body bgcolor="yellow"> <center> <h1>Login to www.nareshit.com</h1> <s:form action="login" method="post"> <s:textfield label="username" name="username"/><br> <s:textfield label="password" name="password"/><br> <s:submit value="login"/> </s:form> </center> </body> </html> __________________________________________________________________________________________________________ Day:-49 21/11/12 ----------- Q)Modify Struts1 "accountapplication" into that of Struts2. struts2accountapplication account.jsp noaccount.jsp accountdetails.jsp WEB-INF
  • 55. Struts Struts By L N Rao Page 55 web.xml src AccountAction.java AccountModel.java Account.java(DTO) DBUtil.java lib commons-logging-1.1.jar freemarker-2.3.8.jar ognl-2.6.11.jar struts2-core-2.0.6.jar xwork-2.0.1.jar classes struts.xml *.class http://localhost:8081/struts2accountapplication Note:- noaccount.jsp, Account.java, AccountModel.java and DBUtil.java from struts 1 accountapplication. web.xml ----------- =>From the previous application except making account.jsp as the home page. struts.xml ------------ <struts> <package name="mypack" extends="struts-default"> <action name="account" class="com.nareshit.controller.AccountAction"> <result name="success">/accountdetails.jsp</result> <result name="failure">/noaccount.jsp</result> </action> </package> </struts> account.jsp -------------- <%@ taglib uri="/struts-tags" prefix="s" %> <html> <body bgcolor="cyan"> <center> <h1>Account Details Retrieval</h1> <s:form action="account"> <s:textfield label="Account Number" name="accno"/> <br><br> <s:submit value="get account details"/> </s:form> </center> </body> </html> AccountAction.java ------------------------ package com.nareshit.controller; import com.nareshit.vo.Account; import com.nareshit.service.AccountModel; public class AccountAction { private int accno; private String name; private float balance; //setters & getters
  • 56. Struts Struts By L N Rao Page 56 private static AccountModel am; static { am = new AccountModel(); } public String execute() { String rpage="failure"; Account acc = am.getAccountDetails(accno); if(acc!=null) { setName(acc.getName()); setBalance(acc.getBalance()); rpage = "success"; } return rpage; } } accountdetails.jsp ------------------------ <%@ taglib prefix="s" uri="/struts-tags" %> <html> <body bgcolor="cyan"> <h1>Account Details of A/C No <s:property value="accno" /></h1> A/C holder name: <s:property value="name"/><br> Balance Rs. <s:property value="balance"/><br> </body> </html> ___________________________ Day:-50 22/11/12 ------------ Q)Modify the previous application to implement declarative exception handling. declarativeexpapplication account.jsp noaccount.jsp accountdetails.jsp problem.jsp WEB-INF web.xml src AccountAction.java AccountModel.java DBUtil.java AccountNotFoundException.java ProcessingException.java classes *.class lib *.jar http://localhost:8081/declarativeexpapplication AccountAction.java ------------------------ public String execute()throws Exception { Account acc = am.getAccountDetails(accno); setName(acc.getName()); setBalance(acc.getBalance()); return "success"; }
  • 57. Struts Struts By L N Rao Page 57 struts.xml ------------- <struts> <package name="mypack" extends="struts-default"> <action name="account" class="com.nareshit.controller.AccountAction"> <action-mapping exception="com.nareshit.exception.AccountNotFoundException" result="noacc"/> <action-mapping exception="com.nareshit.exception.ProcessingException" result="problem"/> <result name="success">/accountdetails.jsp</result> <result name="noacc">/noaccount.jsp</result> <result name="problem">/problem.jsp</result> </action> </package> </struts> Q)How to deal with session tracking and coockies in a Struts 2 action class? =>user defined action class needs to lose its POJOness. public class MyAction implements org.apache.struts2.interceptor.ServletRequestAware, org.apache.struts2.interceptor.ServletResponseAware { HttpServletRequest request; HttpServletResponse response; public void setServletRequest(HttpServletRequest request) { this.request = request; } public void setServletResponse(HttpServletResponse response) { this.response = response; } public String execute() { HttpSession session = request.getSession(); ........ ........ } } __________________________________________________________________________________________________________ Day:-21 23/11/12 ----------- Q)Explain about ActionSupport in Struts 2? =>org.opensymphony.xwork2.ActionSupport is a built in Struts 2 class. =>It implements the following interfaces. 1.)Serializable 2.)Action 3.)Validateable 4.)ValidationAware 5.)LocaleProvider 6.)TestProvider =>While implementing real use-cases a Struts2 action class can't be a POJO. It extends ActionSupport class. Q)Struts 2 application on Tiles? =>RTH Q)Struts 2 application on i18n? =>RTH Declarative validation
  • 58. Struts Struts By L N Rao Page 58 --------------------------- LoginAction-validation.xml ---------------------------------- <validators> <field name="username"> <field-validator type="requiredstring"> <message>user name is required</message> </field-validator> </field> <field name="password"> <field-validator type="requiredstring"> <message>password field is empty</message> </field-validator> <field-validator type="stringlength"> <param name="maxLength">10</param> <param name="minLength">4</param> <param name="trim">true</param> <message>Enter password 4-10 characters long</message> </field-validator> </field> </validators> __________________________________________________________________________________________________________ THANK YOU!

×