Presentation is loading. Please wait.

Presentation is loading. Please wait.

Struts Framework Day-2 Ashok Chakravarti. DataSource Usage Sample Struts-config.xml ….......................

Similar presentations


Presentation on theme: "Struts Framework Day-2 Ashok Chakravarti. DataSource Usage Sample Struts-config.xml …......................."— Presentation transcript:

1 Struts Framework Day-2 Ashok Chakravarti

2 DataSource Usage Sample Struts-config.xml ….......................

3 Sample of code under execute() 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=?");

4 Sample of code under execute() 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"; }

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

6 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 Request Processing Basics

7 Form Construction The Basics of Form Processing This section provides information on the following tags: - Render an HTML element - T ext box INPUT element — INPUT type=hidden element — Place a Submit INPUT element — Place a Submit INPUT element which can be used to “cancel” workflow

8 ” 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 Generates HTML: Bean form bound: public class SimpleForm extends ActionForm { private String firstName; private String lastName;

10 Where address is a form bean property which will be set with a selected value. Generates:

11 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")); } Input Validation

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

13 DynaActionForms org.apache.struts.action.DynaActionForm config: 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 execute(...) { DynaActionForm loginForm = (DynaActionForm )form; String name = (String)myForm.get(“name”); } DynaActionForms inside Action

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"/>

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

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" %> Email address: Password: <html:radio property="operation" value="createAccount"/> Create Account <html:radio property="operation" value="changePassword"/> Change Password <html:radio property="operation" value="deleteAccount"/> Delete Account

26 Sample confirmation JSP Page <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %> Account Created Account successfully created for. Congratulations.

27 Sample confirmation JSP Page


Download ppt "Struts Framework Day-2 Ashok Chakravarti. DataSource Usage Sample Struts-config.xml …......................."

Similar presentations


Ads by Google