Successfully reported this slideshow.

Struts tutorial


Published on

Struts Tutorial

Published in: Education, Technology
  • Be the first to comment

Struts tutorial

  1. 1. Struts TutorialMVC ArchitectureStruts MVC ArchitectureThe model contains the business logic and interact with the persistance storage tostore, retrive and manipulate data.The view is responsible for dispalying the results back to the user. In Struts theview layer is implemented using JSP.The controller handles all the request from the user and selects the appropriateview to return. In Sruts the controllers job is done by the ActionServlet.The following events happen when the Client browser issues an HTTP request.The ActionServlet receives the request.The struts-config.xml file contains the details regardingthe Actions, ActionForms,ActionMappings and ActionForwards.During the startup the ActionServelet reads the struts-config.xml file and creates adatabase of configuration objects. Later while processing the requestthe ActionServletmakes decision by refering to this object.When the ActionServlet receives the request it does the following tasks.Bundles all the request values into a JavaBean class which extendsStruts ActionForm class.Decides which action class to invoke to process the request.Validate the data entered by the user.The action class process the request with the help of the model component. Themodel interacts with the database and process the request.After completing the request processing the Action class returnsan ActionForward to the controller.Based on the ActionForward the controller will invoke the appropriate view.The HTTP response is rendered back to the user by the view component.Hello World Example in Eclipse Page 1 of 19
  2. 2. Struts TutorialIn this tutorial you will learn how to create a Struts hello world applicationin eclipse. First create a new project, go to File->New and selectDynamicWebProject.Enter the project name and click the Finish button. Page 2 of 19
  3. 3. Add the following jar files to the WEB-INFlib directory.Right click the src folder and select New->Package. Page 3 of 19
  4. 4. Enter the package name as com.vaannila.form and click Finish.Now right click the newly created package and select New->Class.Enter the class name as HelloWorldForm and the superclass nameasorg.apache.struts.action.ActionForm and click Finish. Page 4 of 19
  5. 5. In the HelloWorldForm class add the following code.01.package com.vaannila.form;02.03.import org.apache.struts.action.ActionForm;04.05.public class HelloWorldForm extends ActionForm {06.07.private static final long serialVersionUID = -473562596852452021L;08.09.private String message;10.11.public String getMessage() {12.return message;13.}14.15.public void setMessage(String message) {16.this.message = message;17.}18.}In the same way create a new package com.vaannila.action and create Page 5 of 19
  6. 6. a HelloWorldActionclass extending org.apache.struts.action.Action. Add thefollowing code to the action class and save it.01.package com.vaannila.action;02.03.import javax.servlet.http.HttpServletRequest;04.import javax.servlet.http.HttpServletResponse;05.06.import org.apache.struts.action.Action;07.import org.apache.struts.action.ActionForm;08.import org.apache.struts.action.ActionForward;09.import org.apache.struts.action.ActionMapping;10.11.import com.vaannila.form.HelloWorldForm;12.13.public class HelloWorldAction extends Action {14.15.@Override16.public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throwsException{17.HelloWorldForm hwForm = (HelloWorldForm) form;18.hwForm.setMessage("Hello World");19.return mapping.findForward("success");20.}21.}Here we typecast the ActionForm to HelloWorldForm and set the messagevalue.Add the following entries in the struts-config.xml file.01.<?xml version="1.0" encoding="ISO-8859-1" ?>02.03.<!DOCTYPE struts-config PUBLIC04."-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"05."">06.07.<struts-config>08.09.<form-beans>10.<form-bean name="helloWorldForm"type="com.vaannila.form.HelloWorldForm"/>11.</form-beans>12.13.<global-forwards>14.<forward name="helloWorld" path="/"/>15.</global-forwards>16.17.<action-mappings>18.<action path="/helloWorld"type="com.vaannila.action.HelloWorldAction"name="helloWorldForm">19.<forward name="success" path="/helloWorld.jsp" />20.</action>21.</action-mappings>22. Page 6 of 19
  7. 7. 23.</struts-config>Now configure the deployment descriptor. Add the following configurationinformation in theweb.xml file.01.<?xml version="1.0" encoding="UTF-8"?>02.<web-app xmlns:xsi=""xmlns=""xmlns:web=""xsi:schemaLocation="" id="WebApp_ID"version="2.5">03.<display-name>StrutsExample1</display-name>04.05.<servlet>06.<servlet-name>action</servlet-name>07.<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>08.<init-param>09.<param-name>config</param-name>10.<param-value>/WEB-INF/struts-config.xml</param-value>11.</init-param>12.<load-on-startup>2</load-on-startup>13.</servlet>14.15.<servlet-mapping>16.<servlet-name>action</servlet-name>17.<url-pattern>*.do</url-pattern>18.</servlet-mapping>19.20.<welcome-file-list>21.<welcome-file>index.jsp</welcome-file>22.</welcome-file-list>23.</web-app>When we run the application the index.jsp page will be executed first. Inthe index.jsp page we redirect the request to the URI, whichinturn invokes the HelloWorldAction.1.<%@ taglib uri="" prefix="logic" %>2.<logic:redirect forward="helloWorld"/>In the action class we return the ActionForward "success" which is mappedto thehelloWorld.jsp page. In the helloWorld.jsp page we display the "HelloWorld" message.01.<%@taglib uri="" prefix="bean" %>02.<html>03.<head>04.<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">05.<title>Hello World</title>06.</head>07.<body>08.<bean:write name="helloWorldForm" property="message"/>09.</body>10.</html>After creating all the files the directory structure of the application lookslike this. Page 7 of 19
  8. 8. On executing the application the "Hello World" message gets displayed to theuser.Hello World ApplicationLets say a quick hello to struts. Struts follows MVC 2 pattern. The followingfiles are needed to create a hello world Page 8 of 19
  9. 9. web.xmlweb.xml is used to configure the servlet container properties of the helloworld appliation.1.<welcome-file-list>2.<welcome-file>index.jsp</welcome-file>3.</welcome-file-list>The gateway for our hello world application is index.jsp file. The index.jsp fileshould be mentioned in web.xml as shown above.index.jspIn the hello world example the index.jsp page simply forwards the request tothe hello world action.1.<jsp:forward page=""/>struts-config.xmlstruts-config.xml file is used to configure the struts framework for the helloworld application. This file contains the details regarding the form bean andthe action mapping.01.<struts-config>02. Page 9 of 19
  10. 10. 03.<form-beans>04.<form-bean name="HelloWorldActionForm"05.type="com.vaannila.HelloWorldActionForm"/>06.</form-beans>07.08.<action-mappings>09.<action input="/index.jsp" name="HelloWorldActionForm"path="/HelloWorld" scope="session"type="com.vaannila.HelloWorldAction">10.<forward name="success" path="/helloWorld.jsp" />11.</action>12.</action-mappings>13.14.</struts-config>HelloWorldActionForm.javaHelloWorldActionForm extends org.apache.struts.action.ActionForm.HelloWorldActionForm class has one String variable message and thecorresponding getter and setter methods.01.public class HelloWorldActionForm {03.04.private String message;05.06.public HelloWorldActionForm() {07.super();08.}09.10.public String getMessage() {11.return message;12.}13.14.public void setMessage(String message) {15.this.message = message;16.}17.18.}HelloWorldAction.javaHelloWorldAction class extends org.apache.struts.action.Action. The actionclass contains an execute method which contains the business logic of theapplication. To access the HelloWorldActionForm variables in the Action weneed to type caste the form object to HelloWorldActionForm. Then we canaccess the variables using the getter and setter methods. The executemethod returns a value of type ActionForward, based on its value thecorresponding view will be called. This configuration is done in struts-config.xml file.01.public class HelloWorldAction extends org.apache.struts.action.Action {02.03.private final static String SUCCESS = "success";04.05.public ActionForward execute(ActionMapping mapping,ActionForm form, Page 10 of 19
  11. 11. 06.HttpServletRequest request,HttpServletResponseresponse)throws Exception {07.08.HelloWorldActionForm helloWorldForm = (HelloWorldActionForm) form;09.helloWorldForm.setMessage("Hello World!");10.return mapping.findForward(SUCCESS);11.12.}13.}1.<action-mappings>2.<action input="/index.jsp" name="HelloWorldActionForm"path="/HelloWorld"3.scope="session" type="com.vaannila.HelloWorldAction">4.<forward name="success" path="/helloWorld.jsp" />5.</action>6.</action-mappings>The name "success" is mapped to the view helloWorld.jsp. So when theexecute method in the action returns "success" the request will be forwardedto the helloWold.jsp page.helloWorld.jspIn helloWorld.jsp we get the value of the form variable message and displayit. We use struts bean tag to do this. The name attribute of the bean tag holdthe value of the action form and the property attribute holds the value of thevariable to be displayed.01.<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>02.<html>03.<head>04.<title>Hello World</title>05.</head>06.<body>07.<h1>08.<bean:write name="HelloWorldActionForm" property="message" />09.</h1>10.</body>11.</html>Extract the downloaded files into the webapps folder of the Tomcat server.Start the Tomcat server. Type the following url in the browser"http://localhost:8080/Example1/index.jsp". There you go, you have yourfirst struts program up and running. Page 11 of 19
  12. 12. Login Application Using Action FormLogin Application Using Action FormIn this example we will see how to create a login application usingActionForm. The following files are required for the login application.login.jspsuccess.jspfailure.jspweb.xmlstruts-config.xmlLoginAction.javaLoginForm.javaApplicationResource.propertiesweb.xmlThe first page that will be called in the login application is the login.jsp page.This configuration should be done in web.xml as shown below.1.<welcome-file-list>2.<welcome-file>login.jsp</welcome-file>3.</welcome-file-list>login.jspWe use Struts HTML Tags to create login page. The form has one text field toget the user name and one password field to get the password. The form alsohas one submit button, which when clicked calls the loginaction. <html:errors /> tag is used to display the error messages to the user.01.<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>02.<html>03.<head>04.<title>Login Page</title>05.</head> Page 12 of 19
  13. 13. 06.<body>07.<div style="color:red">08.<html:errors />09.</div>10.<html:form action="/Login" >11.User Name :<html:text name="LoginForm" property="userName" />12.Password :<html:password name="LoginForm" property="password" />13.<html:submit value="Login" />14.</html:form>15.</body>16.</html>The user enters the user name and password and clicks the login button. Thelogin action is invoked.struts-config.xmlThe validate method in the LoginForm class is called when the Form issubmitted. If any errors are found then the control is returned back to theinput page where the errors are displayed to the user. The input page isconfigured in the action tag of strut-config file. <html:errors /> tag is used todisplay the errors in the jsp page.01.<struts-config>02.<form-beans>03.<form-bean name="LoginForm" type="com.vaannila.LoginForm"/>04.</form-beans>05.06.<action-mappings>07.<action input="/login.jsp" name="LoginForm" path="/Login"scope="session" type="com.vaannila.LoginAction">08.<forward name="success" path="/success.jsp" />09.<forward name="failure" path="/failure.jsp" />10.</action>11.</action-mappings>12.</struts-config>Here the action is "/Login" , the input page is "login.jsp" and thecorresponding action class is Now the validate method inthe LoginForm class will be invoked.LoginForm.javaInside the validate method, we check whether the user name and password isentered. If not the corresponding error message is displayed to the user. Theerror messages are configured in the file.01.public ActionErrors validate(ActionMapping mapping, HttpServletRequestrequest) {02.ActionErrors errors = new ActionErrors();03.if (userName == null || userName.length() < 1) {04.errors.add("userName", newActionMessage("error.userName.required"));05.}06.if (password == null || password.length() < 1) {07.errors.add("password", newActionMessage("error.password.required"));08.} Page 13 of 19
  14. 14. 09.return errors;10.}ApplicationResource.propertiesThe file contains the error messages. The key"error.userName.required" is used in the validate function to add a new error.Since the error messages are configured in a seperate properties file they canbe changed anytime without making any changes to the java files or the jsppages.1.error.userName.required = User Name is required.2.error.password.required = Password is required.If either user name or password is not entered then the corresponding errormessage will be added to the ActionErrors. If any errors are found then thecontrol is returned back to the input jsp page, where the error messages aredisplayed using the <html:errors /> tag. The validate method is used toperform the client-side validations. Once when the input data is valid theexecute method in the LoginAction class is called.LoginAction.javaThe execute method contains the business logic of the application. Here firstwe typecast the ActionForm object to LoginForm, so that we can access theform variables using the getter and setter methods. If the user name andpassword is same then we forward the user to the success page else weforward to the failure page.01.public class LoginAction extends org.apache.struts.action.Action {02.03.private final static String SUCCESS = "success";04.private final static String FAILURE = "failure";05.06.public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throwsException{07.LoginForm loginForm = (LoginForm) form;08.if (loginForm.getUserName().equals(loginForm.getPassword())) {09.return mapping.findForward(SUCCESS);10.} else {11.return mapping.findForward(FAILURE);12.}13.}14.}Lets enter the user names and password as "Eswar". Since the user name andpassword is same the execute method will return an ActionForward"success". The corresponding result associated with the name "success" willbe shown to the user. This configuration is done in struts-config.xml file.1.<action-mappings>2.<action input="/login.jsp" name="LoginForm" path="/Login"scope="session" type="com.vaannila.LoginAction">3.<forward name="success" path="/success.jsp" /> Page 14 of 19
  15. 15. 4.<forward name="failure" path="/failure.jsp" />5.</action>6.</action-mappings>So according to the configuration in struts-config.xml the user will beforwarded to success.jsp page.If the user name and password did not match the user will be forwarded tothe failure page. Lets try entering "Joe" as the user name and "Eswar" as thepassword, the following page will be displayed to the user. Page 15 of 19
  16. 16. DispatchAction ClassDispatchAction ClassDispatchAction provides a mechanism for grouping a set of related functionsinto a single action, thus eliminating the need to create seperate actions foreach functions. In this example we will see how to group a set of user relatedactions like add user, update user and delete user into a single action calledUserAction.The class UserAction extends org.apache.struts.actions.DispatchAction. Thisclass does not provide an implementation of the execute() method as thenormal Action class does. The DispatchAction uses the execute method tomanage delegating the request to the individual methods based on theincoming request parameter. For example if the incoming parameter is"method=add", then the add method will be invoked. These methods shouldhave similar signature as the execute method.01.public class UserAction extends DispatchAction {02.03.private final static String SUCCESS = "success";04.05.public ActionForward add(ActionMapping mapping, ActionForm form,06.HttpServletRequest request, HttpServletResponse response)07.throws Exception {08.UserForm userForm = (UserForm) form;09.userForm.setMessage("Inside add user method.");10.return mapping.findForward(SUCCESS);11.}12.13.public ActionForward update(ActionMapping mapping, ActionForm form,14.HttpServletRequest request, HttpServletResponse response)15.throws Exception {16.UserForm userForm = (UserForm) form;17.userForm.setMessage("Inside update user method.");18.return mapping.findForward(SUCCESS);19.}20.21.public ActionForward delete(ActionMapping mapping, ActionForm form, Page 16 of 19
  17. 17. 22.HttpServletRequest request, HttpServletResponse response)23.throws Exception {24.UserForm userForm = (UserForm) form;25.userForm.setMessage("Inside delete user method.");26.return mapping.findForward(SUCCESS);27.}28.}If you notice the signature of the add, update and delete methods are similarto the execute method except the name. The next step is to create an actionmapping for this action handler. The request parameter name is specifiedusing the parameter attribute. Here the request parameter name is method.1.<action-mappings>2.<action input="/index.jsp" parameter="method" name="UserForm"path="/UserAction" scope="session" type="com.vaannila.UserAction">3.<forward name="success" path="/index.jsp" />4.</action>5.</action-mappings>Now lets see how to invoke a DispatchAction from jsp. We have a simple formwith three buttons to add, update and delete a user. When each button isclicked a different method in UserAction class is invoked.01.<html>02.<head>03.<script type="text/javascript">04.function submitForm()05.{06.document.forms[0].action = ""07.document.forms[0].submit();08.}09.</script>10.</head>11.<body>12.<html:form action="UserAction" >13.<table>14.<tr>15.<td>16.<bean:write name="UserForm" property="message" />17.</td>18.</tr>19.<tr>20.<td>21.<html:submit value="Add" onclick="submitForm()" />22.</td>23.</tr>24.<tr>25.<td>26.<html:submit property="method" value="update" />27.</td>28.</tr>29.<tr>30.<td>31.<html:submit property="method" >delete</html:submit>32.</td> Page 17 of 19
  18. 18. 33.</tr>34.</table>35.</html:form>36.</body>37.</html>Now consider the update and the delete button. The request parameter namespecified in the action handler is "method". So this should be specified as theproperty name for the submit button. The name of the method to be invokedand the value of the button should be the same. So when the button isclicked the corresponding method in the UserAction will be called. Thedelete button shows an alternate way to specify the value of the button.Here the main constraint is the method name and the button name should besame. So we cant have an update button like this "Update". Inorder to avoidthis you can call a javascript function on click of the button. Specify theaction and submit the form from javascript. In this way we can have adifferent button name and method name. On click of the Add button theaction value is set to "" and the form is submittedfrom javascript.On executing the sample example the following page is displayed to the user.After clicking the add button the following page is displayed. Page 18 of 19
  19. 19. Page 19 of 19