Struts 2 and Hibernate Integration ”; Previous Next Hibernate is a high-performance Object/Relational persistence and query service which is licensed under the open source GNU Lesser General Public License (LGPL) and is free to download. In this chapter. we are going to learn how to achieve Struts 2 integration with Hibernate. If you are not familiar with Hibernate, then you can check our Hibernate tutorial. Database Setup For this tutorial, I am going to use the “struts2_tutorial” MySQL database. I connect to this database on my machine using the username “root” and no password. First of all, you need to run the following script. This script creates a new table called student and creates few records in this table − CREATE TABLE IF NOT EXISTS `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(40) NOT NULL, `last_name` varchar(40) NOT NULL, `marks` int(11) NOT NULL, PRIMARY KEY (`id`) ); — — Dumping data for table `student` — INSERT INTO `student` (`id`, `first_name`, `last_name`, `marks`) VALUES(1, ”George”, ”Kane”, 20); INSERT INTO `student` (`id`, `first_name`, `last_name`, `marks`) VALUES(2, ”Melissa”, ”Michael”, 91); INSERT INTO `student` (`id`, `first_name`, `last_name`, `marks`) VALUES(3, ”Jessica”, ”Drake”, 21); Hibernate Configuration Next let us create the hibernate.cfg.xml which is the hibernate”s configuration file. <?xml version = ”1.0” encoding = ”utf-8”?> <!DOCTYPE hibernate-configuration PUBLIC “-//Hibernate/Hibernate Configuration DTD//EN” “http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”> <hibernate-configuration> <session-factory> <property name = “hibernate.connection.driver_class”>c om.mysql.jdbc.Driver </property> <property name = “hibernate.connection.url”> jdbc:mysql://www.tutorialspoint.com/struts_tutorial </property> <property name = “hibernate.connection.username”>root</property> <property name = “hibernate.connection.password”></property> <property name = “hibernate.connection.pool_size”>10</property> <property name = “show_sql”>true</property> <property name = “dialect”> org.hibernate.dialect.MySQLDialect </property> <property name = “hibernate.hbm2ddl.auto”>update</property> <mapping class = “com.tutorialspoint.hibernate.Student” /> </session-factory> </hibernate-configuration> Let us go through the hibernate config file. First, we declared that we are using MySQL driver. Then we declared the jdbc url for connecting to the database. Then we declared the connection”s username, password and pool size. We also indicated that we would like to see the SQL in the log file by turning on “show_sql” to true. Please go through the hibernate tutorial to understand what these properties mean. Finally, we set the mapping class to com.tutorialspoint.hibernate.Student which we will create in this chapter. Envrionment Setup Next you need a whole lot of jars for this project. Attached is a screenshot of the complete list of JAR files required − Most of the JAR files can be obtained as part of your struts distribution. If you have an application server such as glassfish, websphere or jboss installed, then you can get the majority of the remaining jar files from the appserver”s lib folder. If not you can download the files individually − Hibernate jar files − Hibernate.org Struts hibernate plugin − Struts hibernate plugin JTA files − JTA files Dom4j files − Dom4j log4j files − log4j Rest of the files, you should be able to get from your Struts2 distribution. Hibernate Classes Let us now create required java classes for the hibernate integration. Following is the content of Student.java − package com.tutorialspoint.hibernate; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = “student”) public class Student { @Id @GeneratedValue private int id; @Column(name = “last_name”) private String lastName; @Column(name = “first_name”) private String firstName; private int marks; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public int getMarks() { return marks; } public void setMarks(int marks) { this.marks = marks; } } This is a POJO class that represents the student table as per Hibernate specification. It has properties id, firstName and lastName which correspond to the column names of the student table. Next let us create StudentDAO.java file as follows − package com.tutorialspoint.hibernate; import java.util.ArrayList; import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; import com.googlecode.s2hibernate.struts2.plugin. annotations.SessionTarget; import com.googlecode.s2hibernate.struts2.plugin. annotations.TransactionTarget; public class StudentDAO { @SessionTarget Session session; @TransactionTarget Transaction transaction; @SuppressWarnings(“unchecked”) public List<Student> getStudents() { List<Student> students = new ArrayList<Student>(); try { students = session.createQuery(“from Student”).list(); } catch(Exception e) { e.printStackTrace(); } return students; } public void addStudent(Student student) { session.save(student); } } The StudentDAO class is the data access layer for the Student class. It has methods to list all students and then to save a new student record. Action Class Following file AddStudentAction.java defines our action class. We have two action methods here – execute() and listStudents(). The execute() method is used to add the new student record. We use the dao”s save() method to achieve this. The other method, listStudents() is used to list the students. We use the dao”s list method to get the list of all students. package com.tutorialspoint.struts2; import java.util.ArrayList; import java.util.List; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.tutorialspoint.hibernate.Student; import com.tutorialspoint.hibernate.StudentDAO; public class AddStudentAction extends ActionSupport implements ModelDriven<Student> { Student student = new Student(); List<Student> students = new ArrayList<Student>(); StudentDAO dao = new StudentDAO(); @Override public Student getModel() { return student; } public String execute() { dao.addStudent(student); return “success”; } public String listStudents() { students = dao.getStudents(); return “success”; } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } public List<Student> getStudents() { return students; } public void setStudents(List<Student> students) { this.students = students; } } You will notice that we are implementing the ModelDriven interface. This is used when your action class is dealing with a concrete model class (such as Student) as opposed to individual properties (such as firstName, lastName). The ModelAware interface requires you to implement a method to return the model. In our case we are returning the “student” object. Create View Files Let us now create the student.jsp view file with the following content − <%@ 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 = “addStudent”> <s:textfield name = “firstName” label = “First Name”/> <s:textfield name = “lastName” label = “Last Name”/> <s:textfield name
Category: struts 2
Struts2 – Examples
Struts 2 – Hello World Example ”; Previous Next As you have already learnt from the Struts 2 architecture, when you click on a hyperlink or submit an HTML form in a Struts 2 web-application, the input is collected by the Controller which is sent to a Java class called Actions. After the Action is executed, a result selects a resource to render the response. The resource is generally a JSP, but it can also be a PDF file, an Excel spreadsheet, or a Java applet window. Assuming that you already have built your development environment. Now, let us proceed for building our first Hello World Struts2 project. The aim of this project is to build a web application that collects the user”s name and displays “Hello World” followed by the user name. We would have to create following four components for any Struts 2 project − Sr.No Components & Description 1 Action Create an action class which will contain complete business logic and control the interaction between the user, the model, and the view. 2 Interceptors Create interceptors if required, or use existing interceptors. This is part of Controller. 3 View Create a JSPs to interact with the user to take input and to present the final messages. 4 Configuration Files Create configuration files to couple the Action, View and Controllers. These files are struts.xml, web.xml, struts.properties. I am going to use Eclipse IDE, so that all the required components will be created under a Dynamic Web Project. Let us now start with creating Dynamic Web Project. Create a Dynamic Web Project Start your Eclipse and then go with File > New > Dynamic Web Project and enter project name as HelloWorldStruts2 and set rest of the options as given in the following screen − Select all the default options in the next screens and finally check Generate Web.xml deployment descriptor option. This will create a dynamic web project for you in Eclipse. Now go with Windows > Show View > Project Explorer, and you will see your project window something as below − Now copy following files from struts 2 lib folder C:struts-2.2.3lib to our project”s WEB-INFlib folder. To do this, you can simply drag and drop all the following files into WEB-INFlib folder. commons-fileupload-x.y.z.jar commons-io-x.y.z.jar commons-lang-x.y.jar commons-logging-x.y.z.jar commons-logging-api-x.y.jar freemarker-x.y.z.jar javassist-.xy.z.GA ognl-x.y.z.jar struts2-core-x.y.z.jar xwork-core.x.y.z.jar Create Action Class Action class is the key to Struts 2 application and we implement most of the business logic in action class. So let us create a java file HelloWorldAction.java under Java Resources > src with a package name com.tutorialspoint.struts2 with the contents given below. The Action class responds to a user action when user clicks a URL. One or more of the Action class”s methods are executed and a String result is returned. Based on the value of the result, a specific JSP page is rendered. package com.tutorialspoint.struts2; public class HelloWorldAction { private String name; public String execute() throws Exception { return “success”; } public String getName() { return name; } public void setName(String name) { this.name = name; } } This is a very simple class with one property called “name”. We have standard getters and setter methods for the “name” property and an execute method that returns the string “success”. The Struts 2 framework will create an object of the HelloWorldAction class and call the executed method in response to a user”s action. You put your business logic inside this method which finally returns the String constant. In other words, for each URL, you would have to implement one action class and either you can use that class name directly as your action name or you can map to some other name using struts.xml file as shown below. Create a View We need a JSP to present the final message, this page will be called by Struts 2 framework when a predefined action will happen and this mapping will be defined in struts.xml file. So let us create the below jsp file HelloWorld.jsp in the WebContent folder in your eclipse project. To do this, right click on the WebContent folder in the project explorer and select New >JSP File. <%@ 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> The taglib directive tells the Servlet container that this page will be using the Struts 2 tags and that these tags will be preceded by s. The s:property tag displays the value of action class property “name> which is returned by the method getName() of the HelloWorldAction class. Create Main Page We also need to create index.jsp in the WebContent folder. This file will serve as the initial action URL where a user can click to tell the Struts 2 framework to call a defined method of the HelloWorldAction class and render the HelloWorld.jsp view. <%@ 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> The hello action defined in the above view file will be mapped to the HelloWorldAction class and its execute method using struts.xml file. When a user clicks on the Submit button it will cause the Struts 2 framework to run the execute method defined in the HelloWorldAction class and based on the returned value of the method, an appropriate view will be selected and rendered as a response. Configuration Files We need a mapping to tie the URL, the HelloWorldAction class (Model), and the HelloWorld.jsp (the view) together. The mapping tells the Struts 2 framework which class will respond to the user”s action (the URL), which method of that class will
Struts2 Questions and Answers ”; Previous Next Struts2 Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations. SN Question/Answers Type 1 Struts2 Interview Questions This section provides a huge collection of Struts2 Interview Questions with their answers hidden in a box to challenge you to have a go at them before discovering the correct answer. 2 Struts2 Online Quiz This section provides a great collection of Struts2 Multiple Choice Questions (MCQs) on a single page along with their correct answers and explanation. If you select the right option, it turns green; else red. 3 Struts2 Online Test If you are preparing to appear for a Java and Struts2 Framework related certification exam, then this section is a must for you. This section simulates a real online test along with a given timer which challenges you to complete the test within a given time-frame. Finally you can check your overall test score and how you fared among millions of other candidates who attended this online test. 4 Struts2 Mock Test This section provides various mock tests that you can download at your local machine and solve offline. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself. Print Page Previous Next Advertisements ”;
Struts2 – Validations
Struts 2 – Validations Framework ”; Previous Next In this chapter, we shall look deeper into Struts validation framework. At the Struts core, we have the validation framework that assists the application to run the rules to perform validation before the action method is executed. Client side validation is usually achieved using Javascript. However, one should not rely upon client side validation alone. The best practices suggest that the validation should be introduced at all levels of your application framework. Now let us look at two ways of adding validation to our Struts project. Here, we will take an example of an Employee whose name and age should be captured using a simple page, and we will put these two validations to make sure that the user always enters a name and age which should be in a range between 28 and 65. Let us start with the main JSP page of the example. Create Main Page Let us write main page JSP file index.jsp, which will be used to collect Employee related information mentioned above. <%@ 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</title> </head> <body> <s:form action = “empinfo” method = “post”> <s:textfield name = “name” label = “Name” size = “20” /> <s:textfield name = “age” label = “Age” size = “20” /> <s:submit name = “submit” label = “Submit” align=”center” /> </s:form> </body> </html> The index.jsp makes use of Struts tag, which we have not covered yet, but we will study them in tags related chapters. But for now, just assume that the s:textfield tag prints a input field, and the s:submit prints a submit button. We have used label property for each tag which creates label for each tag. Create Views We will use JSP file success.jsp 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> Employee Information is captured successfully. </body> </html> Create Action So let us define a small action class Employee, and then add a method called validate() as shown below in Employee.java file. Make sure that your action class extends the ActionSupport class, otherwise your validate method will not be executed. 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; } public void validate() { if (name == null || name.trim().equals(“”)) { addFieldError(“name”,”The name is required”); } if (age < 28 || age > 65) { addFieldError(“age”,”Age must be in between 28 and 65″); } } } As shown in the above example, the validation method checks whether the ”Name” field has a value or not. If no value has been supplied, we add a field error for the ”Name” field with a custom error message. Secondly, we check if entered value for ”Age” field is in between 28 and 65 or not, if this condition does not meet we add an error above the validated field. 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 = “empinfo” class = “com.tutorialspoint.struts2.Employee” method = “execute”> <result name = “input”>/index.jsp</result> <result name = “success”>/success.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 − Now do not enter any required information, just click on Submit button. You will see the following result − Enter the required information but enter a wrong From field, let us say name as “test” and age as 30, and finally click on Submit button. You will see the following result − How this Validation Works? When the user presses the submit button, Struts 2 will automatically execute the validate method and if any of the “if” statements listed inside the method are true, Struts 2 will call its addFieldError method. If any errors have been added, then Struts 2 will not proceed to call the execute method. Rather the Struts 2 framework will return input as the result of calling the action. Hence, when validation fails and Struts 2 returns input, the Struts 2 framework will redisplay the index.jsp file. Since, we used Struts 2 form tags, Struts 2 will automatically add the error messages just above the form filed. These error messages are the ones we specified in the addFieldError method call. The addFieldError method takes two arguments. The first, is the form field name to which the error applies and the second, is the error message to display above that form field. addFieldError(“name”,”The name is required”); To handle the return value of input we need to add the following result to our action node in struts.xml. <result name = “input”>/index.jsp</result> XML Based Validation The second method of doing validation is by placing an xml file next to the action class. Struts2 XML based validation provides more
Struts2 – Spring
Struts 2 & Spring Integration ”; Previous Next Spring is a popular web framework that provides easy integration with lots of common web tasks. So the question is, why do we need Spring when we have Struts2? Well, Spring is more than a MVC framework – it offers many other goodies which are not available in Struts. For example: dependency injection that can be useful to any framework. In this chapter, we will go through a simple example to see how to integrate Spring and Struts2 together. First of all, you need to add the following files to the project”s build path from Spring installation. You can download and install latest version of Spring Framework from https://www.springsource.org/download org.springframework.asm-x.y.z.M(a).jar org.springframework.beans-x.y.z.M(a).jar org.springframework.context-x.y.z.M(a).jar org.springframework.core-x.y.z.M(a).jar org.springframework.expression-x.y.z.M(a).jar org.springframework.web-x.y.z.M(a).jar org.springframework.web.servlet-x.y.z.M(a).jar Finally add struts2-spring-plugin-x.y.z.jar in your WEB-INF/lib from your struts lib directory. If you are using Eclipse then you may face an exception java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener. To fix this problem, you should have to go in Marker tab and righ click on the class dependencies one by one and do Quick fix to publish/export all the dependences. Finally make sure there is no dependency conflict available under the marker tab. Now let us setup the web.xml for the Struts-Spring integration as follows − <?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> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <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> The important thing to note here is the listener that we have configured. The ContextLoaderListener is required to load the spring context file. Spring”s configuration file is called applicationContext.xml file and it must be placed at the same level as the web.xml file Let us create a simple action class called User.java with two properties – firstName and lastName. package com.tutorialspoint.struts2; public class User { private String firstName; private String lastName; public String execute() { return “success”; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } Now let us create the applicationContext.xml spring configuration file and instantiate the User.java class. As mentioned earlier, this file should be under the WEB-INF folder − <?xml version = “1.0” Encoding = “UTF-8”?> <!DOCTYPE beans PUBLIC “-//SPRING//DTD BEAN//EN” “http://www.springframework.org/dtd/spring-beans.dtd”> <beans> <bean id = “userClass” class = “com.tutorialspoint.struts2.User”> <property name = “firstName” value = “Michael” /> <property name = “lastName” value = “Jackson” /> </bean> </beans> As seen above, we have configured the user bean and we have injected the values Michael and Jackson into the bean. We have also given this bean a name “userClass”, so that we can reuse this elsewhere. Next let us create the User.jsp in the WebContent folder − <%@ 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 – Spring integration</h1> <s:form> <s:textfield name = “firstName” label = “First Name”/><br/> <s:textfield name = “lastName” label = “Last Name”/><br/> </s:form> </body> </html> The User.jsp file is pretty straight forward. It serves only one purpose – to display the values of the firstname and lastname of the user object. Finally, let us put all entities together using the struts.xml file. <?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 = “user” class=”userClass” method = “execute”> <result name = “success”>/User.jsp</result> </action> </package> </struts> The important thing to note is that we are using the id userClass to refer to the class. This means that we are using spring to do the dependency injection for the User class. 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/User.jsp. This will produce the following screen − We have now seen how to bring two great frameworks together. This concludes the Struts – Spring integration chapter. Print Page Previous Next Advertisements ”;
Struts2 – Annotations
Struts 2 – Annotations ”; Previous Next As mentioned previously, Struts provides two forms of configuration. The traditional way is to use the struts.xml file for all the configurations. We have seen so many examples of that in the tutorial so far. The other way of configuring Struts is by using the Java 5 Annotations feature. Using the struts annotations, we can achieve Zero Configuration. To start using annotations in your project, make sure you have included the following jar files in your WebContent/WEB-INF/lib folder − struts2-convention-plugin-x.y.z.jar asm-x.y.jar antlr-x.y.z.jar commons-fileupload-x.y.z.jar commons-io-x.y.z.jar commons-lang-x.y.jar commons-logging-x.y.z.jar commons-logging-api-x.y.jar freemarker-x.y.z.jar javassist-.xy.z.GA ognl-x.y.z.jar struts2-core-x.y.z.jar xwork-core.x.y.z.jar Now, let us see how you can do away with the configuration available in the struts.xml file and replace it with annotaions. To explain the concept of Annotation in Struts2, we would have to reconsider our validation example explained in Struts2 Validations chapter. Here, we shall take an example of an Employee whose name, age would be captured using a simple page, and we will put two validations to make sure that ÜSER always enters a name and age should be in between 28 and 65. Let us start with the main JSP page of the example. Create Main Page Let us write main page JSP file index.jsp, which is used to collect Employee related information mentioned above. <%@ 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</title> </head> <body> <s:form action = “empinfo” method = “post”> <s:textfield name = “name” label = “Name” size = “20” /> <s:textfield name = “age” label = “Age” size = “20” /> <s:submit name = “submit” label = “Submit” align=”center” /> </s:form> </body> </html> The index.jsp makes use of Struts tag, which we have not covered yet but we will study them in tags related chapters. But for now, just assume that the s:textfield tag prints a input field, and the s:submit prints a submit button. We have used label property for each tag which creates label for each tag. Create Views We will use JSP file success.jsp which will be invoked in case the 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> Employee Information is captured successfully. </body> </html> Create Action This is the place where annotation is used. Let us re-define action class Employee with annotation, and then add a method called validate () as shown below in Employee.java file. Make sure that your action class extends the ActionSupport class, otherwise your validate method will not be executed. package com.tutorialspoint.struts2; import com.opensymphony.xwork2.ActionSupport; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.Results; import com.opensymphony.xwork2.validator.annotations.*; @Results({ @Result(name = “success”, Location = “/success.jsp”), @Result(name = “input”, Location = “/index.jsp”) }) public class Employee extends ActionSupport { private String name; private int age; @Action(value = “/empinfo”) public String execute() { return SUCCESS; } @RequiredFieldValidator( message = “The name is required” ) public String getName() { return name; } public void setName(String name) { this.name = name; } @IntRangeFieldValidator(message = “Age must be in between 28 and 65”, min = “29”, max = “65”) public int getAge() { return age; } public void setAge(int age) { this.age = age; } } We have used few annotations in this example. Let me go through them one by one − First, we have included the Results annotation. A Results annotation is a collection of results. Under the results annotation, we have two result annotations. The result annotations have the name that correspond to the outcome of the execute method. They also contain a location as to which view should be served corresponding to return value from execute() The next annotation is the Action annotation. This is used to decorate the execute() method. The Action method also takes in a value which is the URL on which the action is invoked. Finally, I have used two validation annotations. I have configured the required field validator on name field and the integer range validator on the age field. I have also specified a custom message for the validations. Configuration Files We really do not need struts.xml configuration file, so let us remove this file and let us check 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> <init-param> <param-name>struts.devMode</param-name> <param-value>true</param-value> </init-param> </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 − Now do not enter any required information, just click on Submit button. You will see the following result − Enter the required information but enter a wrong From field, let us say name as “test” and age as 30, and finally click on Submit button. You will see the following result − Struts 2 Annotations Types Struts 2 applications can use Java 5 annotations as an alternative to XML and Java properties configuration. You can check the list of most important annotations related to different categories − Struts 2 Annotations Types. Print Page Previous Next Advertisements ”;
Struts2 – Sending Email
Struts 2 – Sending Email ”; Previous Next This chapter explains how you can send an email using your Struts 2 application. For this exercise, you need to download and install the mail.jar from JavaMail API 1.4.4 and place the mail.jar file in your WEB-INFlib folder and then proceed to follow the standard steps of creating action, view and configuration files. Create Action The next step is to create an Action method that takes care of sending the email. Let us create a new class called Emailer.java with the following contents. package com.tutorialspoint.struts2; import java.util.Properties; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import com.opensymphony.xwork2.ActionSupport; public class Emailer extends ActionSupport { private String from; private String password; private String to; private String subject; private String body; static Properties properties = new Properties(); static { properties.put(“mail.smtp.host”, “smtp.gmail.com”); properties.put(“mail.smtp.socketFactory.port”, “465”); properties.put(“mail.smtp.socketFactory.class”, “javax.net.ssl.SSLSocketFactory”); properties.put(“mail.smtp.auth”, “true”); properties.put(“mail.smtp.port”, “465”); } public String execute() { String ret = SUCCESS; try { Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); } } ); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject(subject); message.setText(body); Transport.send(message); } catch(Exception e) { ret = ERROR; e.printStackTrace(); } return ret; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public static Properties getProperties() { return properties; } public static void setProperties(Properties properties) { Emailer.properties = properties; } } As seen in the source code above, the Emailer.java has properties that correspond to the form attributes in the email.jsp page given below. These attributes are − From − The email address of the sender. As we are using Google”s SMTP, we need a valid gtalk id Password − The password of the above account To − Who to send the email to? Subject − subject of the email Body − The actual email message We have not considered any validations on the above fields, validations will be added in the next chapter. Let us now look at the execute() method. The execute() method uses the javax Mail library to send an email using the supplied parameters. If the mail is sent successfully, action returns SUCCESS, otherwise it returns ERROR. Create Main Page Let us write main page JSP file index.jsp, which will be used to collect email related information mentioned above − <%@ 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>Email Form</title> </head> <body> <em>The form below uses Google”s SMTP server. So you need to enter a gmail username and password </em> <form action = “emailer” method = “post”> <label for = “from”>From</label><br/> <input type = “text” name = “from”/><br/> <label for = “password”>Password</label><br/> <input type = “password” name = “password”/><br/> <label for = “to”>To</label><br/> <input type = “text” name = “to”/><br/> <label for = “subject”>Subject</label><br/> <input type = “text” name = “subject”/><br/> <label for = “body”>Body</label><br/> <input type = “text” name = “body”/><br/> <input type = “submit” value = “Send Email”/> </form> </body> </html> Create Views We will use JSP file success.jsp 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 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>Email Success</title> </head> <body> Your email to <s:property value = “to”/> was sent successfully. </body> </html> Following will be the view file error.jsp in case of an ERROR is returned from the action. <%@ 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>Email Error</title> </head> <body> There is a problem sending your email to <s:property value = “to”/>. </body> </html> Configuration Files Now 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 = “emailer” class = “com.tutorialspoint.struts2.Emailer” 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 the required information and click Send Email button. If everything goes fine, then you should see the following page. Print Page Previous Next Advertisements ”;
Struts2 – Configuration
Struts 2 – Configuration Files ”; Previous Next This chapter will take you through basic configuration which is required for a Struts 2 application. Here we will see what can be configured with the help of few important configuration files like web.xml, struts.xml, strutsconfig.xml and struts.properties Honestly speaking, you can start working by just using web.xml and struts.xml configuration files (as you have already witnessed in our previous chapter where our example worked using these two files). However, for your knowledge we will explain regarding other files also. The web.xml File The web.xml configuration file is a J2EE configuration file that determines how elements of the HTTP request are processed by the servlet container. It is not strictly a Struts2 configuration file, but it is a file that needs to be configured for Struts2 to work. As discussed earlier, this file provides an entry point for any web application. The entry point of Struts2 application will be a filter defined in deployment descriptor (web.xml). Hence we will define an entry of FilterDispatcher class in web.xml. The web.xml file needs to be created under the folder WebContent/WEB-INF. This is the first configuration file you will need to configure if you are starting without the aid of a template or tool that generates it (such as Eclipse or Maven2). Following is the content of web.xml file which we used in our last example. <?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> Note that we map the Struts 2 filter to /*, and not to /*.action which means that all urls will be parsed by the struts filter. We will cover this when we will go through the Annotations chapter. The Struts.xml File The struts.xml file contains the configuration information that you will be modifying as actions are developed. This file can be used to override default settings for an application, for example struts.devMode = false and other settings which are defined in property file. This file can be created under the folder WEB-INF/classes. Let us have a look at the struts.xml file we created in the Hello World example explained in previous chapter. <?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> <– more actions can be listed here –> </package> <– more packages can be listed here –> </struts> The first thing to note is the DOCTYPE. All struts configuration file needs to have the correct doctype as shown in our little example. <struts> is the root tag element, under which we declare different packages using <package> tags. Here <package> allows separation and modularization of the configuration. This is very useful when you have a large project and project is divided into different modules. For example, if your project has three domains – business_application, customer_application and staff_application, then you could create three packages and store associated actions in the appropriate package. The package tag has the following attributes − Sr.No Attribute & Description 1 name (required) The unique identifier for the package 2 extends Which package does this package extend from? By default, we use struts-default as the base package. 3 abstract If marked true, the package is not available for end user consumption. 4 namespace Unique namespace for the actions The constant tag along with name and value attributes should be used to override any of the following properties defined in default.properties, like we just set struts.devMode property. Setting struts.devMode property allows us to see more debug messages in the log file. We define action tags corresponds to every URL we want to access and we define a class with execute() method which will be accessed whenever we will access corresponding URL. Results determine what gets returned to the browser after an action is executed. The string returned from the action should be the name of a result. Results are configured per-action as above, or as a “global” result, available to every action in a package. Results have optional name and type attributes. The default name value is “success”. Struts.xml file can grow big over time and so breaking it by packages is one way of modularizing it, but Struts offers another way to modularize the struts.xml file. You could split the file into multiple xml files and import them in the following fashion. <?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> <include file=”my-struts1.xml”/> <include file=”my-struts2.xml”/> </struts> The other configuration file that we haven”t covered is the struts-default.xml. This file contains the standard configuration settings for Struts and you would not have to touch these settings for 99.99% of your projects. For this reason, we are not going into too much detail on this file. If you are interested, take a look into the at the default.properties file available in struts2-core-2.2.3.jar file. The Struts-config.xml File The struts-config.xml configuration file is a link between the View and Model components in the Web Client but you would not have to touch these settings for 99.99% of your projects. The configuration file basically contains following main elements − Sr.No Interceptor & Description 1 struts-config This is the root node of the configuration file. 2 form-beans This is where you map your ActionForm subclass to a name. You use this name as an alias for your ActionForm throughout the rest of the strutsconfig.xml file, and even on your JSP pages. 3 global forwards This section maps a page on your webapp to a name. You can use this name to refer to the actual page. This avoids hardcoding URLs on your web pages. 4 action-mappings This
Struts2 – Discussion
Discuss Struts 2 ”; Previous Next Apache Struts 2 is an elegant, extensible framework for creating enterprise-ready Java web applications. This framework is designed to streamline the full development cycle from building, to deploying and maintaining applications over time. Apache Struts 2 was originally known as Web Work 2. This tutorial will teach you, how to use Apache Struts for creating enterprise-ready Java web applications in simple and easy steps. Print Page Previous Next Advertisements ”;
Struts2 – Useful Resources
Struts 2 – Useful Resources ”; Previous Next The following resources contain additional information on Struts2. Please use them to get more in-depth knowledge on this topic. Useful Links on Struts 2 Apache Struts project − Apache”s Official site giving link on Struts material. Sun”s Site on JSP − Sun”s Official site giving link on JSP material. Sun”s Site on Servlets − Sun”s Official site giving link on Servlets material. JSP Engine – Tomcat − Apache Tomcat is an open source software implementation of the Java Servlet and JavaServer Pages technologies. MySQL Connector/J − MySQL Connector/J is the official JDBC driver for MySQL. The JavaTM Tutorials − The Java Tutorials are practical guides for programmers who want to use the Java programming language to create applications. JavaTM 2 SDK, Standard Edition − Official site for JavaTM 2 SDK, Standard Edition Free Java Download − Download Java for your desktop computer now! Sun Developer Network − Sun Microsystem”s official website listing down all the API documentation, latest Java Technologies, Books and other resource. Useful Books on Java and Struts To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;