java struts questions

Upload: kaviarasu

Post on 31-May-2018

213 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/14/2019 Java STRUTS Questions

    1/13

    Struts

    Struts is a open source framework which make building of the web applications easier based on thejava Servlet and JavaServer pages technologies.

    Struts framework was created by Craig R. McClanahan and donated to the Apache Software Foundationin 2000. The Project now has several committers, and many developers are contributing to overall tothe framework.

    Developing web application using struts frame work is fairly complex, but it eases things after it is

    setup. It encourages software development following the MVC design pattern. Many web applicationsare JSP-only or Servlets-only. With JSP and Servlets, Java code is embedded in the HTML code and theJava code calls println methods to generate the HTML code respectively. Both approaches have theiradvantages and drawbacks; Struts gathers their strengths to get the best of their association.

    Struts is based on Model-View-Controller (MVC) design paradigm, it is an implementation of JSP Model2 Architecture. For more of Model-View-Controller (MVC) click here.

    Consists of 8 Top-Level Packagesand approx 250 Classes and Interfaces.

    Struts is a set of cooperating classes, servlets, and JSP tags that make up a reusable MVC 2 design.This definition implies that Struts is a framework, rather than a library, but Struts also contains anextensive tag library and utility classes that work independently of the framework.

    The overview of struts

    Client browserAn HTTP request from the client browser creates an event. The Web container will respond with an

    HTTP response.

    ControllerThe controller is responsible for intercepting and translating user input into actions tobe performed by the model. The controller is responsible for selecting the next view based on userinput and the outcome of model operations.The Controller receives the request from the browser, andmakes the decision where to send the request. With Struts, the Controller is a command design patternimplemented as a servlet. The struts-config.xml file configures the Controller.

    Business logicThe business logic updates the state of the model and helps control the flow of the application. WithStruts this is done with an Action class as a thin wrapper to the actual business logic.

    ModelA model represents an applications data and contains the logic for accessing and manipulating thatdata. Any data that is part of the persistent state of the application should reside in the model objects.The business objects update the application state. ActionForm bean represents the Model state at asession or request level, and not at a persistent level. Model services are accessed by the controller for

    either querying or effecting a change in the model state. The model notifies the view when a statechange occurs in the model.The JSP file reads information from the ActionForm bean using JSP tags.

    ViewThe view is responsible for rendering the state of the model. The presentation semantics areencapsulated within the view, therefore model data can be adapted for several different kinds ofclients.The view modifies itself when a change in the model is communicated to the view. A viewforwards user input to the controller.The view is simply a JSP file. There is no flow logic, no businesslogic, and no model information -- just tags. Tags are one of the things that make Struts uniquecompared to other frameworks like Velocity.

    MVC

  • 8/14/2019 Java STRUTS Questions

    2/13

    The MVC (Model-View-Controller) architecture the client request is first intercepted by a servletreferred as controller servlet. this servlet handles the initial processing of the request and determineswhich JSP page to display next. Here the controller servlet is the single point of entry, there is a clearsepration of business logic, presentation output and request processing. MCV architecture is a way ofdecomposing an application into three parts:

    The model maintains the state and data that the application represents.The view allows the display of information about the model to the user.

    The controller allows the user to manipulate the application.

    the model, the view and the controller.

    MVC was originally applied in the graphical user interaction model of input, processing and output.

    In Struts, the view is handled by JSPs and presentation components, the model is represented by JavaBeans and the controller uses Servlets to perform its action.

    ModelA model represents an applications data and contains the logic for accessing and manipulating that

    data. Any data that is part of the persistent state of the application should reside in the model objects.The business objects update the application state. ActionForm bean represents the Model state at a

    session or request level, and not at a persistent level. Model services are accessed by the controller for

    either querying or effecting a change in the model state. The model notifies the view when a statechange occurs in the model.The JSP file reads information from the ActionForm bean using JSP tags.

    ViewThe view is responsible for rendering the state of the model. The presentation semantics areencapsulated within the view, therefore model data can be adapted for several different kinds ofclients.The view modifies itself when a change in the model is communicated to the view. A view

    forwards user input to the controller.The view is simply a JSP or HTML file. There is no flow logic, nobusiness logic, and no model information -- just tags. Tags are one of the things that make Struts

    unique compared to other frameworks like Velocity.

    Controller

    The controller is responsible for intercepting and translating user input into actions tobe performed by the model. The controller is responsible for selecting the next view based on userinput and the outcome of model operations.The Controller receives the request from the browser, andmakes the decision where to send the request. With Struts, the Controller is a command design patternimplemented as a servlet. The struts-config.xml file configures the Controller.

    Installing Struts

    In order to do any Java development you need the Java Developer Kit. You can find JDK1.4 at

    http://java.sun.com.

    Just execute the installation executable and follow the instructions.

    You will need to setup the PATH and the JAVA HOME variables;

    Struts can also be found as a subproject of the Jakarta project (http://jakarta.apache.org). There is no Struts

    installation for the moment, just uncompress it in a convenient directory.

    Copy the following JAR files, extracted from the Jakarta Struts archive, to the

    /WEB-INF/lib directory:struts.jarcommons-beanutils.jar

    commons-collections.jarcommons-digester.jarcommons-logging.jarcommons-validator.jar

  • 8/14/2019 Java STRUTS Questions

    3/13

    Copy the tld files you want to use in the /WEB-INF directory:struts-html.tldstruts-bean.tldstruts-logic.tldstruts-nested.tld

    struts-template.tld

    If you want to use tiles add the struts-tiles.tld also in the /WEB-INF directory.

    Struts 1.0 and 1.1

    The new features added to Struts 1.1 are

    1. RequestProcessor class2. Method perform() replaced by execute() in Struts base Action Class3.4.

    5.6.7.8.

    910.

    11.12.13.

    Changes to web.xml and struts-config.xmlDeclarative exception handling

    Dynamic ActionFormsPlug-insMultiple Application ModulesNested Tags

    The Struts ValidatorChange to the ORO package

    Change to Commons loggingRemoval of Admin actionsDeprecation of the GenericDataSource

    Struts Controller

    The controller is responsible for intercepting and translating user input into actions to be performed bythe model. The controller is responsible for selecting the next view based on user input and the

    outcome of model operations. The Controller receives the request from the browser, invoke a businessoperation and coordinating the view to return to the client.

    The controller is implemented by a java servlet, this servlet is centralized point of control for the web

    application. In struts framework the controller responsibilities are implemented by several differentcomponents like

    The ActionServlet ClassThe RequestProcessor Class

    The Action Class

    The ActionServlet extends the javax.servlet.http.httpServlet class. The ActionServlet class is notabstract and therefore can be used as a concrete controller by your application.

    The controller is implemented by the ActionServlet class. All incoming requests are mapped to thecentral controller in the deployment descriptor as follows.

    actionorg.apache.struts.action.ActionServlet

    All request URIs with the pattern *.do are mapped to this servlet in the deployment descriptor asfollows.

  • 8/14/2019 Java STRUTS Questions

    4/13

    action*.do

    *.do

    A request URI that matches this pattern will have the following form.http://www.my_site_name.com/mycontext/actionName.do

    The preceding mapping is called extension mapping, however, you can also specify path mappingwhere a pattern ends with /* as shown below.

    action/do/*

    *.do

    A request URI that matches this pattern will have the following form.http://www.my_site_name.com/mycontext/do/action_Name

    The class org.apache.struts.action.requestProcessor process the request from the controller. You

    can sublass the RequestProcessor with your own version and modify how the request is processed.

    Once the controller receives a client request, it delegates the handling of the request to a helper class.This helper knows how to execute the business operation associated with the requested action. In theStruts framework this helper class is descended oforg.apache.struts.action.Action class. It acts asa bridge between a client-side user action and business operation. The Action class decouples the clientrequest from the business model. This decoupling allows for more than one-to-one mapping between

    the user request and an action. The Action class also can perform other functions such asauthorization, logging before invoking business operation. the Struts Action class contains several

    methods, but most important method is the execute() method.

    public ActionForward execute(ActionMapping mapping,

    ActionForm form, HttpServletRequest request, HttpServletResponseresponse)

    throws Exception;

    The execute() method is called by the controller when a request is received from a client. Thecontroller creates an instance of the Action class if one doesnt already exist. The strut framework willcreate only a single instance of each Action class in your application.

    Action are mapped in the struts configuration file and this configuration is loaded into memory at

    startup and made available to the framework at runtime. Each Action element is represented inmemory by an instance of the org.apache.struts.action.ActionMapping class . The ActionMapping object

    contains a path attribute that is matched against a portion of the URI of the incoming request.

    path= "/somerequest"type="com.somepackage.someAction"scope="request"name="someForm"

    validate="true"input="somejsp.jsp"

    Once this is done the controller should determine which view to return to the client. The executemethod signature in Action class has a return type org.apache.struts.action.ActionForward class. TheActionForward class represents a destination to which the controller may send control once an action

  • 8/14/2019 Java STRUTS Questions

    5/13

    has completed. Instead of specifying an actual JSP page in the code, you can declaratively associate asaction forward through out the application. The action forward are specified in the configuration file.

    path= "/somerequest"type="com.somepackage.someAction"scope="request"

    name="someForm"validate="true"

    input="somejsp.jsp"

    The action forward mappings also can be specified in a global section, independent of any specificaction mapping.

    Struts Model

    A model represents an applications data and contains the logic for accessing and manipulating thatdata. Any data that is part of the persistent state of the application should reside in the model objects.The business objects update the application state. ActionForm bean represents the Model state at asession or request level, and not at a persistent level. Model services are accessed by the controller for

    either querying or effecting a change in the model state. The model notifies the view when a statechange occurs in the model.The JSP file reads information from the ActionForm bean using JSP tags.

    The Struts frame work doen't offer much in the way pf building model components. The EnterpriseJavaBeans (EJB), Java Data Objects(JDO) and JavaBeans can be use as a model. Struts frame work

    doesn't limit you to one particular model implementation.

    Struts View

    The view is responsible for rendering the state of the model. The presentation semantics areencapsulated within the view, therefore model data can be adapted for several different kinds of

    clients.The view modifies itself when a change in the model is communicated to the view. A viewforwards user input to the controller.The view is simply a JSP or HTML file. There is no flow logic, no

    business logic, and no model information -- just tags. Tags are one of the things that make Strutsunique compared to other frameworks like Velocity.

    The view components typically employed in a struts application areHTMLData Transfer ObjectsStruts ActionFormsJavaServer pages

    Custom tagsJava resource bundles

    Struts ActionForm

    Struts ActionForm objects are used to pass client input data back and forth between the user and thebusiness layer. The framework automatically collects the input from the request and passes this data toan Action using a form bean, which is then passed to the business layer.

    Struts Tag Library

  • 8/14/2019 Java STRUTS Questions

    6/13

    The Struts framework provides a fairly rich set of framework components. It also includes a set of taglibraries that are designed to interact intimately with the rest o the framework. The customg tagsprovided by Struts framework are grouped into four distinct libraries1. HTML2. Bean3. Logic

    4. Template

    And a special library called Nested tag library.

    Custom tags with in Struts HTML tag library

    base - renders an HTML base elementbutton - renders a button input fielscancel - renders a cancel buttoncheckbox - renders a checkbox input fielderrors - conditionnaly renders a set of accumulated error messagesfile - renders a file select input fieldform - defines an HTML form elementframe - renders an HTML frame elementhidden - renders a hidden fieldhtml - renders an HTMl html elementimage - renders an input tag of type "image"img - renders an HTMl img tag

    javascript - renderts JavaScript validation rules loaded by ValidationPluginlink - renders an HTML anchoror hyperlinkmessages - Conditionally displays a set of accumulated messagesmultibox -renders multiple checkbox input fieldsoption - renders a select optionoptions - renders a collection of select optionsoptions Collection - render a collection of select optionspassword -renders apassword input field

    radio -renders a radio button input field

    reset -renders a rest button input field

    rewrite - renders a URI

    select -renders a select element

    submit -renders a submi button

    text -renders an input field of type "text"textarea -renders an textarea input field

    Struts Example

    Struts is modeled after the MVC design pattern, you can follow a standard development process for allof your Struts Web applications.

    Identificaty of the application Views, the Controller objects that will service those Views, and the Modelcomponents being operated on.

    1. Define and create all of the Views, in relation to their purpose, that will represent the user interfaceof our application. Add all ActionForms used by the created Views to the struts-config.xml file.2. Create the components of the applications Controller.

    3. Define the relationships that exist between the Views and the Controllers (struts-config.xml).4. Make the appropriate modifications to the web.xml file, describe the Struts components to the Webapplication.

    Lets Start with step one. we will create the view file named index.jsp

    index.jsp

    Sample Struts Application

  • 8/14/2019 Java STRUTS Questions

    7/13

    Name:

    We have used some Struts-specific Form tag like instead of HTML tags.

    In the Form tags the attributes you can find some attributes defined in we will go through it.

    action : Represents the URL to which this form will be submitted. This attribute is also used to find theappropriate ActionMapping in the Struts configuration file, which we will describe later in this section.The value used in our example is Name, which will map to an ActionMapping with a path attributeequal to Name.

    name :Identifies the key that the ActionForm will be referenced by. We use the value NameForm. An

    ActionForm is an object that is used by Struts to represent the form data as a JavaBean. It mainpurpose is to pass form data between View and Controller components. We will discuss NameFormlater in this section.type :Names the fully qualified class name of the form bean to use in this request. For this example,

    we use thevalue example.NameForm, which is an ActionForm object containing data membersmatching the inputs of this form.

    To use the HTML tags, you must first add a taglib entry in the applications web.xml file that referencesthe URI /WEB-INF/struts-html.tld. This TLD describes all of the tags in the HTML tag library. The

    following snippet shows the element that must be added to the web.xml file:

    /WEB-INF/struts-html.tld/WEB-INF/struts-html.tld

    The struts-html.tld is placed in the /WEB_INF directory.

    Next Step is to create the action form

    The ActionForm used in this example contains a single data member that maps directly to the nameinput parameter of the form defined in the index.jsp View. When an is submitted, theStruts framework populates the matching data members of the ActionForm with the values entered

    into the tags. The Struts framework does this by using JavaBean reflection. Theaccessors of the ActionForm must follow the JavaBean standard naming convention for example

    private String name;public void setName(String name);public String getName();

  • 8/14/2019 Java STRUTS Questions

    8/13

    The NameForm.java file is shown belowNameForm.java

    package example;//import statementsimport javax.servlet.http.HttpServletRequest;

    import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionMapping;

    public class NameForm extends ActionForm {

    private String name = null;public String getName() {

    return (name);

    }

    public void setName(String name) {

    this.name = name;

    }

    public void reset(ActionMapping mapping, HttpServletRequest request) {

    this.name = null;

    }

    }

    To deploy the NameForm to our Struts application, you need to compile this class, move it to the/WEB-INF/classes/example directory, and add the following line to the section of the/WEB-INF/struts-config.xml file:

    This makes the Struts application aware of the NameForm and how it should be referenced.

    Now we create the out page for the sample application.Lets name it diplayname.jspdisplayname.jsp

    Sample Struts Display Name

    Hello !!

    Now we move to the step two of creating the application's controller

    In a Struts application, two components make up the Controller. These two components are theorg.apache.struts.action.ActionServlet and the org.apache. struts.action.Action classes. Inmost Struts applications, there is one org. apache.struts.action.ActionServlet implementation and

    can have many org.apache. struts.action.Action implementations.

    The org.apache.struts.action.ActionServlet is the Controller component that handles client

    requests and determines which org.apache.struts.action.Action will process the received request.

  • 8/14/2019 Java STRUTS Questions

    9/13

    When assembling simple applications, such as the one we are building, the default ActionServlet willsatisfy your application needs, and therefore, you do not need to create a specializedorg.apache.struts.action.ActionServlet implementation.

    The second component of a Struts Controller is the org.apache.struts. action.Action class. Asopposed to the ActionServlet, the Action class must be extended for each specialized function in your

    application. This class is where your applications specific logic begins.NameAction.java

    package example;

    import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;

    import org.apache.struts.action.ActionMapping;

    public class NameAction extends Action {

    public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException {

    String target = new String("success");if ( form != null ) {

    // Use the NameForm to get the request parametersNameForm nameForm = (NameForm)form;String name = nameForm.getName();

    }

    // if no mane supplied Set the target to failureif ( name == null ) {

    target = new String("failure"); }

    else {

    request.setAttribute("NAME", name);

    }

    return (mapping.findForward(target));}

    }

    Moving to step three, to deploy the NameAction to our Struts application, we need to compile the

    NameAction class and move the class file to /WEB-INF/classes/example directory, and add the

    following entry to the section of the /WEB-INF/struts-config.xml file:

    For step four we modify the web.xml file. We have to to tell the Web application about ourActionServlet. This is accomplished by adding the following servlet definition to the /WEB-INF/web.xml

    file:

    action

  • 8/14/2019 Java STRUTS Questions

    10/13

    org.apache.struts.action.ActionServlet

    config/WEB-INF/struts-config.xml

    1

    Once we have told the container about the ActionServlet, we need to tell it when the action should beexecuted. To do this, we have to add a element to the /WEB-INF/ web.xml file:

    action*.do

    You will notice in the previously listed index.jsp that our action does not include a .do at the end of the

    URL. We do not have to append the .do because it is automatically appended if we use the tag. If you do not use the tag, then you will need to append .do to the action's URL.

    This mapping tells the Web application that whenever a request is received with .do appended to theURL, the servlet named action should service the request.

    Now you are ready to run the application, to begin using this application, you need to open your Webbrowser to the following URL:http://localhost:port/example/

    Struts Internationalization (i18n)Struts Internationalization (i18n) can be done with some handy modifications in our existingapplication. We have to know the two Internationalization (i18n) components that are packaged withthe Struts Framework. The first of these components, which is managed by the application Controller,is a Message class that references a resource bundle containing Locale-dependent strings. The second

    Internationalization (i18n) component is a JSP custom tag, , which is used in theView layer to present the actual strings managed by the Controller.

    In this section we will move with an example to understand the whole process. We are continuing thesame example which we used earlier to understand the simple struts example in the section StrutsExample.

    First thing we will require for Internationalization (i18n) is a set of simple Java properties files. Each filecontains a key/value pair for each message that you expect your application to present, in thelanguage appropriate for the requesting client.

    This property file contains the key/value pairs for the default language of your application. The naming

    format for this file is ResourceBundleName.properties. An example of this default file, using English asthe default language, would be ApplicationResources.properties A sample entry in this file would

    be app.name=Name, this tells Struts that for every occurrence of the app.name key the Name will besubstituted.

    We must define a properties file for each language that your application will use. This file must follow

    the same naming convention as the default properties file, except that it must include the two-letterISO language code of the language that it represents. Example of this naming conventionFor an German-speaking client would be ApplicationResources_de.properties

    For an French-speaking client would be ApplicationResources_fr.propertiesFor an Italian-speaking client would be ApplicationResources_it.properties

    http://www.allapplabs.com/struts/configuring_struts.htmhttp://www.allapplabs.com/struts/configuring_struts.htmhttp://www.allapplabs.com/struts/configuring_struts.htmhttp://www.allapplabs.com/struts/configuring_struts.htm
  • 8/14/2019 Java STRUTS Questions

    11/13

    For an Spanish-speaking client would be ApplicationResources_es.properties

    Now add the respective entries in each properties files you require.

    After you define all of the properties files for your application, you need to make Struts aware of them.It is achieved by adding a sub-element to the struts-config.xml file. Then you

    should copy all the resource bundles into the application classpath, /WEB-INF/classes/example, andthen use the package path plus the base file name as the value of the

    subelement. The following snippet shows an example of using the subelement

    to configure a resource bundle, using the properties files described above

    Once this part is done we customise the view part , this is achieved throught the second i18ncomponent defined by the Struts Framework is a JSP custom tag, , which is used topresent the actual strings that have been loaded by the Controller.

    To use the , we must first deploy the bean tag library, which contains the

    tag. Deploying a tag library is a very simple process that requires only the additionof a new entry in the web.xml file of the Web application using the bean library. Here is an

    example of this

    entry:

    /WEB-INF/struts-bean.tld/WEB-INF/struts-bean.tld

    Also check that the struts-bean.tld file is copied to the /WEB-INF/ folder.

    tag and how it is configured for use.

    Now we are done we will check step by step of our saple application.

    1. WeCreate the resource bundles that will contain the key/value pairs used in your application. For our

    application, we will have four properties files that contain our resource bundles.

    The German ApplicationResources_de.properties file.app.name=Name

    app.hello=Hallo

    The French ApplicationResources_fr.properties file.app.name=Nomapp.hello=Bonjour

    The Italian ApplicationResources_it.properties file.app.name=Nome

    app.hello=Ciao

    The Spanish ApplicationResources_fr.properties file.app.name=Nombreapp.hello=Hola

    The English ApplicationResources.properties file.app.name=Nameapp.hello=Hello

    2. Copy all of the properties files to the /WEB-INF/classes/example directory.Add an application subelement, naming the wiley. ApplicationResources to the

    struts-config.xml file, as shown

  • 8/14/2019 Java STRUTS Questions

    12/13

    3. Modify the web.xml file as discussed above by adding

    /WEB-INF/struts-bean.tld

    /WEB-INF/struts-bean.tld

    4. Modify the index.jsp fileindex.jsp

    Sample Struts Application

    :

    Modify the diplayname.jspdisplayname.jsp

    Sample Struts Display Name

  • 8/14/2019 Java STRUTS Questions

    13/13

    !!

    So we are done with Internationalization (i18n) you need to open your Web browser to the followingURL:

    http://localhost:port/example/