Struts2: Convention Plugin Simple Example

DOWNLOAD Apache Struts2 is a java based web framework that encourages developers to adopt to Model-View-Controller architecture....



Apache Struts2 is a java based web framework that encourages developers to adopt to Model-View-Controller architecture. The goal of Struts is to separate the application logic from the user interface that will help improve maintenance of the project. The web developer is responsible for creating the model (core logic) and for creating a central configuration file (struts.xml) that will bind together the model, view and the controller. One can also go for convention based programming and name the action classes (controllers) and the views (JSP) according to the standard conventions    so that the program will automatically recognize the right one to call, instead of using the traditional configuration file (struts.xml) approach.

In this post, I am going to explain the step-by-step process of creating a very simple hello world example in struts framework and going to use struts convention plugin instead of struts.xml file. If you are new to struts I recommend you to read this post on how to create a simple struts application using struts.xml file. This will help you understand the use of conventions in struts application. 

These are the basic convention rules one should know before creating a struts application using conventions,

  1. By default, the Convention plugin assumes that all of the results(JSP's, XSLT or vm files) are stored in WEB-INF/content folderThis can be changed by setting the property struts.convention.result.path in the Struts properties file to the new location.
  2. First the Convention plugin finds packages named strutsstruts2action or actions. Any packages that match those names are considered the root packages for the Convention plugin.
  3. Next, the plugin looks at all of the classes in those packages as well as sub-packages and determines if the classes implement com.opensymphony.xwork2.Action or if their name ends with Action (i.e. FooAction).
  4.  The plugin determines the URL of the resource using the class name. It first removes the word Action from the end of the class name and then converts camel case names to dashes. For example, for the Action class named HelloWorldAction.java, the plugin will look for url /hello-world. 
  5. You can tell the Convention plugin to ignore certain packages using the property struts.convention.exclude.packages. You can also tell the plugin to use different strings to locate root packages using the property struts.convention.package.locators. Finally, you can tell the plugin to search specific root packages using the property struts.convention.action.packages.
  6.  For results or views(JSP's, XSLT or vm files), the first part of the file name must be the same as the URL of the action and the result code can be added to the last part of the name if required. This is the convention that the plugin uses to determine which results to render. For example, if the url is hello-world, then the result should be named like hello-world.jsp and if the action class returns "error" instead of success, then the plugin will look for a jsp page named as hello-world-error.jsp.
Let's get started by downloading struts2 framework,

1. Download the latest release of struts2 framework from here.

2. Create a dynamic web project in Eclipse, and add the following jars to WEB-INF/lib folder from the download. Please note that the 'x.x' in the jar name denotes the version of the jar.
  • asm-x.x.jar
  • asm-commons-x.x.jar
  • commons-fileupload-x.x.jar
  • commons-io-x.x.x.jar
  • commons-langs-x.x.x.jar
  • commons.lang3-x.x.jar
  • freemarker-x.x.jar
  • javassist-x.x-GA.jar
  • ognl.jar
  • struts2-convention-plugin-x.x.x.jar
  • struts2-core-x.x.x.jar
  • xwork-core-x.x.x.jar
3. Open the web.xml file and add the following filter and filter mapping to it,

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

4. Now let us create a package under the src package that ends with the term 'actions'. In this example I have created a package called com.programmingfree.actions.

5. Create a class in the com.programmingfree.actions and name it as "HelloAction.java". Please use the same name for every component in this application since conventions are all about how we name each and every part of this application.

6. Copy and paste the below code in the HelloAction class you just created. 


package com.programmingfree.actions;

import com.opensymphony.xwork2.Action;


public class HelloAction implements Action {

 private String greeting;
 @Override
 public String execute() throws Exception {
  setGreeting("Hello World - Struts2 Example by Priya!!");
  return SUCCESS;
 }
 public void setGreeting(String greeting) {
  this.greeting = greeting;
 }
 public String getGreeting() {
  return greeting;
 }

}

In the above code, we have implemented the Action interface from com.opensymphony.xwork2.Action package. Here we are overriding execute() method form the Action interface, which will be executed automatically whenever this action class is called. This class just sets or gets the value of a string field named as "greeting".


7. Now let us create a result or the view for this action class. Remember rule no.1 explained in the beginning of this post - By default, the Convention plugin assumes that all of the results(JSP's, XSLT or vm files) are stored in WEB-INF/content folder. So  first create a folder named content under the WEB-INF directory. Then add a new JSP file to that folder and name it as 'hello.jsp'.



8. Copy and paste the below code in the hello.jsp 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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Struts Introduction</title>
</head>
<body>
<h1><s:property value="greeting"/></h1>
</body>
</html>


Note in the above code, we have used struts tag library to display the string property that we created in HelloAction.java class. There are a set of tags struts provides you to display the response from the action class and to control the flow of page execution.


9. The last step is to start Tomcat Server, then hit the url 'http://localhost:8080/SimpleStrutsApplication/hello'(replace SimpleStrutsApplication with your project name) in the browser and verify the output. The url value to be used here is 'hello' since we named our JSP page as 'hello.jsp' and action class as 'HelloAction.java'. The program will search for hello.jsp and to render the content of the jsp it will search for the action class starting with the term 'Hello' and ending with the term 'Action'. The output of the program is shown below,




For better understanding download the source code of the above example (use download button at the beginning of this article) and run it yourself with small alterations to the code,

Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts.Thanks for reading!!

Subscribe to GET LATEST ARTICLES!


Related

Struts2 2231175560496901078

Post a Comment

emo-but-icon

SUBSCRIBE


item