Struts 2 – Themes & Templates ”; Previous Next Before starting actual tutorial for this chapter, let us look into few definition as given by https://struts.apache.org− Sr.No Term & Description 1 TAG A small piece of code executed from within JSP, FreeMarker, or Velocity. 2 TEMPLATE A bit of code, usually written in FreeMarker, that can be rendered by certain tags (HTML tags). 3 THEME A collection of templates packaged together to provide common functionality. I would also suggest going through the Struts2 Localization chapter because we will take same example once again to perform our excercise. When you use a Struts 2 tag such as <s:submit…>, <s:textfield…> etc in your web page, the Struts 2 framework generates HTML code with a preconfigured style and layout. Struts 2 comes with three built-in themes − Sr.No Theme & Description 1 SIMPLE theme A minimal theme with no “bells and whistles”. For example, the textfield tag renders the HTML <input/> tag without a label, validation, error reporting, or any other formatting or functionality. 2 XHTML theme This is the default theme used by Struts 2 and provides all the basics that the simple theme provides and adds several features like standard two-column table layout for the HTML, Labels for each of the HTML, Validation and error reporting etc. 3 CSS_XHTML theme This theme provides all the basics that the simple theme provides and adds several features like standard two-column CSS-based layout, using <div> for the HTML Struts Tags, Labels for each of the HTML Struts Tags, placed according to the CSS stylesheet. As mentioned above, if you don’t specify a theme, then Struts 2 will use the xhtml theme by default. For example, this Struts 2 select tag − <s:textfield name = “name” label = “Name” /> generates following HTML markup − <tr> <td class=”tdLabel”> <label for = “empinfo_name” class=”label”>Name:</label> </td> <td> <input type = “text” name = “name” value = “” id = “empinfo_name”/> </td> </tr> Here empinfo is the action name defined in struts.xml file. Selecting Themes You can specify the theme on as per Struts 2, tag basis or you can use one of the following methods to specify what theme Struts 2 should use − The theme attribute on the specific tag The theme attribute on a tag”s surrounding form tag The page-scoped attribute named “theme” The request-scoped attribute named “theme” The session-scoped attribute named “theme” The application-scoped attribute named “theme” The struts.ui.theme property in struts.properties (defaults to xhtml) Following is the syntax to specify them at tag level if you are willing to use different themes for different tags − <s:textfield name = “name” label = “Name” theme=”xhtml”/> Because it is not very much practical to use themes on per tag basis, so simply we can specify the rule in struts.properties file using the following tags − # Standard UI theme struts.ui.theme = xhtml # Directory where theme template resides struts.ui.templateDir = template # Sets the default template type. Either ftl, vm, or jsp struts.ui.templateSuffix = ftl Following is the result we picked up from localization chapter where we used the default theme with a setting struts.ui.theme = xhtml in struts-default.properties file which comes by default in struts2-core.xy.z.jar file. How a Theme Works? For a given theme, every struts tag has an associated template like s:textfield → text.ftl and s:password → password.ftl etc. These template files come zipped in struts2-core.xy.z.jar file. These template files keep a pre-defined HTML layout for each tag. In this way, Struts 2 framework generates final HTML markup code using Sturts tags and associated templates. Struts 2 tags + Associated template file = Final HTML markup code. Default templates are written in FreeMarker and they have an extension .ftl. You can also design your templates using velocity or JSP and accordingly set the configuration in struts.properties using struts.ui.templateSuffix and struts.ui.templateDir. Creating New Themes The simplest way to create a new theme is to copy any of the existing theme/template files and do required modifications. Let us start with creating a folder called template in WebContent/WEBINF/classes and a sub-folder with the name of our new theme. For example, WebContent/WEB-INF/classes/template/mytheme. From here, you can start building templates from scratch, or you can also copy the templates from the Struts2 distribution where you can modify them as required in future. We are going to modify existing default template xhtml for learning purpose. Now, let us copy the content from struts2-core-x.y.z.jar/template/xhtml to our theme directory and modify only WebContent/WEBINF/classes/template/mytheme/control.ftl file. When we open control.ftl which will have the following lines − <table class=”${parameters.cssClass?default(”wwFormTable”)?html}”<#rt/> <#if parameters.cssStyle??> style=”${parameters.cssStyle?html}”<#rt/> </#if> > Let us change above file control.ftl to have the following content − <table style = “border:1px solid black;”> If you will check form.ftl then you will find that control.ftl is used in this file, but form.ftl is referring this file from xhtml theme. So let us change it as follows − <#include “/${parameters.templateDir}/xhtml/form-validate.ftl” /> <#include “/${parameters.templateDir}/simple/form-common.ftl” /> <#if (parameters.validate?default(false))> onreset = “${parameters.onreset?default(”clearErrorMessages(this); clearErrorLabels(this);”)}” <#else> <#if parameters.onreset??> onreset=”${parameters.onreset?html}” </#if> </#if> #include “/${parameters.templateDir}/mytheme/control.ftl” /> I assume that, you would not have much understanding of the FreeMarker template language, still you can get a good idea of what is to be done by looking at the .ftl files. However, let us save above changes, and go back to our localization example and create the WebContent/WEB-INF/classes/struts.properties file with the following content # Customized them struts.ui.theme = mytheme # Directory where theme template resides struts.ui.templateDir = template # Sets the template type to ftl. struts.ui.templateSuffix = ftl Now after this change, right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat”s webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2. This will produce the following screen − You can see a border around the form component which is a result of the change we did in out theme after copying it from xhtml theme. If you put little effort in learning FreeMarker, then
Category: struts 2
Struts2 – Form Tags
Struts 2 – The Form Tags ”; Previous Next The list of form tags is a subset of Struts UI Tags. These tags help in the rendering of the user interface required for the Struts web applications and can be categorised into three categories. This chapter will take you thorugh all the three types of UI tags − Simple UI Tags We have used these tags in our examples already, we will brush them in this chapter. Let us look a simple view page email.jsp with several simple UI tags − <%@ page language = “java” contentType = “text/html; charset = ISO-8859-1” pageEncoding = “ISO-8859-1″%> <%@ taglib prefix = “s” uri = “/struts-tags”%> <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”> <html> <head> <s:head/> <title>Hello World</title> </head> <body> <s:div>Email Form</s:div> <s:text name = “Please fill in the form below:” /> <s:form action = “hello” method = “post” enctype = “multipart/form-data”> <s:hidden name = “secret” value = “abracadabra”/> <s:textfield key = “email.from” name = “from” /> <s:password key = “email.password” name = “password” /> <s:textfield key = “email.to” name = “to” /> <s:textfield key = “email.subject” name = “subject” /> <s:textarea key = “email.body” name = “email.body” /> <s:label for = “attachment” value = “Attachment”/> <s:file name = “attachment” accept = “text/html,text/plain” /> <s:token /> <s:submit key = “submit” /> </s:form> </body> </html> If you are aware of HTML, then all the tags used are very common HTML tags with an additional prefix s: along with each tag and different attributes. When we execute the above program, we get the following user interface provided you have setup proper mapping for all the keys used. As shown, the s:head generates the javascript and stylesheet elements required for the Struts2 application. Next, we have the s:div and s:text elements. The s:div is used to render a HTML Div element. This is useful for people who do not like to mix HTML and Struts tags together. For those people, they have the choice to use s:div to render a div. The s:text as shown is used to render a text on the screen. Next we have the famiilar s:form tag. The s:form tag has an action attribute that determines where to submit the form. Because we have a file upload element in the form, we have to set the enctype to multipart. Otherwise, we can leave this blank. At the end of the form tag, we have the s:submit tag. This is used to submit the form. When the form is submitted, all the form values are submitted to the the action specified in the s:form tag. Inside the s:form, we have a hidden attribute called secret. This renders a hidden element in the HTML. In our case, the “secret” element has the value “abracadabra”. This element is not visible to the end user and is used to carry the state from one view to another. Next we have the s:label, s:textfield, s:password and s:textarea tags. These are used to render the label, input field, password and the text area respectively. We have seen these in action in the “Struts – Sending Email” example. The important thing to note here is the use of “key” attribute. The “key” attribute is used to fetch the label for these controls from the property file. We have already covered this feature in the Struts2 Localization, internationalization chapter. Then, we have the s:file tag which renders a input file upload component. This component allows the user to upload files. In this example, we have used the “accept” parameter of the s:file tag to specify which file types are allowed to be uploaded. Finally we have the s:token tag. The token tag generates an unique token which is used to find out whether a form has been double submitted When the form is rendered, a hidden variable is placed as the token value. Let us say, for example that the token is “ABC”. When this form is submitted, the Struts Fitler checks the token against the token stored in the session. If it matches, it removes the token from the session. Now, if the form is accidentally resubmitted (either by refreshing or by hitting the browser back button), the form will be resubmitted with “ABC” as the token. In this case, the filter checks the token against the token stored in the session again. But because the token “ABC” has been removed from the session, it will not match and the Struts filter will reject the request. Group UI Tags The group UI tags are used to create radio button and the checkbox. Let us look a simple view page HelloWorld.jsp with check box and radio button tags − <%@ page contentType = “text/html; charset = UTF-8″%> <%@ taglib prefix = “s” uri = “/struts-tags”%> <html> <head> <title>Hello World</title> <s:head /> </head> <body> <s:form action = “hello.action”> <s:radio label = “Gender” name = “gender” list=”{”male”,”female”}” /> <s:checkboxlist label = “Hobbies” name = “hobbies” list = “{”sports”,”tv”,”shopping”}” /> </s:form> </body> </html> When we execute the above program, our output will look similar to the following − Let us look at the example now. In the first example, we are creating a simple radio button with the label “Gender”. The name attribute is mandatory for the radio button tag, so we specify a name which is “gender”. We then supply a list to the gender. The list is populated with the values “male” and “female”. Therefore, in the output we get a radio button with two values in it. In the second example, we are creating a checkbox list. This is to gather the user”s hobbies. The user can have more than one hobby and therefore we are using the checkbox instead of the radiobutton. The checkbox is populated with the list “sports”, “TV” and “Shopping”. This presents the hobbies as a checkbox list. Select UI Tags Let us explore the different variations of the Select Tag offered by Struts. Let us look a simple view page
Struts2 – Exception Handling
Struts 2 – Exception Handling ”; Previous Next Struts provides an easier way to handle uncaught exception and redirect users to a dedicated error page. You can easily configure Struts to have different error pages for different exceptions. Struts makes the exception handling easy by the use of the “exception” interceptor. The “exception” interceptor is included as part of the default stack, so you don”t have to do anything extra to configure it. It is available out-of-the-box ready for you to use. Let us see a simple Hello World example with some modification in HelloWorldAction.java file. Here, we deliberately introduced a NullPointer Exception in our HelloWorldAction action code. package com.tutorialspoint.struts2; import com.opensymphony.xwork2.ActionSupport; public class HelloWorldAction extends ActionSupport{ private String name; public String execute(){ String x = null; x = x.substring(0); return SUCCESS; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Let us keep the content of HelloWorld.jsp as follows − <%@ page contentType = “text/html; charset = UTF-8” %> <%@ taglib prefix = “s” uri = “/struts-tags” %> <html> <head> <title>Hello World</title> </head> <body> Hello World, <s:property value = “name”/> </body> </html> Following is the content of index.jsp − <%@ page language = “java” contentType = “text/html; charset = ISO-8859-1” pageEncoding = “ISO-8859-1″%> <%@ taglib prefix = “s” uri = “/struts-tags”%> <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”> <html> <head> <title>Hello World</title> </head> <body> <h1>Hello World From Struts2</h1> <form action = “hello”> <label for = “name”>Please enter your name</label><br/> <input type = “text” name = “name”/> <input type = “submit” value = “Say Hello”/> </form> </body> </html> Your struts.xml should look like − <?xml version = “1.0” Encoding = “UTF-8”?> <!DOCTYPE struts PUBLIC “-//Apache Software Foundation//DTD Struts Configuration 2.0//EN” “http://struts.apache.org/dtds/struts-2.0.dtd”> <struts> <constant name = “struts.devMode” value = “true” /> <package name = “helloworld” extends = “struts-default”> <action name = “hello” class = “com.tutorialspoint.struts2.HelloWorldAction” method = “execute”> <result name = “success”>/HelloWorld.jsp</result> </action> </package> </struts> Now right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat”s webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the following screen − Enter a value “Struts2” and submit the page. You should see the following page − As shown in the above example, the default exception interceptor does a great job of handling the exception. Let us now create a dedicated error page for our Exception. Create a file called Error.jsp with the following contents − <%@ page language = “java” contentType = “text/html; charset = ISO-8859-1” pageEncoding = “ISO-8859-1″%> <%@ taglib prefix = “s” uri = “/struts-tags”%> <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”> <html> <head> <title></title> </head> <body> This is my custom error page </body> </html> Let us now configure Struts to use this this error page in case of an exception. Let us modify the struts.xml as follows − <?xml version = “1.0” Encoding = “UTF-8”?> <!DOCTYPE struts PUBLIC “-//Apache Software Foundation//DTD Struts Configuration 2.0//EN” “http://struts.apache.org/dtds/struts-2.0.dtd”> <struts> <constant name = “struts.devMode” value = “true” /> <package name = “helloworld” extends = “struts-default”> <action name = “hello” class = “com.tutorialspoint.struts2.HelloWorldAction” method = “execute”> <exception-mapping exception = “java.lang.NullPointerException” result = “error” /> <result name = “success”>/HelloWorld.jsp</result> <result name = “error”>/Error.jsp</result> </action> </package> </struts> As shown in the example above, now we have configured Struts to use the dedicated Error.jsp for the NullPointerException. If you rerun the program now, you shall now see the following output − In addition to this, Struts2 framework comes with a “logging” interceptor to log the exceptions. By enabling the logger to log the uncaught exceptions, we can easily look at the stack trace and work out what went wrong Global Exception Mappings We have seen how we can handle action specific exception. We can set an exception globally which will apply to all the actions. For example, to catch the same NullPointerException exceptions, we could add <global-exception-mappings…> tag inside <package…> tag and its <result…> tag should be added inside the <action…> tag in struts.xml file as follows − <?xml version = “1.0” Encoding = “UTF-8”?> <!DOCTYPE struts PUBLIC “-//Apache Software Foundation//DTD Struts Configuration 2.0//EN” “http://struts.apache.org/dtds/struts-2.0.dtd”> <struts> <constant name = “struts.devMode” value = “true” /> <package name = “helloworld” extends = “struts-default”> <global-exception-mappings> <exception-mapping exception = “java.lang.NullPointerException” result = “error” /> </global-exception-mappings> <action name = “hello” class = “com.tutorialspoint.struts2.HelloWorldAction” method = “execute”> <result name = “success”>/HelloWorld.jsp</result> <result name = “error”>/Error.jsp</result> </action> </package> </struts> Print Page Previous Next Advertisements ”;
Struts2 – Data Tags
Struts 2 – Data Tags ”; Previous Next The Struts 2 data tags are primarily used to manipulate the data displayed on a page. Listed below are the important data tags: <Start here> The Action Tag This tag enables developers to call actions directly from a JSP page by specifying the action name and an optional namespace. The body content of the tag is used to render the results from the Action. Any result processor defined for this action in struts.xml will be ignored, unless the executeResult parameter is specified. <div>Tag to execute the action</div> <br /> <s:action name = “actionTagAction” executeresult = “true” /> <br /> <div>To invokes special method in action class</div> <br /> <s:action name = “actionTagAction!specialMethod” executeresult = “true” /> Check Detailed Example The Include Tag These include will be used to include a JSP file in another JSP page. <– First Syntax –> <s:include value = “myJsp.jsp” /> <– Second Syntax –> <s:include value = “myJsp.jsp”> <s:param name = “param1” value = “value2” /> <s:param name = “param2” value = “value2” /> </s:include> <– Third Syntax –> <s:include value = “myJsp.jsp”> <s:param name = “param1”>value1</s:param> <s:param name = “param2″>value2</s:param> </s:include> Check Detailed Example The Bean Tag These bean tag instantiates a class that conforms to the JavaBeans specification. This tag has a body which can contain a number of Param elements to set any mutator methods on that class. If the var attribute is set on the BeanTag, it will place the instantiated bean into the stack”s Context. <s:bean name = “org.apache.struts2.util.Counter” var = “counter”> <s:param name = “first” value = “20”/> <s:param name = “last” value = “25” /> </s:bean> Check Detailed Example The Date Tag These date tag will allow you to format a Date in a quick and easy way. You can specify a custom format (eg. “dd/MM/yyyy hh:mm”), you can generate easy readable notations (like “in 2 hours, 14 minutes”), or you can just fall back on a predefined format with key ”struts.date.format” in your properties file. <s:date name = “person.birthday” format = “dd/MM/yyyy” /> <s:date name = “person.birthday” format = “%{getText(”some.i18n.key”)}” /> <s:date name = “person.birthday” nice=”true” /> <s:date name = “person.birthday” /> Check Detailed Example The Param Tag These param tag can be used to parameterize other tags. This tag has the following two parameters. name (String) − the name of the parameter value (Object) − the value of the parameter <pre> <ui:component> <ui:param name = “key” value = “[0]”/> <ui:param name = “value” value = “[1]”/> <ui:param name = “context” value = “[2]”/> </ui:component> </pre> Check Detailed Example The Property Tag These property tag is used to get the property of a value, which will default to the top of the stack if none is specified. <s:push value = “myBean”> <!– Example 1: –> <s:property value = “myBeanProperty” /> <!– Example 2: –>TextUtils <s:property value = “myBeanProperty” default = “a default value” /> </s:push> Check Detailed Example The Push Tag These push tag is used to push value on stack for simplified usage. <s:push value = “user”> <s:propery value = “firstName” /> <s:propery value = “lastName” /> </s:push> Check Detailed Example The Set Tag These set tag assigns a value to a variable in a specified scope. It is useful when you wish to assign a variable to a complex expression and then simply reference that variable each time rather than the complex expression. The scopes available are application, session, request, page and action. <s:set name = “myenv” value = “environment.name”/> <s:property value = “myenv”/> Check Detailed Example The Text Tag These text tag is used to render a I18n text message. <!– First Example –> <s:i18n name = “struts.action.test.i18n.Shop”> <s:text name = “main.title”/> </s:i18n> <!– Second Example –> <s:text name = “main.title” /> <!– Third Examlpe –> <s:text name = “i18n.label.greetings”> <s:param >Mr Smith</s:param> </s:text> Check Detailed Example The URL Tag These url tag is used to create a URL. <– Example 1 –> <s:url value = “editGadget.action”> <s:param name = “id” value = “%{selected}” /> </s:url> <– Example 2 –> <s:url action = “editGadget”> <s:param name = “id” value = “%{selected}” /> </s:url> <– Example 3–> <s:url includeParams=”get”> <s:param name = “id” value = “%{”22”}” /> </s:url> Check Detailed Example Print Page Previous Next Advertisements ”;
Struts2 – Tiles
Struts 2 & Tiles Integration ”; Previous Next In this chapter, let us go through the steps involved in integrating the Tiles framework with Struts2. Apache Tiles is a templating framework built to simplify the development of web application user interfaces. First of all we need to download the tiles jar files from the Apache Tiles website. You need to add the following jar files to the project”s class path. tiles-api-x.y.z.jar tiles-compat-x.y.z.jar tiles-core-x.y.z.jar tiles-jsp-x.y.z.jar tiles-servlet-x.y.z.jar In addition to the above, we have to copy the following jar files from the struts2 download in your WEB-INF/lib. commons-beanutils-x.y.zjar commons-digester-x.y.jar struts2-tiles-plugin-x.y.z.jar Now let us setup the web.xml for the Struts-Tiles integration as given below. There are two important point to note here. First, we need to tell tiles, where to find tiles configuration file tiles.xml. In our case, it will be under /WEB-INF folder. Next we need to initiliaze the Tiles listener that comes with Struts2 download. <?xml version = “1.0” Encoding = “UTF-8”?> <web-app xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xmlns = “http://java.sun.com/xml/ns/javaee” xmlns:web = “http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd” xsi:schemaLocation = “http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd” id = “WebApp_ID” version = “2.5”> <display-name>Struts2Example15</display-name> <context-param> <param-name> org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG </param-name> <param-value> /WEB-INF/tiles.xml </param-value> </context-param> <listener> <listener-class> org.apache.struts2.tiles.StrutsTilesListener </listener-class> </listener> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> Next let us create tiles.xml under /WEB-INF folder with the following contents − <?xml version = “1.0” Encoding = “UTF-8” ?> <!DOCTYPE tiles-definitions PUBLIC “-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN” “http://tiles.apache.org/dtds/tiles-config_2_0.dtd”> <tiles-definitions> <definition name = “baseLayout” template=”/baseLayout.jsp”> <put-attribute name = “title” value = “Template”/> <put-attribute name = “banner” value = “/banner.jsp”/> <put-attribute name = “menu” value = “/menu.jsp”/> <put-attribute name = “body” value = “/body.jsp”/> <put-attribute name = “footer” value = “/footer.jsp”/> </definition> <definition name = “tiger” extends = “baseLayout”> <put-attribute name = “title” value = “Tiger”/> <put-attribute name = “body” value = “/tiger.jsp”/> </definition> <definition name = “lion” extends = “baseLayout”> <put-attribute name = “title” value = “Lion”/> <put-attribute name = “body” value = “/lion.jsp”/> </definition> </tiles-definitions> Next, we define a basic skeleton layout in the baseLayout.jsp. It has five reusable / overridable areas. Namely title, banner, menu, body and footer. We provide the default values for the baseLayout and then we create two customizations that extend from the default layout. The tiger layout is similar to the basic layout, except it uses the tiger.jsp as its body and the text “Tiger” as the title. Similarly, the lion layout is similar to the basic layout, except it uses the lion.jsp as its body and the text “Lion” as the title. Let us have a look at the individual jsp files. Following is the content of baseLayout.jsp file − <%@ taglib uri = “http://tiles.apache.org/tags-tiles” prefix = “tiles”%> <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”> <html> <head> <meta http-equiv=”Content-Type” content=”text/html; charset = UTF-8″> <title> <tiles:insertAttribute name = “title” ignore=”true” /> </title> </head> <body> <tiles:insertAttribute name = “banner” /><br/> <hr/> <tiles:insertAttribute name = “menu” /><br/> <hr/> <tiles:insertAttribute name = “body” /><br/> <hr/> <tiles:insertAttribute name = “footer” /><br/> </body> </html> Here, we just put together a basic HTML page that has the tiles attributes. We insert the tiles attributes in the places where we need them to be. Next, let us create a banner.jsp file with the following content − <img src=”http://www.tutorialspoint.com/images/tp-logo.gif”/> The menu.jsp file will have the following lines which are the links – to the TigerMenu.action and the LionMenu.action struts actions. <%@taglib uri = “/struts-tags” prefix = “s”%> <a href = “<s:url action = “tigerMenu”/>” Tiger</a><br> <a href = “<s:url action = “lionMenu”/>” Lion</a><br> The lion.jsp file will have following content − <img src=”http://upload.wikimedia.org/wikipedia/commons/d/d2/Lion.jpg”/> The lion The tiger.jsp file will have following content − <img src=”http://www.freewebs.com/tigerofdarts/tiger.jpg”/> The tiger Next, let us create the action class file MenuAction.java which contains the following − package com.tutorialspoint.struts2; import com.opensymphony.xwork2.ActionSupport; public class MenuAction extends ActionSupport { public String tiger() { return “tiger”; } public String lion() { return “lion”; } } This is a pretty straight forward class. We declared two methods tiger() and lion() that return tiger and lion as outcomes respectively. Let us put it all together in the struts.xml file − <!DOCTYPE struts PUBLIC “-//Apache Software Foundation//DTD Struts Configuration 2.0//EN” “http://struts.apache.org/dtds/struts-2.0.dtd”> <struts> <package name = “default” extends = “struts-default”> <result-types> <result-type name = “tiles” class=”org.apache.struts2.views.tiles.TilesResult” /> </result-types> <action name = “*Menu” method = “{1}” class = “com.tutorialspoint.struts2.MenuAction”> <result name = “tiger” type = “tiles”>tiger</result> <result name = “lion” type = “tiles”>lion</result> </action> </package> </struts> Let us check what we did in above file. First of all, we declared a new result type called “tiles” as we are now using tiles instead of plain jsp for the view technology. Struts2 has its support for the Tiles View result type, so we create the result type “tiles” to be of the “org.apache.struts2.view.tiles.TilesResult” class. Next, we want to say if the request is for /tigerMenu.action take the user to the tiger tiles page and if the request is for /lionMenu.action take the user to the lion tiles page. We achieve this using a bit of regular expression. In our action definition, we say anything that matches the pattern “*Menu” will be handled by this action. The matching method will be invoked in the MenuAction class. That is, tigerMenu.action will invoke tiger() and lionMenu.action will invoke lion(). We then need to map the outcome of the result to the appropriate tiles pages. Now right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat”s webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/tigerMenu.jsp. This will produce the following screen − Similarly, if you goto the lionMenu.action page, you will see the lion page which uses the same tiles layout. Print Page Previous Next Advertisements ”;
Struts2 – Localization
Struts2 – Localization, internationalization (i18n) ”; Previous Next Internationalization (i18n) is the process of planning and implementing products and services so that they can easily be adapted to specific local languages and cultures, a process called localization. The internationalization process is called translation or localization enablement. Internationalization is abbreviated i18n because the word starts with the letter “i” and ends with “n”, and there are 18 characters between the first i and the last n. Struts2 provides localization, i.e., internationalization (i18n) support through resource bundles, interceptors and tag libraries in the following places − The UI Tags Messages and Errors. Within action classes. Resource Bundles Struts2 uses resource bundles to provide multiple language and locale options to the users of the web application. You don”t need to worry about writing pages in different languages. All you have to do is to create a resource bundle for each language that you want. The resource bundles will contain titles, messages, and other text in the language of your user. Resource bundles are the file that contains the key/value pairs for the default language of your application. The simplest naming format for a resource file is − bundlename_language_country.properties Here, bundlename could be ActionClass, Interface, SuperClass, Model, Package, Global resource properties. Next part language_country represents the country locale for example, Spanish (Spain) locale is represented by es_ES, and English (United States) locale is represented by en_US etc. where you can skip country part which is optional. When you reference a message element by its key, Struts framework searches for a corresponding message bundle in the following order − ActionClass.properties Interface.properties SuperClass.properties model.properties package.properties struts.properties global.properties To develop your application in multiple languages, you should maintain multiple property files corresponding to those languages/locale and define all the content in terms of key/value pairs. For example, if you are going to develop your application for US English (Default), Spanish, and French, then you would have to create three properties files. Here I will use global.properties file only, you can also make use of different property files to segregate different type of messages. global.properties − By default English (United States) will be applied global_fr.properties − This will be used for Franch locale. global_es.properties − This will be used for Spanish locale. Access the messages There are several ways to access the message resources, including getText, the text tag, key attribute of UI tags, and the i18n tag. Let us see them in brief − To display i18n text, use a call to getText in the property tag, or any other tag, such as the UI tags as follows − <s:property value = “getText(”some.key”)” /> The text tag retrieves a message from the default resource bundle, i.e., struts.properties <s:text name = “some.key” /> The i18n tag pushes an arbitrary resource bundle on to the value stack. Other tags within the scope of the i18n tag can display messages from that resource bundle− <s:i18n name = “some.package.bundle”> <s:text name = “some.key” /> </s:i18n> The key attribute of most UI tags can be used to generate a message from a resource bundle − <s:textfield key = “some.key” name = “textfieldName”/> Localization Example Let us target to create index.jsp from the previous chapter in multiple languages. Same file would be written as follows − <%@ page language = “java” contentType = “text/html; charset = ISO-8859-1” pageEncoding = “ISO-8859-1″%> <%@ taglib prefix = “s” uri = “/struts-tags”%> <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”> <html> <head> <title>Employee Form with Multilingual Support</title> </head> <body> <h1><s:text name = “global.heading”/></h1> <s:url id = “indexEN” namespace=”/” action = “locale” > <s:param name = “request_locale” >en</s:param> </s:url> <s:url id = “indexES” namespace=”/” action = “locale” > <s:param name = “request_locale” >es</s:param> </s:url> <s:url id = “indexFR” namespace=”/” action = “locale” > <s:param name = “request_locale” >fr</s:param> </s:url> <s:a href=”%{indexEN}” >English</s:a> <s:a href=”%{indexES}” >Spanish</s:a> <s:a href=”%{indexFR}” >France</s:a> <s:form action = “empinfo” method = “post” namespace = “/”> <s:textfield name = “name” key = “global.name” size = “20” /> <s:textfield name = “age” key = “global.age” size = “20” /> <s:submit name = “submit” key = “global.submit” /> </s:form> </body> </html> We will create success.jsp file which will be invoked in case defined action returns SUCCESS. <%@ page language = “java” contentType = “text/html; charset = ISO-8859-1” pageEncoding = “ISO-8859-1″%> <%@ taglib prefix = “s” uri = “/struts-tags”%> <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”> <html> <head> <title>Success</title> </head> <body> <s:property value = “getText(”global.success”)” /> </body> </html> Here we would need to create the following two actions. (a) First action a to take care of Locale and display same index.jsp file with different language (b) Another action is to take care of submitting form itself. Both the actions will return SUCCESS, but we will take different actions based on return values because our purpose is different for both the actions Action to take care of Locale package com.tutorialspoint.struts2; import com.opensymphony.xwork2.ActionSupport; public class Locale extends ActionSupport { public String execute() { return SUCCESS; } } Action To Submit The Form package com.tutorialspoint.struts2; import com.opensymphony.xwork2.ActionSupport; public class Employee extends ActionSupport{ private String name; private int age; public String execute() { return SUCCESS; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } Now let us create the following three global.properties files and put the in CLASSPATH − global.properties global.name = Name global.age = Age global.submit = Submit global.heading = Select Locale global.success = Successfully authenticated global_fr.properties global.name = Nom d”utilisateur global.age = l”âge global.submit = Soumettre des global.heading = Sé lectionnez Local global.success = Authentifi é avec succès global_es.properties global.name = Nombre de usuario global.age = Edad global.submit = Presentar global.heading = seleccionar la configuracion regional global.success = Autenticado correctamente We will create our struts.xml with two actions as follows − <?xml version = “1.0” Encoding = “UTF-8”?> <!DOCTYPE struts PUBLIC “-//Apache Software Foundation//DTD Struts Configuration 2.0//EN” “http://struts.apache.org/dtds/struts-2.0.dtd”> <struts> <constant name
Struts2 – Environment Setup
Struts 2 – Environment Setup ”; Previous Next Our first task is to get a minimal Struts 2 application running. This chapter will guide you on how to prepare a development environment to start your work with Struts 2. I assume that you already have JDK (5+), Tomcat and Eclipse installed on your machine. If you do not have these components installed, then follow the given steps on fast track − Step 1 – Setup Java Development Kit (JDK) You can download the latest version of SDK from Oracle”s Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally, set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and installed the SDK in C:jdk1.5.0_20, you should be inputting the following line in your C:autoexec.bat file. set PATH = C:jdk1.5.0_20bin;%PATH% set JAVA_HOME = C:jdk1.5.0_20 Alternatively, on Windows NT/2000/XP − You can right-click on My Computer, Select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button. On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use the C shell, you would put the following into your .cshrc file. On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use the C shell, you would put the following into your .cshrc file. setenv PATH /usr/local/jdk1.5.0_20/bin:$PATH setenv JAVA_HOME /usr/local/jdk1.5.0_20 Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java, otherwise do proper setup as per the given document of IDE. Step 2 – Setup Apache Tomcat You can download the latest version of Tomcat from https://tomcat.apache.org/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:apache-tomcat-6.0.33 on windows, or /usr/local/apachetomcat-6.0.33 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations. You can start Tomcat by executing the following commands on windows machine, or you can simply double click on startup.bat %CATALINA_HOME%binstartup.bat or C:apache-tomcat-6.0.33binstartup.bat Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine − $CATALINA_HOME/bin/startup.sh or /usr/local/apache-tomcat-6.0.33/bin/startup.sh After a successful startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine, then it should display the following result − Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat website: https://tomcat.apache.org/ Tomcat can be stopped by executing the following commands on windows machine − %CATALINA_HOME%binshutdown or C:apache-tomcat-5.5.29binshutdown Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine − $CATALINA_HOME/bin/shutdown.sh or /usr/local/apache-tomcat-5.5.29/bin/shutdown.sh Step 3 – Setup Eclipse (IDE) All the examples in this tutorial are written using Eclipse IDE. I suggest that, you have the latest version of Eclipse installed in your machine. To install Eclipse Download the latest Eclipse binaries from https://www.eclipse.org/downloads/. Once you download the installation, unpack the binary distribution into a convenient location. For example in C:eclipse on windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately. Eclipse can be started by executing the following commands on windows machine, or you can simply double click on eclipse.exe %C:eclipseeclipse.exe Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine − $/usr/local/eclipse/eclipse After a successful startup, if everything is fine, it should display the following result − Step 4 – Setup Struts2 Libraries Now if everything is fine, then you can proceed to setup your Struts2 framemwork. Following are the simple steps to download and install Struts2 on your machine. Make a choice whether you want to install Struts2 on Windows, or Unix and then proceed to the next step to download .zip file for windows and .tz file for Unix. Download the latest version of Struts2 binaries from https://struts.apache.org/download.cgi. At the time of writing this tutorial, I downloaded struts-2.0.14-all.zip and when you unzip the downloaded file it will give you directory structure inside C:struts-2.2.3 as follows. Second step is to extract the zip file in any location, I downloaded & extracted struts-2.2.3-all.zip in c: folder on my Windows 7 machine so that I have all the jar files into C:struts-2.2.3lib. Make sure you set your CLASSPATH variable properly otherwise you will face problem while running your application. Print Page Previous Next Advertisements ”;
Struts2 – File Uploads
Struts 2 – File Uploads ”; Previous Next The Struts 2 framework provides built-in support for processing file upload using “Form-based File Upload in HTML”. When a file is uploaded, it will typically be stored in a temporary directory and they should be processed or moved by your Action class to a permanent directory to ensure the data is not lost. Note − Servers may have a security policy in place that prohibits you from writing to directories other than the temporary directory and the directories that belong to your web application. File uploading in Struts is possible through a pre-defined interceptor called FileUpload interceptor which is available through the org.apache.struts2.interceptor.FileUploadInterceptor class and included as part of thedefaultStack. Still you can use that in your struts.xml to set various paramters as we will see below. Create View Files Let us start with creating our view which will be required to browse and upload a selected file. So let us create an index.jsp with plain HTML upload form that allows the user to upload a file − <%@ page language = “java” contentType = “text/html; charset = ISO-8859-1” pageEncoding = “ISO-8859-1″%> <%@ taglib prefix = “s” uri = “/struts-tags”%> <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”> <html> <head> <title>File Upload</title> </head> <body> <form action = “upload” method = “post” enctype = “multipart/form-data”> <label for = “myFile”>Upload your file</label> <input type = “file” name = “myFile” /> <input type = “submit” value = “Upload”/> </form> </body> </html> There is couple of points worth noting in the above example. First, the form”s enctype is set to multipart/form-data. This should be set so that file uploads are handled successfully by the file upload interceptor. The next point noting is the form”s action method upload and the name of the file upload field – which is myFile. We need this information to create the action method and the struts configuration. Next, let us create a simple jsp file success.jsp to display the outcome of our file upload in case it becomes success. <%@ page contentType = “text/html; charset = UTF-8” %> <%@ taglib prefix = “s” uri = “/struts-tags” %> <html> <head> <title>File Upload Success</title> </head> <body> You have successfully uploaded <s:property value = “myFileFileName”/> </body> </html> Following will be the result file error.jsp in case there is some error in uploading the file − <%@ page contentType = “text/html; charset = UTF-8” %> <%@ taglib prefix = “s” uri = “/struts-tags” %> <html> <head> <title>File Upload Error</title> </head> <body> There has been an error in uploading the file. </body> </html> Create Action Class Next, let us create a Java class called uploadFile.java which will take care of uploading file and storing that file at a secure location − package com.tutorialspoint.struts2; import java.io.File; import org.apache.commons.io.FileUtils; import java.io.IOException; import com.opensymphony.xwork2.ActionSupport; public class uploadFile extends ActionSupport { private File myFile; private String myFileContentType; private String myFileFileName; private String destPath; public String execute() { /* Copy file to a safe location */ destPath = “C:/apache-tomcat-6.0.33/work/”; try { System.out.println(“Src File name: ” + myFile); System.out.println(“Dst File name: ” + myFileFileName); File destFile = new File(destPath, myFileFileName); FileUtils.copyFile(myFile, destFile); } catch(IOException e) { e.printStackTrace(); return ERROR; } return SUCCESS; } public File getMyFile() { return myFile; } public void setMyFile(File myFile) { this.myFile = myFile; } public String getMyFileContentType() { return myFileContentType; } public void setMyFileContentType(String myFileContentType) { this.myFileContentType = myFileContentType; } public String getMyFileFileName() { return myFileFileName; } public void setMyFileFileName(String myFileFileName) { this.myFileFileName = myFileFileName; } } The uploadFile.java is a very simple class. The important thing to note is that the FileUpload interceptor along with the Parameters Interceptor does all the heavy lifting for us. The FileUpload interceptor makes three parameters available for you by default. They are named in the following pattern − [your file name parameter] − This is the actual file that the user has uploaded. In this example it will be “myFile” [your file name parameter]ContentType − This is the content type of the file that was uploaded. In this example it will be “myFileContentType” [your file name parameter]FileName − This is the name of the file that was uploaded. In this example it will be “myFileFileName” The three parameters are available for us, thanks to the Struts Interceptors. All we have to do is to create three parameters with the correct names in our Action class and automatically these variables are auto wired for us. So, in the above example, we have three parameters and an action method that simply returns “success” if everything goes fine otherwise it returns “error”. Configuration Files Following are the Struts2 configuration properties that control file uploading process − Sr.No Properties & Description 1 struts.multipart.maxSize The maximum size (in bytes) of a file to be accepted as a file upload. Default is 250M. 2 struts.multipart.parser The library used to upload the multipart form. By default is jakarta 3 struts.multipart.saveDir The location to store the temporary file. By default is javax.servlet.context.tempdir. In order to change any of these settings, you can use constant tag in your applications struts.xml file, as I did to change the maximum size of a file to be uploaded. Let us have our struts.xml as follows − <?xml version = “1.0” Encoding = “UTF-8”?> <!DOCTYPE struts PUBLIC “-//Apache Software Foundation//DTD Struts Configuration 2.0//EN” “http://struts.apache.org/dtds/struts-2.0.dtd”> <struts> <constant name = “struts.devMode” value = “true” /> <constant name = “struts.multipart.maxSize” value = “1000000” /> <package name = “helloworld” extends = “struts-default”> <action name = “upload” class = “com.tutorialspoint.struts2.uploadFile”> <result name = “success”>/success.jsp</result> <result name = “error”>/error.jsp</result> </action> </package> </struts> Since, FileUpload interceptor is a part of the default Stack of interceptors, we do not need to configure it explicity. But, you can add <interceptor-ref> tag inside <action>. The fileUpload interceptor takes two parameters (a) maximumSize and (b) allowedTypes. The maximumSize parameter sets the maximum file size allowed (the default is approximately 2MB). The allowedTypes parameter is a comma-separated list of accepted content (MIME) types as shown below − <action name = “upload”
Basic MVC Architecture ”; Previous Next Model View Controller or MVC as it is popularly called, is a software design pattern for developing web applications. A Model View Controller pattern is made up of the following three parts − Model − The lowest level of the pattern which is responsible for maintaining data. View − This is responsible for displaying all or a portion of the data to the user. Controller − Software Code that controls the interactions between the Model and View. MVC is popular as it isolates the application logic from the user interface layer and supports separation of concerns. Here the Controller receives all requests for the application and then works with the Model to prepare any data needed by the View. The View then uses the data prepared by the Controller to generate a final presentable response. The MVC abstraction can be graphically represented as follows. The Model The model is responsible for managing the data of the application. It responds to the request from the view and it also responds to instructions from the controller to update itself. The View It means presentation of data in a particular format, triggered by a controller”s decision to present the data. They are script-based templating systems like JSP, ASP, PHP and very easy to integrate with AJAX technology. The Controller The controller is responsible for responding to the user input and perform interactions on the data model objects. The controller receives the input, it validates the input and then performs the business operation that modifies the state of the data model. Struts2 is a MVC based framework. In the coming chapters, let us see how we can use the MVC methodology within Struts2. Print Page Previous Next Advertisements ”;
Struts2 – Database Access
Struts 2 – Database Access ”; Previous Next This chapter will teach you how to access a database using Struts 2 in simple steps. Struts is a MVC framework and not a database framework but it provides excellent support for JPA/Hibernate integration. We shall look at the hibernate integration in a later chapter, but in this chapter we shall use plain old JDBC to access the database. The first step in this chapter is to setup and prime our database. I am using MySQL as my database for this example. I have MySQL installed on my machine and I have created a new database called “struts_tutorial”. I have created a table called login and populated it with some values. Below is the script I used to create and populate the table. My MYSQL database has the default username “root” and “root123” password CREATE TABLE `struts_tutorial`.`login` ( `user` VARCHAR( 10 ) NOT NULL , `password` VARCHAR( 10 ) NOT NULL , `name` VARCHAR( 20 ) NOT NULL , PRIMARY KEY ( `user` ) ) ENGINE = InnoDB; INSERT INTO `struts_tutorial`.`login` (`user`, `password`, `name`) VALUES (”scott”, ”navy”, ”Scott Burgemott”); Next step is to download the MySQL Connector jar file and placing this file in the WEB-INFlib folder of your project. After we have done this, we are now ready to create the action class. Create Action The action class has the properties corresponding to the columns in the database table. We have user, password and name as String attributes. In the action method, we use the user and password parameters to check if the user exists, if so, we display the user name in the next screen. If the user has entered wrong information, we send them to the login screen again. Following is the content of LoginAction.java file − package com.tutorialspoint.struts2; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import com.opensymphony.xwork2.ActionSupport; public class LoginAction extends ActionSupport { private String user; private String password; private String name; public String execute() { String ret = ERROR; Connection conn = null; try { String URL = “jdbc:mysql://localhost/struts_tutorial”; Class.forName(“com.mysql.jdbc.Driver”); conn = DriverManager.getConnection(URL, “root”, “root123”); String sql = “SELECT name FROM login WHERE”; sql+=” user = ? AND password = ?”; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, user); ps.setString(2, password); ResultSet rs = ps.executeQuery(); while (rs.next()) { name = rs.getString(1); ret = SUCCESS; } } catch (Exception e) { ret = ERROR; } finally { if (conn != null) { try { conn.close(); } catch (Exception e) { } } } return ret; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Create Main Page Now, let us create a JSP file index.jsp to collect the username and password. This username and password will be checked against the database. <%@ page language = “java” contentType = “text/html; charset = ISO-8859-1” pageEncoding = “ISO-8859-1″%> <%@ taglib prefix = “s” uri = “/struts-tags”%> <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”> <html> <head> <title>Login</title> </head> <body> <form action = “loginaction” method = “post”> User:<br/><input type = “text” name = “user”/><br/> Password:<br/><input type = “password” name = “password”/><br/> <input type = “submit” value = “Login”/> </form> </body> </html> Create Views Now let us create success.jsp file which will be invoked in case action returns SUCCESS, but we will have another view file in case of an ERROR is returned from the action. <%@ page contentType = “text/html; charset = UTF-8” %> <%@ taglib prefix = “s” uri = “/struts-tags” %> <html> <head> <title>Successful Login</title> </head> <body> Hello World, <s:property value = “name”/> </body> </html> Following will be the view file error.jsp in case of an ERROR is returned from the action. <%@ page contentType = “text/html; charset = UTF-8” %> <%@ taglib prefix = “s” uri = “/struts-tags” %> <html> <head> <title>Invalid User Name or Password</title> </head> <body> Wrong user name or password provided. </body> </html> Configuration Files Finally, let us put everything together using the struts.xml configuration file as follows − <?xml version = “1.0” Encoding = “UTF-8”?> <!DOCTYPE struts PUBLIC “-//Apache Software Foundation//DTD Struts Configuration 2.0//EN” “http://struts.apache.org/dtds/struts-2.0.dtd”> <struts> <constant name = “struts.devMode” value = “true” /> <package name = “helloworld” extends = “struts-default”> <action name = “loginaction” class = “com.tutorialspoint.struts2.LoginAction” method = “execute”> <result name = “success”>/success.jsp</result> <result name = “error”>/error.jsp</result> </action> </package> </struts> Following is the content of web.xml file − <?xml version = “1.0” Encoding = “UTF-8”?> <web-app xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xmlns = “http://java.sun.com/xml/ns/javaee” xmlns:web = “http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd” xsi:schemaLocation = “http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd” id = “WebApp_ID” version = “3.0”> <display-name>Struts 2</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> Now, right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat”s webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the following screen − Enter a wrong user name and password. You should see the next page. Now enter scott as user name and navy as password. You should see the next page. Print Page Previous Next Advertisements ”;