242 Advanced Internet Programming 5. Struts Framework is based on __________. (a) Servlet,JSP and Java (b) Servlet,HTML and Java (c) Servlet,JSP,XML and Java (d) Applet,Xml and Java Answers 1. (c), 2. (c), 3. (c), 4. (c), 5. (c) 10.18 References 1. https://www.javatpoint.com/struts-2-tutorial 2. https://www.developer.com/java/ent/article.php/10933_1495931_2/An-Introduction-to- Struts.htm 3. Budi Kurniawan, 1 January 2010, “Struts 2 Design and Programming” Paperback. CU IDOL SELF LEARNING MATERIAL (SLM)
UNIT 11 JAVA STRUTS - II Structure: 11.0 Learning Objectives 11.1 Introduction 11.2 Sending Mails 11.2 Validation 11.3 Localization 11.4 Type Conversion 11.5 Exception Handling 11.6 Annotation 11.7 Tags and Integrations 11.8 Practical Assignment 11.9 Summary 11.10 Key Words/Abbreviations 11.11 Learning Activity 11.12 Unit End Questions (MCQs and Descriptive) 11.13 References CU IDOL SELF LEARNING MATERIAL (SLM)
244 Advanced Internet Programming 11.0 Learning Objectives After studying this unit, you will be able to: Describe sending mails, validation, and localization Explain type conversion, exception handling, and annotation Discuss tags and integrations 11.1 Introduction The struts framework is an open source framework for creating well-structured web based applications. The struts framework is based on the Model View Controller (MVC) paradigm which distinctly separates all the three layers - Model (state of the application), View (presentation) and Controller (controlling the application flow). This makes struts different from conventional JSP applications where sometimes logic, flow and UI are mingled in a Java Server Page. The struts framework is a complete web framework as it provides complete web form components, validators, error handling, internationalization, tiles and more. Struts framework provides its own Controller component. It integrates with other technologies for both Model and View components. Struts can integrate well with Java Server Pages (JSP), Java Server Faces (JSF), JSTL, Velocity templates and many other presentation technologies for View. For Model, Struts works great with data access technologies like JDBC, Hibernate, EJB and many more. 11.2 Sending mails The JavaMail is an API that is used to compose, write and read electronic messages (emails). The JavaMail API provides protocol-independent and plateform-independent framework for sending and receiving mails. The javax.mail and javax.mail.activation packages contains the core classes of JavaMail API. The JavaMail facility can be applied to many events. It can be used at the time of registering the user (sending notification such as thanks for your interest to my site), forgot password (sending password to the users email id), sending notifications for important updates etc. So there can be various usage of java mail api. CU IDOL SELF LEARNING MATERIAL (SLM)
Java Struts - II 245 Protocols used in JavaMail API There are some protocols that are used in JavaMail API. SMTP POP IMAP MIME NNTP and others Sending Email in Java There are various ways to send email using JavaMail API. For this purpose, you must have SMTP server that is responsible to send mails. You can use one of the following techniques to get the SMTP server: Install and use any SMTP server such as Postcast server, Apache James server, cmail server etc. (or) Use the SMTP server provided by the host provider e.g. my SMTP server is mail.javatpoint.com (or) Use the SMTP Server provided by other companies e.g. gmail etc. Here, we are going to learn above three approaches to send email using javamail API. But we should learn the basic steps to send email from java application. Steps to Send Email using JavaMail API There are following three steps to send email using JavaMail. They are as follows: 1. Get the session object that stores all the information of host like host name, username, password etc. 2. compose the message 3. send the message 1. Get the session object The javax.mail.Session class provides two methods to get the object of session, Session.getDefaultInstance() method and Session.getInstance() method. You can use any method to get the session object. CU IDOL SELF LEARNING MATERIAL (SLM)
246 Advanced Internet Programming Method of Session Class Table 11.1: Method of Session Class No. Method Description 1. public static Session getDefaultInstance(Properties props) returns the default session. 2. public static Session getDefaultInstance (Properties returns the default session. props,Authenticatorauth) 3. public static Session getInstance(Properties props) returns the new session 4. public static Session get Instance(Properties returns the new session props,Authenticatorauth) Example of getDefaultInstance() method Properties properties=new Properties(); //fill all the information like host name etc. Session session=Session.getDefaultInstance(properties,null); Example of getInstance() method Properties properties=new Properties(); //fill all the information like host name etc. Session session=Session.getInstance(properties,null); 2. Compose the Message The javax.mail.Message class provides methods to compose the message. But it is an abstract class so its subclass javax.mail.internet.MimeMessage class is mostly used. To create the message, you need to pass session object in MimeMessage class constructor. For example: MimeMessage message=new MimeMessage(session); Now message object has been created but to store information in this object MimeMessage class provides many methods. Let’ see methods provided by the MimeMessage class: CU IDOL SELF LEARNING MATERIAL (SLM)
Java Struts - II 247 Commonly used Methods of MimeMessage class Table 11.2: Commonly used Methods of MimeMessage class No. Method Description 1. public void setFrom (Address address) is used to set the from header field. 2. public void addRecipient is used to add the given address to the recipient type. (Message.Recipient Type type, Address address) 3. public void is used to add the given addresses to the recipient addRecipients(Message.RecipientType type. type, Address[] addresses) 4. public void setSubject(String subject) is used to set the subject header field. 5. public void setText(String textmessage) is used to set the text as the message content using text/plain MIME type. 6. public void setContent(Object msg, is used to set the content as the message content using String contentType) given MIME type. Example to compose the message: MimeMessage message=new MimeMessage(session); message.setFrom(new InternetAddress(\"[email protected]\")); message.addRecipient(Message.RecipientType.To, new InternetAddress(\"[email protected]\")); message.setHeader(\"Hi, everyone\"); message.setText(\"Hi, This mail is to inform you...\"); 3. Send the Message The javax.mail.Transport class provides method to send the message. Commonly used Methods of Transport Class Table 11.3: Commonly used Methods of Transport Class No. Method Description 1. public static void send(Message message) is used send the message. 2. public static void send(Message message, Address[] is used send the message to the given address) addresses. CU IDOL SELF LEARNING MATERIAL (SLM)
248 Advanced Internet Programming Example to Send the Message Transport.send(message); Example for Sending Email JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications. Required Library: In this example, you need to add below libraries in your project build path. 1. mail-1.4.jar <build> <sourceDirectory>src</sourceDirectory> pom.xml <plugins> <plugin> <artifactId>maven-compiler- <project xmlns=\"http://maven.apache.org/POM/4.0.0\" plugin</artifactId> xmlns:xsi=\"http://www.w3.org/2001/XMLSchema- <version>3.3</version> instance\" <configuration> xsi:schemaLocation=\"http://maven.apache.org/POM/4.0. <source>1.8</source> <target>1.8</target> 0http://maven.apache.org/xsd/maven-4.0.0.xsd\"> </configuration> <modelVersion>4.0.0</modelVersion> </plugin> <plugin> <groupId>org.websparrow</groupId> <artifactId>maven-war-plugin</artifactId> <artifactId>Test</artifactId> <version>2.6</version> <version>0.0.1-SNAPSHOT</version> <configuration> <packaging>war</packaging> <warSourceDirectory>WebContent</warS <dependencies> ourceDirectory> <dependency> <failOnMissingWebXml>false</failOnMiss <groupId>org.apache.struts</groupId> ingWebXml> <artifactId>struts2-core</artifactId> </configuration> <version>2.3.20</version> </plugin> </plugins> </build> </project> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4</version> </dependency> </dependencies> Software Used 1. Eclipse IDE 2. Tomcat 8 3. JDK 8 CU IDOL SELF LEARNING MATERIAL (SLM)
Java Struts - II 249 Project Structure in Eclipse Fig. 11.1: Project Structure in Eclipse Add Struts 2 Filter Define the struts 2 filters into web.xml <?xml version=\"1.0\" encoding=\"UTF-8\"?> </welcome-file-list> <filter> <web-app <filter-name>struts2</filter-name> <filter- xmlns:xsi=\"http://www.w3.org/2001/XMLSchema- class>org.apache.struts2.dispatcher.ng.filter.S instance\" trutsPrepareAndExecuteFilter</filter-class> </filter> xmlns=\"http://java.sun.com/xml/ns/javaee\" <filter-mapping> xsi:schemaLocation=\"http://java.sun.com/xml/ns/ja <filter-name>struts2</filter-name> vaeehttp://java.sun.com/xml/ns/javaee/web- <url-pattern>/*</url-pattern> app_2_5.xsd\" id=\"WebApp_ID\" version=\"2.5\"> </filter-mapping> </web-app> <display- name>Struts2JavaMailApiExample</display- name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> CU IDOL SELF LEARNING MATERIAL (SLM)
250 Advanced Internet Programming Create Action Class The next step is creating the Action Class that control the sending of email. In this Action class, we have to call the method sendMail of SendEmail class and passes the parameter. Struts2JavaMailAction.java packageorg.websparrow; @Override import public String execute() throws Exception { com.opensymphony.xwork2.ActionSupport; obj = new SendEmail(); resp = obj.sendMail(senderEmail, public class Struts2JavaMailAction extends senderPassword, receiverEmail, subject, ActionSupport { message); if (resp == 1) { private static final long serialVersionUID = return \"SUCCESS\"; 8676674317393590961L; } else { return \"ERROR\"; // getter and setters... }} } private String senderEmail, senderPassword, receiverEmail, subject, message; SendEmailobj = null; Int resp = 0; Now create a class SendMail which has a method sendMail requires the below parameters. from: Email address of the sender. Gmail Account password: Password of above email. to: Email address of the receiver. subject: Subject of the email. msg: Contents of the message. SendEmail.java protectedPasswordAuthenticationgetPasswordAut hentication(){ packageorg.websparrow; returnnewPasswordAuthentication(from, import java.util.Properties; password); impor tjavax.mail.Message; } }); import javax.mail.MessagingException; try { import javax.mail.PasswordAuthentication; Message message=new MimeMessage(session); import javax.mail.Session; message.setFrom(newInternetAddress(from)); import javax.mail.Transport; // recipients email address import javax.mail.internet.InternetAddress; message.setRecipients(Message.RecipientType. import javax.mail.internet.MimeMessage; CU IDOL SELF LEARNING MATERIAL (SLM)
Java Struts - II 251 public class SendEmail{ TO,InternetAddress.parse(to)); // add the Subject of email public intsendMail(String from, String message.setSubject(subject); password, String to, String subject, String // message body msg) { message.setText(msg); Transport.send(message); // setting gmailsmtp properties return1; }catch(MessagingException e) Properties props =newProperties(); { e.printStackTrace(); props.put(\"mail.smtp.auth\",\"true\"); return 0; }} } props.put(\"mail.smtp.starttls.enable\",\"true\"); props.put(\"mail.smtp.host\",\"smtp.gmail.com\"); props.put(\"mail.smtp.port\",\"587\"); // check the authentication Session session=Session.getInstance(props,newjava x.mail.Authenticator() { Create View Component In this example, we have created 3 JSP pages. index.jsp for taking the input from the user. success.jsp for email successfully sent. error.jsp for error message if any. index.jsp <%@taglib prefix=\"s\" uri=\"/struts-tags\"%> <div class=\"row\"> <html> <head> <div class=\"col-md-6\"> <link rel=\"stylesheet\" <div class=\"form-group\"> href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/ css/bootstrap.min.css\" /> <label <title>Sending email using Struts 2 and JavaMail for=\"senderEmail\">Login</label><input API</title> type=\"text\" name=\"senderEmail\" <style type=\"text/css\"> class=\"form-control\" id=\"senderEmail\" placeholder=\"Sender email\" .jumbotron { required=\"required\" /> background: #358CCE; color: #FFF; <br><input type=\"password\" class=\"form- control\" id=\"senderPassword\" border-radius: 0px; placeholder=\"Password\" } name=\"senderPassword\" required=\"required\" /> </div> <div class=\"form-group\"> CU IDOL SELF LEARNING MATERIAL (SLM)
252 Advanced Internet Programming .jumbotron-sm { <label for=\"receiverEmail\">Receiver padding-top: 24px; Email</label><input type=\"text\" padding-bottom: 24px; name=\"receiverEmail\" class=\"form-control\" } id=\"receiverEmail\" placeholder=\"Receiver .jumbotron small { email\" color: #FFF; } required=\"required\" /> .h2 small { font-size: 18px; </div> } </style> <div class=\"form-group\"> </head> <body> <label for=\"subject\">Subject</label><input <div class=\"jumbotronjumbotron-sm\"> type=\"text\" class=\"form-control\" id=\"subject\" <div class=\"container\"> name=\"subject\" placeholder=\"Subject\" <div class=\"row\"> required=\"required\" /> <div class=\"col-sm-12 col-lg-12\"> <h2 class=\"h2\"> </div> </div> WebSparrow.org <small>Sending email using Struts 2 and JavaMail API</small> <div class=\"col-md-6\"> </h2> </div> </div> </div> </div> <div class=\"form-group\"> <div class=\"container\"> <div class=\"row\"> <label for=\"message\"> Message</label> <div class=\"col-md-8\"> <div class=\"well well-sm\"> <textarea name=\"message\" id=\"message\" <form action=\"sendemail\" method=\"post\"> class=\"form-control\" rows=\"11\" cols=\"25\" required=\"required\" placeholder=\"Message\"></textarea> </div> </div> <div class=\"col-md-12\"> <button type=\"submit\" class=\"btnbtn-primary pull-right\" id=\"btnContactUs\">Send Message</button> </div> </div> </form> </div> </div> </div> </div> </body> </html> success.jsp <html> .h2 small { font-size: 18px; <head> } </style> </head> <body> <link rel=\"stylesheet\" <div class=\"jumbotronjumbotron-sm\"> href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/ <div class=\"container\"> bootstrap.min.css\" /> <title>Sending email using Struts 2 and JavaMail API</title> CU IDOL SELF LEARNING MATERIAL (SLM)
Java Struts - II 253 <style type=\"text/css\"> <div class=\"row\"> .jumbotron { <div class=\"col-sm-12 col-lg-12\"> background: #358CCE; <h2 class=\"h2\"> color: #FFF; WebSparrow.org <small>Sending email border-radius: 0px; using Struts 2 and JavaMail API</small> } </h2> .jumbotron-sm { </div> </div> </div> </div> padding-top: 24px; <div class=\"container\"> padding-bottom: 24px; } <p style=\"color: green;\">Email Sent .jumbotron small { Successfully</p> color: #FFF; } </div> </body> </html> error.jsp .h2 small { <html> font-size: 18px; <head> <link rel=\"stylesheet\" } href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bo otstrap.min.css\" /> </style> </head> <title>Sending email using Struts 2 and JavaMail API</title> <body> <style type=\"text/css\"> .jumbotron { <div class=\"jumbotronjumbotron- background: #358CCE; sm\"> color: #FFF; border-radius: 0px; <div class=\"container\"> } .jumbotron-sm { <div class=\"row\"> padding-top: 24px; padding-bottom: 24px; <div class=\"col-sm-12 col-lg-12\"> } .jumbotron small { <h2 class=\"h2\"> color: #FFF; } WebSparrow.org <small>Sending email using Struts 2 and JavaMail API</small> </h2> </div> </div> </div> </div> <div class=\"container\"> <p style=\"color: red;\">Some error occurred. For more info check the console.</p> </div> </body> </html> CU IDOL SELF LEARNING MATERIAL (SLM)
254 Advanced Internet Programming Configuration File Create the struts.xml file in the source package and map the Action class. struts.xml <?xml version=\"1.0\" encoding=\"UTF-8\" ?> <package name=\"default\" namespace=\"/\" extends=\"struts-default\"> <!DOCTYPE struts PUBLIC <action name=\"sendemail\" \"-//Apache Software Foundation//DTD Struts class=\"org.websparrow.Struts2JavaMailAction\" Configuration 2.0//EN\" > \"http://struts.apache.org/dtds/struts-2.0.dtd\"> <result name=\"SUCCESS\">/success.jsp</result> <struts> <result name=\"ERROR\">/error.jsp</result> <constant name=\"struts.devMode\" value=\"true\" /> </action> </package> </struts> 11.3 Validation To avoid the wrong values, we need to perform validation on forms where user submits some values. For example, if user writes his/her email id as abc, we need to give error message to the user that the given email id is not correct. So, that we can have only valuable informations. There are three ways to perform validation in struts 2. 1. By Custom Validation: Here, we must implement the Validateable interface (or extend ActionSupport class) and provide the implementation of validate method. 2. By Input Validation (built-in validators) : Struts 2 provides a lot of predefined that can be used in struts 2 application to perform validation. Struts 2 provides following bundled validators. requiredstring validator stringlength validator email validator date validator int validator double validator url validator regex validator CU IDOL SELF LEARNING MATERIAL (SLM)
Java Struts - II 255 3. By Ajax Validation (built-in validators with ajax): If we don’t want to refresh the page, we can use jsonValidation interceptor to perform validation with ajax. 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 <body> = \"text/html; charset = ISO-8859-1\" <s:form action = \"empinfo\" method = \"post\"> pageEncoding = \"ISO-8859-1\"%> <s:textfield name = \"name\" label = \"Name\" size = <%@ taglib prefix = \"s\" uri = \"/struts- \"20\" /> tags\"%> <s:textfield name = \"age\" label = \"Age\" size = \"20\" <!DOCTYPE html PUBLIC \"-//W3C//DTD /> HTML 4.01 Transitional//EN\" <s:submit name = \"submit\" label = \"Submit\" \"http://www.w3.org/TR/html4/loose.dtd\"> align=\"center\" /> <html> <head> </s:form> <title>Employee Form</title> </head> </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 = <html> <head> \"text/html; charset = ISO-8859-1\" <title>Success</title> CU IDOL SELF LEARNING MATERIAL (SLM)
256 Advanced Internet Programming pageEncoding = \"ISO-8859-1\"%> </head> <%@ taglib prefix = \"s\" uri = \"/struts-tags\"%> <body> <!DOCTYPE html PUBLIC \"-//W3C//DTD HTML Employee Information is captured 4.01 Transitional//EN\" successfully. \"http://www.w3.org/TR/html4/loose.dtd\"> </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; public intgetAge() { import return age; com.opensymphony.xwork2.ActionSupport; } public class Employee extends ActionSupport { public void setAge(int age) { private String name; this.age = age; privateint age; } public String execute() { public void validate() { return SUCCESS; if (name == null || name.trim().equals(\"\")) { } addFieldError(\"name\",\"The name is required\"); public String getName() { } return name; if (age < 28 || age > 65) { } addFieldError(\"age\",\"Age must be in between public void setName(String name) { 28 and 65\"); this.name = name; } }}} 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\"?> <action name = \"empinfo\" <!DOCTYPE struts PUBLIC class = \"com.tutorialspoint.struts2.Employee\" \"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN\" method = \"execute\"> CU IDOL SELF LEARNING MATERIAL (SLM)
Java Struts - II 257 \"http://struts.apache.org/dtds/struts-2.0.dtd\"> <result name = <struts> \"input\">/index.jsp</result> <constant name = \"struts.devMode\" value = \"true\" /> <package name = \"helloworld\" extends = \"struts- <result name = default\"> \"success\">/success.jsp</result> Following is the content of web.xml file – </action> </package> </struts> <?xml version = \"1.0\" Encoding = \"UTF-8\"?> <welcome-file>index.jsp</welcome-file> <web-app xmlns:xsi = </welcome-file-list> \"http://www.w3.org/2001/XMLSchema- <filter> instance\" <filter-name>struts2</filter-name> <filter-class> xmlns = \"http://java.sun.com/xml/ns/javaee\" org.apache.struts2.dispatcher.FilterDispatcher </filter-class> xmlns:web = \"http://java.sun.com/xml/ns/javaee/web- app_2_5.xsd\" xsi:schemaLocation = </filter> \"http://java.sun.com/xml/ns/javaee <filter-mapping> <filter-name>struts2</filter-name> http://java.sun.com/xml/ns/javaee/web- <url-pattern>/*</url-pattern> app_3_0.xsd\" </filter-mapping> </web-app> id = \"WebApp_ID\" version = \"3.0\"> <display-name>Struts 2</display-name> <welcome-file-list> 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 – CU IDOL SELF LEARNING MATERIAL (SLM)
258 Advanced Internet Programming 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 − 11.4 Localization 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. CU IDOL SELF LEARNING MATERIAL (SLM)
Java Struts - II 259 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 − 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. CU IDOL SELF LEARNING MATERIAL (SLM)
260 Advanced Internet Programming 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\"/> his example tries to show in a simple and straight forward way of creating a web application with Internationalization or I18N capability. In this example, we are creating following pages: 1. HelloWorld.java 2. HelloWorld_en.properties and HelloWorld _hi.properties 3. HelloWorld.jsp 4. struts.xml 1. Create the Action Class /** */ * @author LEE private String message; */ /** packagecom.nirvanaitedge.lee; * Return Message property. import * CU IDOL SELF LEARNING MATERIAL (SLM)
Java Struts - II 261 com.opensymphony.xwork2.ActionSupport; * @return Message property public class HelloWorld extends ActionSupport */ { public String getMessage() { public String execute() throws Exception { return message; setMessage(getText(MESSAGE)); } return SUCCESS; /** } * Set Message property. /** * * Provide default value for Message property. * @param message Text to display on */ HelloWorld page. public static final String MESSAGE = */ \"HelloWorld.message\"; public void setMessage(String message) { /** this.message = message; * Field for Message property. }} 2. Create the Properties file 2.HelloWorld_hi.properties HelloWorld.message=Suprabhat! 1.HelloWorld_en.properties HelloWorld.message=Good Morning! <h3>Languages</h3> <ul> <li> 3. Create HelloWorld.jsp for input <s:url id=\"url\" action=\"HelloWorld\"> <s:param <%-- name=\"request_locale\">en</s:param> Document : newjsp </s:url> Created on : 14 Jan, 2015, 6:46:19 PM Click <s:ahref=\"%{url}\">here</s:a> to greet in Author : LEE English. --%> </li> <li> <%@ page contentType=\"text/html; <s:url id=\"url\" action=\"HelloWorld\"> charset=UTF-8\" %> <s:param name=\"request_locale\">in</s:param> <%@ taglib prefix=\"s\" uri=\"/struts-tags\" %> </s:url> <html> Click <s:ahref=\"%{url}\" >here</s:a> to greet in <head> Hindi. <title><s:text </li> </ul> </body> </html> name=\"HelloWorld.message\"/></title> </head> <body> <h2><s:property value=\"message\"/></h2> CU IDOL SELF LEARNING MATERIAL (SLM)
262 Advanced Internet Programming 4 Define action in struts.xml <struts> <package name=\"com.nirvanaitedge.lee\" namespace=\"/com.nirvanaitedge.lee\" extends=\"struts-default\"> <action name=\"HelloWorld\" class=\"com.nirvanaitedge.lee.HelloWorld\"> <result>/com.nirvanaitedge.lee/HelloWorld.jsp</result> </action> </package> </struts> Make a note that we don ’ t need to specify ‘ method = “ execute ” ’ as action tag attribute because Struts by default checks the ‘execute’ method if no method is specified. The ‘method’ attribute of action class is used only when we are using a method name other than ‘execute’ who’ s result we need to map in struts.xml file. Running the Application: HelloWorld.jsp is loaded with two hyperlinks. Clicking on any of the links will greet in the specific language. Clicking on 1st hyperlink greets in English. Clicking on second hyperlink greets in Hindi. CU IDOL SELF LEARNING MATERIAL (SLM)
Java Struts - II 263 11.4 Type Conversion Struts uses a variety of type converters under the covers to do the heavy lifting. For example, if you have an integer attribute in your Action class, Struts automatically converts the request parameter to the integer attribute without you doing anything. By default, Struts comes with a number of type converters like: Integer, Float, Double, Decimal Date and Datetime Arrays and Collections Enumerations Boolean BigDecimal 11.5 Exception Handling Struts provides an easy way for handling uncaught exceptions which might be thrown during execution of action classes. Uncaught exceptions are ones which are not caught by the regular try- catch clause. There are two methods for handing uncaught exceptions in Struts: Global exception handling: specifies exception mappings (exception type - view name) which apply to all action classes in a Struts package. Exception handling per action: specifies exception mappings which apply to a specific action class. CU IDOL SELF LEARNING MATERIAL (SLM)
264 Advanced Internet Programming Understanding the Internal Working of Exception Interceptor If there occurs exception, it is wrapped in ExceptionHolder and pushed in the valuestack so that we can easily access exception object from the result. Parameters of exception interceptor There are 3 parameters defined for exception interceptor. All are optional. Table 11.4: Parameters Defined for Exception Interceptor Parameter Description logEnabled specifies log should be enabled or not. You can pass true or false. logLevel specifies the log level. It may be trace, debug, info, warn, error, fatal. Default log level is debug. logCategory specifies the log category eg. com.mycompany.app. The default is com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor… 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; x = x.substring(0); import return SUCCESS; } com.opensymphony.xwork2.ActionSupport; public String getName() { return name; } public class HelloWorldAction extends public void setName(String name) { ActionSupport{ this.name = name; }} private String name; public String execute() { String x = null; Let us keep the content of HelloWorld.jsp as follows − <%@ page contentType = \"text/html; charset = UTF-8\" %> <%@ taglib prefix = \"s\" uri = \"/struts-tags\" %> <html> CU IDOL SELF LEARNING MATERIAL (SLM)
Java Struts - II 265 <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 = </head> \"text/html; charset = ISO-8859-1\" <body> pageEncoding = \"ISO-8859-1\"%> <h1>Hello World From Struts2</h1> <%@ taglib prefix = \"s\" uri = \"/struts-tags\"%> <form action = \"hello\"> <!DOCTYPE html PUBLIC \"-//W3C//DTD HTML <label for = \"name\">Please enter your 4.01 Transitional//EN\" name</label><br/> \"http://www.w3.org/TR/html4/loose.dtd\"> <input type = \"text\" name = \"name\"/> <html> <input type = \"submit\" value = \"Say Hello\"/> <head> <title>Hello World</title> </form> </body> </html> Your struts.xml should look like – <?xml version = \"1.0\" Encoding = \"UTF-8\"?> <action name = \"hello\" <!DOCTYPE struts PUBLIC class = \"com.tutorialspoint.struts2.HelloWorldAction \"-//Apache Software Foundation//DTD Struts \" Configuration 2.0//EN\" method = \"execute\"> \"http://struts.apache.org/dtds/struts-2.0.dtd\"> <result name = <struts> \"success\">/HelloWorld.jsp</result> <constant name = \"struts.devMode\" value = \"true\" </action> /> </package> <package name = \"helloworld\" extends = \"struts- default\"> </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 − CU IDOL SELF LEARNING MATERIAL (SLM)
266 Advanced Internet Programming 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> CU IDOL SELF LEARNING MATERIAL (SLM)
Java Struts - II 267 Let us now configure Struts to use this error page in case of an exception. Let us modify the struts.xml as follows – <?xml version = \"1.0\" Encoding = \"UTF-8\"?> <action name = \"hello\" <!DOCTYPE struts PUBLIC class = \"com.tutorialspoint.struts2.HelloWorldAction\" \"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN\" method = \"execute\"> \"http://struts.apache.org/dtds/struts-2.0.dtd\"> <exception-mapping exception = \"java.lang.NullPointerException\" <struts> result = \"error\" /> <constant name = \"struts.devMode\" value = \"true\" /> <result name = \"success\">/HelloWorld.jsp</result> <package name = \"helloworld\" extends = \"struts-default\"> <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 − 11.6 Annotation Struts 2 provides you convenient way to create struts application using annotations. So, there is no need to have struts.xml file. As we have said earlier, there are 2 ways to use zero configuration file (no struts.xml file). 1. By convention 2. By annotation Annotations used in struts 2 application. CU IDOL SELF LEARNING MATERIAL (SLM)
268 Advanced Internet Programming For simple annotation example of struts 2, we can use 3 annotations: 1. @Action annotation is used to mark the action class. 2. @Results annotation is used to define multiple results for one action. 3. @Result annotation is used to display single result. 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 commons-logging-api-x.y.jar asm-x.y.jar freemarker-x.y.z.jar antlr-x.y.z.jar javassist-.xy.z.GA commons-fileupload-x.y.z.jar ognl-x.y.z.jar commons-io-x.y.z.jar struts2-core-x.y.z.jar commons-lang-x.y.jar xwork-core.x.y.z.jar commons-logging-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. CU IDOL SELF LEARNING MATERIAL (SLM)
Java Struts - II 269 <%@ page language <title>Employee Form</title> =\"java\"contentType=\"text/html; charset = </head> <body> ISO-8859-1\" <s:formaction=\"empinfo\"method=\"post\"> <s:textfieldname=\"name\"label=\"Name\"size=\"20\"/> pageEncoding=\"ISO-8859-1\"%> <s:textfieldname=\"age\"label=\"Age\"size=\"20\"/> <s:submitname=\"submit\"label=\"Submit\"align=\"center\" <%@taglib prefix =\"s\"uri=\"/struts-tags\"%> /> </s:form> <!DOCTYPE html PUBLIC \"-//W3C//DTD </body> HTML 4.01 Transitional//EN\" </html> \"http://www.w3.org/TR/html4/loose.dtd\"> <html> <head> 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; <html> charset = ISO-8859-1\" pageEncoding=\"ISO-8859- <head> <title>Success</title> 1\"%> </head> <body> <%@taglib prefix =\"s\"uri=\"/struts-tags\"%> Employee Information is captured successfully. <!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 </body> </html> Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"> 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; @Action(value=\"/empinfo\") publicString execute() { import return SUCCESS; com.opensymphony.xwork2.ActionSupport; import CU IDOL SELF LEARNING MATERIAL (SLM)
270 Advanced Internet Programming org.apache.struts2.convention.annotation.Action; } import @RequiredFieldValidator( message =\"The org.apache.struts2.convention.annotation.Result; name is required\") import publicStringgetName() { { org.apache.struts2.convention.annotation.Results return name; ; } publicvoidsetName(String name) import this.name = name; com.opensymphony.xwork2.validator.annotations. *; @Results({ } @Result(name @IntRangeFieldValidator(message =\"Age =\"success\",Location=\"/success.jsp\"), must be in between 28 and 65\", min =\"29\", @Result(name =\"input\",Location=\"/index.jsp\") max =\"65\") }) publicclassEmployeeextendsActionSupport{ publicintgetAge() { privateString name; privateint age; return age; } publicvoidsetAge(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\"?> <filter-name>struts2</filter-name> <web- <filter-class> CU IDOL SELF LEARNING MATERIAL (SLM)
Java Struts - II 271 appxmlns:xsi=\"http://www.w3.org/2001/XMLSchem org.apache.struts2.dispatcher.FilterDispatc a-instance\" her xmlns=\"http://java.sun.com/xml/ns/javaee\" </filter-class> xmlns:web=\"http://java.sun.com/xml/ns/javaee/web- <init-param> app_2_5.xsd\" <param-name>struts.devMode</param- xsi:schemaLocation=\"http://java.sun.com/xml/ns/jav name> aee <param-value>true</param-value> http://java.sun.com/xml/ns/javaee/web- </init-param> app_3_0.xsd\" </filter> id=\"WebApp_ID\"version=\"3.0\"> <filter-mapping> <display-name>Struts 2</display-name> <filter-name>struts2</filter-name> <welcome-file-list> <url-pattern>/*</url-pattern> <welcome-file>index.jsp</welcome-file> </filter-mapping> </welcome-file-list> </web-app> <filter> Now, right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat’ 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 – CU IDOL SELF LEARNING MATERIAL (SLM)
272 Advanced Internet Programming 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 – 11.7 Tags and Integrations Struts 2 Data Tags Example In this example you will learn how to use the property tag, the set tag and the push tag. These tags are part of the Struts 2 Data Tags. Before we see the syntax of each tag you need to know what an ActionContext and a ValueStack is. Object 0 ActionContext parameters application attr Value Stack session Object n-1 request Object n The ActionContext is a global storage area that holds all the data associated with the processing of a request. The ActionContext is thread local this makes the Struts 2 actions thread safe. The ValueStack is the part of the ActionContext. In Struts 2 actions resides on the ValueStack. CU IDOL SELF LEARNING MATERIAL (SLM)
Java Struts - II 273 The Property Tag The property tag is used to retrieve the data from the ValueStack or some other object in the ActionContext like application or session. Let’s see how to display the following details using the property tag. Our Action class AlbumInfoAction contains the following piece of code. package vaannila; public String execute() { public class AlbumInfoAction{ return \"success\"; } private String title; public String getTitle() { private Artist artist; return title; } public String populate() public void setTitle(String title) { { this.title = title; } title = \"Thriller\"; public Artist getArtist() { artist = new Artist(\"Michael Jackson\",\"King of return artist; } pop\"); public void setArtist(Artist artist) { return \"populate\"; this.artist = artist; } }} Struts 2 Property Tag Example Our Artist data class contains the following code. package vaannila; public void setName(String name) { public class Artist { this.name = name; private String name; } private String bio; public String getBio() { Artist(String name, String bio) return bio; { } CU IDOL SELF LEARNING MATERIAL (SLM)
274 Advanced Internet Programming this.name = name; public void setBio(String bio) { this.bio = bio; } this.bio = bio; public String getName() { }} return name; } Let’s see how we can access the action class attributes using the property tag in the jsp page. The albumDetails.jsp page contains the following code. <%@taglib uri=\"/struts-tags\" prefix=\"s\"%> <body> <html> <div class=\"content\"> <head> <b>Album Title :</b> <s:head /> <s:property value=\"title\" /> <br> <style type=\"text/css\"> <b>Artist Name :</b> @import url(style.css); <s:property value=\"artist.name\" /> </style> <br> <b>Artist Bio :</b> <title>Album Details</title> <s:property value=\"artist.bio\" /> </head> <br> </div> </body> </html> As you can see title is the property of the AlbumInfoAction so we can access it directly. But name and bio are properties of the Artist class so to access them we need to go one step deeper. We need to use a second-level OGNL expression to access them. Struts 2 Set Tag Example The set tag is used to assign a property value to another name. This helps in accessing the property in a faster and easier way. To access the artist name we need to go one level deeper and fetch it when we used the property tag, instead you can assign the value to another property in the ActionContext and access it directly. The following code shows how to do this. <s:set name=\"artistName\" value=\"artist.name\" /> <s:set name=\"artistBio\" value=\"artist.bio\" /> <b>Album Title :</b> <s:property value=\"title\" /> <br> <b>Artist Name :</b> <s:property value=\"#artistName\" /> <br> <b>Artist Bio :</b> <s:property value=\"#artistBio\" /> <br> The property artistName and artistBio will now be stored in the ActionContext. To refer then you need to use the following syntax #objectName. You can also place the property value in the session map in the following way. Now the value artistName and artistBio will persist throughout the session. CU IDOL SELF LEARNING MATERIAL (SLM)
Java Struts - II 275 <s:set name=\"artistName\" value=\"artist.name\" scope=\"session\" /> <s:set name=\"artistBio\" value=\"artist.bio\" scope=\"session\" /> <b>Album Title :</b> <s:property value=\"title\" /> <br> <b>Artist Name :</b> <s:property value=\"#session['artistName']\" /> <br> <b>Artist Bio :</b> <s:property value=\"#session['artistBio']\" /> <br> In the same way you can also store the values in other maps available in the ActionContext. Struts 2 Push Tag Example You can push a value into the ValueStack using the push tag. The value we pushed using push tag will be on top of the ValueStack, so it can be easily referenced using the first-level OGNL expression instead of a deeper reference. The following code shows how to do this. <b>Album Title :</b> <s:property value=\"title\" /> <br> <s:push value=\"artist\"> <b>Artist Name :</b> <s:property value=\"name\" /> <br> <b>Artist Bio :</b> <s:property value=\"bio\" /> <br> </s:push> Control tags are used for manipulation and navigation of data from a collection. Some of the important Struts 2 control tags are: if-elseif-else tags: These are the basic control tags used for conditional logic in result pages. elseif and else tags always work with if tags. if and elseif tags have test attribute where we can provide expression that should result in boolean values, true or false. Example usage is: <s:if test=\"expression\"> //do something </s:if> <s:elseif test=\"expression\"> //do something </s:elseif> <s:else> //do something </s:else> else tag doesn’t have any attribute. CU IDOL SELF LEARNING MATERIAL (SLM)
276 Advanced Internet Programming iterator tag: We can use iterator tag to loop through a collection of objects. The collection could be array, list, map etc. iterator tags provide option to define a variable in the ActionContext with status attribute. IteratorStatus provides the current status of iterator and expose some methods to get count, odd or even, first or last element etc. Example usage is: <s:iterator value=\"list\" status=\"itStatus\"> <s:property/> </s:iterator> For iterating a map, we need to provide property tag value as key and value. <s:iterator value=\"map\"> Key=<s:property value=\"key\"/>, Value=<s:property value=\"value\"/><br> </s:iterator> The other control tags are provided to work with iterators. append tag: This tag can be used to append multiple lists and then use them in iterator. The lists to append are provided with param tag and lists are appended one after another. So first list elements will be retrieved first by iterator then second list elements and so on. Example usage is: <s:append var=\"myList\"> <s:param value=\"list1\"></s:param> <s:param value=\"list2\"></s:param> </s:append> <s:iterator value=\"#myList\"> <s:property/> </s:iterator> merge tag: We can use merge tag to merge multiple lists. The first elements from all the lists are merged first, then second element and so on. We can use merge tag like below. <s:merge var=\"myList\"> <s:param value=\"list1\"></s:param> <s:param value=\"list2\"></s:param> </s:merge> <s:iterator value=\"#myList\"> <s:property/><br> </s:iterator> CU IDOL SELF LEARNING MATERIAL (SLM)
Java Struts - II 277 sort tag: We can use sort tag to get the sorted list. We need to provide a comparator to be used for sorting the list. We can use it like below. <s:bean name=\"MyComparator\" var=\"myComparator\"></s:bean> <s:sort comparator=\"#myComparator\" source=\"list\"> <s:iterator> <s:property/><br> </s:iterator> </s:sort> subset tag: We can use subset tag to get the subset of an iterator. We need to provide a Decider implementation that will be used by subset tag to filter elements as whether to include them in iterator or not. We can use it like below. <s:subset source=\"list\" decider=\"myDecider\"> <s:iterator> <s:property/><br> </s:iterator> </s:subset> generator tag: We can use generator tag to create an iterator from given values. We can provide separator to use the delimiter for the values and we can also provide Converter implementation to convert the String to an Object. We can use it like below. <s:generator val=\"%{'1,2,3'}\" separator=\",\" var=\"intsIterator\" /> <s:iterator value=\"#intsIterator\"> <s:property /><br/> </s:iterator> Struts 2 Tiles Framework Integration Tutorial Example We can customize the layout of the struts 2 application by integrating with tiles framework. A web page can contain many parts (known as tile) such as header, left pane, right pane, body part, footer etc. In tiles framework, we manage all the tile by our Layout Manager page. Advantage of Tiles Framework There are following advantages of tiles framework: CU IDOL SELF LEARNING MATERIAL (SLM)
278 Advanced Internet Programming Customization by centralized page We can customize the layout of all the pages by single page (centralized page) only. Code reusability A single part e.g. header or footer can be used in many pages. So it saves coding. Easy to modify If any part (tile) is modified, we don’t need to change many pages. Easy to remove If any part (tile) of the page is removed, we don’t need to remove the code from all the pages. We can remove the tile from our layout manager page. HEADER LEFT CENTER RIGHT FOOTER Fig 11.2: Tile Framework Steps to create tiles application The steps are as follows: 1. Add tiles library in your application 2. Define Struts2TilesListener in web.xml file 3. Create the input page (index.jsp) 4. Create the Action class 5. Extend the tiles-default package in your package and define all the result type as tiles in struts.xml file 6. Create the tiles.xml file and define all the tiles definitions 7. Create the LayoutManager page 8. Create the View components 1. Add tiles Library in your Application If you are using myeclipse IDE, you can add tiles library by right click on the project -> Build Path -> Add Library -> Add Myeclipse Library -> Select the Struts 2 tiles library -> ok. CU IDOL SELF LEARNING MATERIAL (SLM)
Java Struts - II 279 If you are using eclipse or Netbeans IDE, you need to add the required tiles library in your project. Steps to Create Tiles Application The steps are as follows: 1. Add tiles library in your application 2. Define Struts2TilesListener in web.xml file 3. Create the input page (index.jsp) 4. Create the Action class 5. Extend the tiles-default package in your package and define all the result type as tiles in struts.xml file 6. Create the tiles.xml file and define all the tiles definitions 7. Create the LayoutManager page 8. Create the View components 1. Add tiles library in Your Application If you are using myeclipse IDE, you can add tiles library by right click on the project -> Build Path -> Add Library -> Add Myeclipse Library -> Select the Struts 2 tiles library -> ok. If you are using eclipse or Netbeans IDE, you need to add the required tiles library in your project. Define Struts2TilesListener in web.xml file Provide entry of listener class Struts2TilesListener in the web.xml file. web.xml <filter-class> <?xml version=\"1.0\" encoding=\"UTF-8\"?> org.apache.struts2.dispatcher.ng.filter.StrutsPrepare <web-app version=\"2.5\" AndExecuteFilter </filter-class> xmlns=\"http://java.sun.com/xml/ns/javaee\" </filter> xmlns:xsi=\"http://www.w3.org/2001/XMLS <filter-mapping> chema-instance\" <filter-name>struts2</filter-name> xsi:schemaLocation=\"http://java.sun.com/ <url-pattern>/*</url-pattern> xml/ns/javaee </filter-mapping> http://java.sun.com/xml/ns/javaee/web- app_2_5.xsd\"> <listener> CU IDOL SELF LEARNING MATERIAL (SLM)
280 Advanced Internet Programming <welcome-file-list> <listener- <welcome-file>index.jsp</welcome-file> class>org.apache.struts2.tiles.StrutsTilesListener</lis </welcome-file-list> tener-class> <filter> </listener> <filter-name>struts2</filter-name> </web-app> 3. Create the input page (index.jsp) index.jsp <%@ taglib uri=\"/struts-tags\" prefix=\"s\" %> <s:form action=\"login\"> <s:textfield name=\"name\" label=\"Name\"></s:textfield> <s:password name=\"password\" label=\"Password\"></s:password> <s:submit value=\"login\"></s:submit> </s:form> 4. Create the action class This action class contains one field name and defines the execute method. Login.java if(password.equals(\"admin\")) { package com.javatpoint; return \"success\"; public class Login { } private String name,password; else{ //getters and setters return \"error\"; public String execute(){ }} } 5. Inherit the tiles-default package and define all the result type as tiles in struts.xml This xml file defines one package with one action and two results. struts.xml <action name=\"login\" class=\"com.javatpoint.Login\"> <?xml version=\"1.0\" encoding=\"UTF-8\" ?> <result name=\"success\" type=\"tiles\">login- <!DOCTYPE struts PUBLIC \"-//Apache success</result> Software Foundation//DTD Struts Configuration 2.1//EN\" <result name=\"error\" type=\"tiles\">login- error</result> \"http://struts.apache.org/dtds/struts-2.1.dtd\"> </action> <struts> </package> </struts> <package name=\"abc\" extends=\"tiles-default\" > CU IDOL SELF LEARNING MATERIAL (SLM)
Java Struts - II 281 6. Create the tiles.xml file and define all the tiles definitions The tiles.xml file must be located inside the WEB-INF directory. tiles.xml <put-attribute name=\"body\" <?xml version=\"1.0\" encoding=\"UTF-8\" ?> value=\"/login-success.jsp\"/> <!DOCTYPE tiles-definitions PUBLIC \"-//Apache Software Foundation//DTD Tiles </definition> Configuration 2.0//EN\" \"http://tiles.apache.org/dtds/tiles-config_2_0.dtd\"> <definition name=\"login-error\" <tiles-definitions> template=\"/layoutmanager.jsp\"> <definition name=\"login-success\" <put-attribute name=\"title\" value=\"Login template=\"/layoutmanager.jsp\"> Error\"/> <put-attribute name=\"title\" value=\"Welcome Page\"/> <put-attribute name=\"body\" value=\"/login-error.jsp\"/> </definition> </tiles-definitions> 7. Create the LayoutManager page It is the layout manager page. It used getAsString tag of tiles to include the string resource and insertAttribute tag of tiles to include the page resource. layoutmanager.jsp <title><tiles:getAsString name=\"title\" /></title> </head> <%@ taglib uri=\"http://tiles.apache.org/tags- <body> tiles\" prefix=\"tiles\" %> <%@ include file=\"header.jsp\" %> <tiles:insertAttribute name=\"body\" /> <!DOCTYPE html PUBLIC \"-//W3C//DTD HTML <%@ include file=\"footer.jsp\" %> 4.01 Transitional//EN\" </body> </html> \"http://www.w3.org/TR/html4/loose.dtd\"> <html> <head> 8. Create View components There are many view components such as header.jsp, footer.jsp, welcome.jsp etc. header.jsp login-success.jsp <%@ taglib uri=\"/struts-tags\" prefix=\"s\" %> <h2 style=\"background-color:pink;text- Welcome, <s:property value=\"name\"/> align:center;\">It is header tile</h2> </textrea></div> <hr/> <strong>login-error.jsp</strong> <hr/> <div class=\"codeblock\"><textarea name=\"code\" class=\"xml\" > footer.jsp <hr> <h2 style=\"background-color:pink;text- align:center;\">It is footer tile</h2> CU IDOL SELF LEARNING MATERIAL (SLM)
282 Advanced Internet Programming Output Sorry, username or password error! <jsp:include page=\"index.jsp\"></jsp:include> Password is not admin, so error page will be displayed. If password is admin, success page will be displayed. CU IDOL SELF LEARNING MATERIAL (SLM)
Java Struts - II 283 How to define multiple tiles files in struts 2 applicaiton To define multiple tiles, you need to add following entry in your web.xml file. <context-param id=\"struts_tiles\"> <param-name>org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG</param-name> <param-value>/WEB-INF/tiles1.xml,/WEB-INF/tiles2.xml</param-value> </context-param> 11.8 Practical Assignment 1. Write a struts application to upload multiple files. 2. Create struts application to check whether entered URL is valid or not through struts. 11.9 Summary Struts2 is a popular and mature web application framework based on the MVC design pattern. Struts2 is not just a new version of Struts 1, but it is a complete rewrite of the Struts architecture. The Webwork framework initially started with Struts framework as the basis and its goal was to offer an enhanced and improved framework built on Struts to make web development easier for the developers. After a while, the Webwork framework and the Struts community joined hands to create the famous Struts2 framework. 11.10 Key Words/Abbreviations Eclipse IDE: It is a general purpose open platform that facilitates and encourages the development of third party plug-ins Validation: Validation is a term that comes from the word “valid” which means “can be justified or defended” API: Application program interface SMTP: Simple Mail Transfer Protocol POP: Post Office Protocol IMAP: Internet Message Access Protocol CU IDOL SELF LEARNING MATERIAL (SLM)
284 Advanced Internet Programming MIME: Multipurpose Internet Mail Extensions NNTP: Network News Transfer Protocol 11.10 Learning Activity 1. Which Protocols used in JavaMail API? ----------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------- 2. Write steps to send Email using JavaMail API. ----------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------- 11.11 Unit End Questions (MCQ and Descriptive) A. Descriptive Types Questions 1. Explain how to send mails. 2. List and explain different types of Validation. 3. Write note on Localization. 4. Explain all Type conversion. 5. What is Exception Handling? 6. Explain Annotation. 7. What are Tags and Integrations ? B. Multiple Choice/Objective Type Questions 1. Struts supports which of these model components? (a) JavaBeans (b) EJB (c) CORBA (d) All Mentioned above 2. Which validates the given string with the specified regular expression,it can be used in password, security key etc.? (a) Regex Validation (b) Url Validation (c) Email Validation (d) RequiredString Validator CU IDOL SELF LEARNING MATERIAL (SLM)
Java Struts - II 285 3. Which type of validation we must implement the Validateable interface (or extend ActionSupport class) and provide the implementation of validate method? (a) By Input Validation (b) By Ajax Validation (c) By Custom Validation (d) None of the above 4. Which is used to make asynchronous request i.e. it doesn’t block the user and it sends only required field data to the server side not all, So it makes the performance fast? (a) AJAX Support (b) Integration Support (c) Various Tag Support (d) Theme and Template Support 5. Struts combines which of these in to a unified Framework? (a) Java Servlets (b) Java Server pages (c) Custom tags and Message Resources (d) All mentioned above. Answers 1. (d), 2. (a), 3. (c), 4. (a), 5. (d) 11.12 References 1. https://netbeans.org/kb/docs/web/quickstart-webapps-struts.html 2. http://mrbool.com/introduction-to-struts-framework/27062 3. Don Brown, Chad Michael Davis, Scott Stanlick, “Struts 2 in Action” 1st Edition. CU IDOL SELF LEARNING MATERIAL (SLM)
PRACTICAL BASICS UNIT 1 vcvc Practical - 1 Implementation of CRUD Operation on JDBC Application with Oracle-MySQL- PostgresSQL Source code: Insert operation package crudapplication; import java.sql.*; public class CrudApplication { public static void main(String[] args) { try { Class.forName(\"com.mysql.jdbc.Driver\").newInstance(); Connection conn = DriverManager.getConnection(\"jdbc:mysql://localhost/test\", \"root\", \"\"); Statement stmt= conn.createStatement(); stmt.execute(\"insert into user values(1,'Meet','Andheri','[email protected]')\"); stmt.execute(\"insert into user values(2,'Sohrab','Andheri','[email protected]')\"); stmt.execute(\"insert into user values(3,'Verlyn','Andheri','[email protected]')\"); System.out.println(\"record inserted\"); stmt.close(); conn.close(); } catch (Exception e) { System.out.println(\"Exception occured: \"+e); }} } CU IDOL SELF LEARNING MATERIAL (SLM)
Basics 287 Output Update and Delete Operation package crudapplication; import java.sql.*; CU IDOL SELF LEARNING MATERIAL (SLM)
288 Advanced Internet Programming public class CrudApplication { public static void main(String[] args) { try { Class.forName(\"com.mysql.jdbc.Driver\").newInstance(); Connection conn = DriverManager.getConnection(\"jdbc:mysql://localhost/test\", \"root\", \"\"); Statement stmt= conn.createStatement(); stmt.execute(\"delete from user where id='3'\"); System.out.println(\"record deleted\"); stmt.executeUpdate(\"update user set address='Kandivali' where id='2'\"); System.out.println(\"record updated\"); stmt.close(); conn.close(); } catch (Exception e) { System.out.println(\"Exception occured: \"+e); }} } CU IDOL SELF LEARNING MATERIAL (SLM)
Basics 289 Practical - 2 Implementation of Java Swings with JDBC Applications with Oracle-MySQL- PostgresSQL Source code: package App; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class UICrud extends javax.swing.JFrame { public UICrud() { initComponents(); } @SuppressWarnings(\"unchecked\") private void initComponents() { jLabel1 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jTextField2 = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jTextField3 = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jTextField4 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText(\"id\"); jLabel2.setText(\"name\"); jLabel3.setText(\"address\"); jLabel4.setText(\"email\"); jButton1.setText(\"Insert\"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); CU IDOL SELF LEARNING MATERIAL (SLM)
290 Advanced Internet Programming getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(28, 28, 28) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel4)) .addGap(36, 36, 36) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE) .addComponent(jTextField2) .addComponent(jTextField3) .addComponent(jTextField4))) .addGroup(layout.createSequentialGroup() .addGap(83, 83, 83) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(31, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(23, 23, 23) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) CU IDOL SELF LEARNING MATERIAL (SLM)
Basics 291 .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(53, 53, 53) .addComponent(jButton1) .addContainerGap(57, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { try { Class.forName(\"com.mysql.jdbc.Driver\").newInstance(); Connection conn = DriverManager.getConnection(\"jdbc:mysql://localhost/test\", \"root\", \"\"); Statement stmt= conn.createStatement(); String id= jTextField1.getText(); String name= jTextField2.getText(); String address= jTextField3.getText(); String email= jTextField4.getText(); String query =\"insert into user values(\"+id+\",'\"+name+\"','\"+address+\"','\"+email+\"')\"; stmt.execute(query); System.out.println(\"record inserted\"); stmt.close(); conn.close(); } catch (Exception e) { System.out.println(\"Exception occured: \"+e); }} CU IDOL SELF LEARNING MATERIAL (SLM)
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301
- 302
- 303
- 304
- 305
- 306
- 307
- 308
- 309
- 310
- 311
- 312
- 313
- 314
- 315
- 316
- 317
- 318
- 319
- 320
- 321
- 322
- 323
- 324
- 325
- 326
- 327
- 328
- 329
- 330
- 331
- 332
- 333
- 334
- 335
- 336
- 337
- 338
- 339
- 340
- 341
- 342
- 343
- 344
- 345
- 346
- 347
- 348
- 349
- 350
- 351
- 352
- 353
- 354
- 355
- 356
- 357
- 358
- 359
- 360
- 361
- 362
- 363
- 364
- 365
- 366
- 367
- 368
- 369
- 370
- 371
- 372