1 / 27

Struts Framework Day-2

Ashok Chakravarti. Struts Framework Day-2. Sample Struts-config.xml < struts-config > < data-sources > < data-source type = "org.apache.tomcat.dbcp.dbcp.BasicDataSource" > < set-property property = "driverClassName" value = "com.mysql.jdbc.Driver" />

harry
Download Presentation

Struts Framework Day-2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Ashok Chakravarti Struts Framework Day-2

  2. Sample Struts-config.xml <struts-config> <data-sources> <data-sourcetype="org.apache.tomcat.dbcp.dbcp.BasicDataSource"> <set-propertyproperty="driverClassName"value="com.mysql.jdbc.Driver"/> <set-propertyproperty="url"value="jdbc:mysql://localhost:3306/strutsdatabase?autoReconnect=true"/> <set-propertyproperty="username"value="root"/> <set-propertyproperty="password"value=""/> <set-propertyproperty="defaultAutoCommit"value="false"/> </data-source> </data-sources> …....................... </struts-config> DataSource Usage

  3. public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { javax.sql.DataSource dataSource = null; java.sql.Connection myConnection = null; try { dataSource = getDataSource(request); myConnection = dataSource.getConnection(); PreparedStatement statement = myConnection.prepareStatement("SELECT password FROM BasicAuthentication WHERE userid=?"); Sample of code under execute()

  4. statement.setString(1, loginForm.getUserName()); ResultSet resultSet = statement.executeQuery(); if(resultSet.next()) { String password = resultSet.getString("password"); if((password != null) && password.equalsIgnoreCase(loginForm.getPassword())) { target = "success"; request.setAttribute("userName", loginForm.getUserName()); } else { target = "failure"; } } Sample of code under execute()

  5. catch (SQLException sqle) { getServlet().log("Connection.process", sqle);} finally { try { if(myConnection != null) {myConnection.close();} } catch (SQLException e) { getServlet().log("Connection.close", e); } } Sample of code under execute()

  6. Request Processing Basics If action mapping defined in the configuration file, the Controller Servlet/RequestProcessor will perform the following: Check session or request for instance of bean of appropriate class If no session/request bean exists, one is created automatically For every request parameter whose name corresponds to the name of a property in the bean, the corresponding setter method will be called The validate() method of ActionForm is called The updated ActionForm bean will be passed to the Action Class execute() method when it is called, making these values immediately available The execute() method must return an instance of ActionForward – instructing the controller which is the next view (page) The next page is merged with data passed in request or session object, and then renders HTML

  7. Form Construction The Basics of Form Processing This section provides information on the following tags: <html:form> - Render an HTML <form> element <html:text> - Text box INPUT element <html:hidden>— INPUT type=hidden element <html:submit>—Place a Submit INPUT element <html:cancel>—Place a Submit INPUT element which can be used to “cancel” workflow

  8. <html:form action="simpleAction" method="POST"> ”simplAction” - action name corresponds to action name in configuration <action path="/simpleAction" cancellable="true" type="edu.depaul.struts.SimpleAction" name="simpleBean" //– name of bean mapped to form controls scope="request" input="/index.jsp" >

  9. <html:text property="firstName"/> Generates HTML: <input type="text" name="firstName" value=""> Bean form bound: public class SimpleForm extends ActionForm { private String firstName; private String lastName;

  10. <html:select property="address"> <html:option value="Please, make selection"/> <html:options property="addresses"/> </html:select> Where address is a form bean property which will be set with a selected value. <html:submit value="Submit"/> Generates: <input type="submit" value="Submit">

  11. Input Validation Validation can be provided: FormBean.validate(ActionMapping mapping, HttpServletRequest request) Directly in the Action.execute() method: ActionErrors errors = new ActionErrors(); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.task.notassigned")); if (!errors.empty()) { saveErrors(request, errors); return (mapping.findForward("failure")); }

  12. Message Configuration Resource Bundle specified in a struts-config file: <message-resources parameter="struts-examples" /> Simple Java properties file: message_key=Message Text Usage at Form to display errors <html:errors> - outputs all error messages <html:errors property=”propName”> - outputs a message for property “propName” if one exists

  13. DynaActionForms org.apache.struts.action.DynaActionForm config: <form-bean name=”loginForm” type=”org.apache.struts.action.DynaActionForm”> <form-property name=”userId” type=”java.lang.String” initial=”admin”/> <form-property name=”password” type=”java.lang.String”/> </form-bean> No need to write any Java. Validation? There is no validate() method. Solution1: validate in Action Solution 2: sub-class the DynaActionForm class and add a validate() method Solution 3: Use validation framework Disadvantage: not type safe, typos can lead to hours of debugging (no Compile time type checking)

  14. DynaActionForms inside Action execute(...) { DynaActionForm loginForm = (DynaActionForm )form; String name = (String)myForm.get(“name”); }

  15. Validation Framework Jakarta Commons Validator Framework http://jakarta.apache.org/commons Deployed as a Struts Plugin Extended by Struts to provide generic validation rules Common Rules: check for required fields check for max/min size check for the right data type

  16. Validator Built-in Rules required – field data provided minlength – more than min length maxlength – less than max length range – in range of values mask – correct format (takes regexp) date – validates correct date format email – validates correct E-Mail fromat

  17. Validator Files validation-rules.xml – contains all possible rules validation.xml – contains mappings of forms, properties and rules

  18. Validator Setup Following entry needs to be added to struts-config.xml <plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" value="/org/apache/struts/validator/validator-rules.xml, /WEB-INF/validation.xml"/> </plug-in>

  19. Questions??

  20. DispatchAction • org.apache.struts.actions.DispatchAction class provides a mechanism for modularizing a set of related functions into a single action. abstract Action that dispatches to a public method that is named by the request parameter whose name is specified by the parameter property. This Action is useful to combine many similar actions into a single Action class and help in simplifying application design.

  21. Sample DispatchAction Class public ActionForward createAccount(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception public ActionForward changePassword(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception public ActionForward deleteAccount(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception

  22. Sample struts-config.xml <action-mappings> <action name="manageAccountForm" path="/login" scope="request" type="com.eperium.strutstraining.ManageAccount" validate="true" parameter="method"> <forward name="createAccount" path="/create.jsp"> <forward name="deleteAccount" path="/delete.jsp"></forward> <forward name="changePassword" path="/password.jsp"></forward> </action> </action-mappings>

  23. Changes to ActionForm The getter needed for this special parameter determines which radio button is initially selected No setter needed for this special parameter It is automatically populated when the input form is submitted.

  24. Sample Form

  25. Sample JSP Page <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %> <html:form action="/accountMod"> Email address: <html:text property="email"/><BR> Password: <html:password property="password"/><BR> <TABLE CELLSPACING="10"> <TR> <TD><html:radio property="operation" value="createAccount"/> Create Account</TD> <TD><html:radio property="operation" value="changePassword"/> Change Password</TD> <TD><html:radio property="operation" value="deleteAccount"/> Delete Account</TD> </TR> </TABLE> <html:submit value="Perform Selected Operation"/> </html:form>

  26. Sample confirmation JSP Page <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %> <!DOCTYPE ...> <HTML> <HEAD><TITLE>Account Created</TITLE></HEAD> <BODY BGCOLOR="#FDF5E6"> <CENTER> <H1>Account successfully created for <bean:write name="userFormBean" property="email"/>.</H1> Congratulations. </CENTER> </BODY></HTML>

  27. Sample confirmation JSP Page

More Related