g l a r i m y presentation on apache struts 2.3 krishna mohan koyya proprietor & principle...

40
G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat http://www.glarimy.com | @glarimy | [email protected] © 2014, Glarimy. All rights reserved. http://www.glarimy.com G l a r i m y

Upload: ashley-norman

Post on 30-Dec-2015

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

G l a r I m y Presentation on

Apache Struts 2.3Krishna Mohan Koyya

Proprietor & Principle ConsultantGlarimy Technology Services | Benguluru | Bharat

http://www.glarimy.com | @glarimy | [email protected]

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

G l a r i m y

Page 2: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Agenda

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 3: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

The Classroom Protocol• Few Administrative Formalities

– Sign in the attendance sheet, if provided– Fill-in the feedback at the end of sessions, if provided

• Derive Maximum Value– Ask questions, any time– Participate in discussions and lab exercises– Avoid brining personal or office work to the class room– Stay away from internet while class in the session

• Lets Learn Together– Switch-off or mute personal phones– Leave/enter the class room without disturbing the class– Take phone calls outside the class room– Keep the class room clean and professional– No cross discussions

• Reference Material– Download from http://workshops.glarimy.com– No Print/CD. Protect Environment

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com.

Page 4: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Glarimy Technology Services• About Glarimy

– Established in 2008 and Registered in 2010– Based out of Benguluru, Bharat (Bangalore, India)

• Business Interests– Technology Consulting

• Architectural Appreciation• Architectural Review• Prototyping

– Corporate Training• Software Design, Architecture and Processes• Web 2.0 Technologies• Standard and Enterprise Technologies

– Weekend Public Workshops• One-day Executive Workshops on Saturdays

• Business Reach– Through 3rd Party Vendor Organizations and Direct Relationships– Geographies: Banguluru, Chennai, Pune, Hyderabad, Kochi and etc., – Client Base: HSBC, Robert Bosch, Oracle, Alcatel-Lucent and etc.,

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 5: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Krishna Mohan Koyya• Career spanning across 17 years

– 9 Years into Software Engineering with Cisco Systems, Wipro/Lucent and HP– 6 Years as Principle Consultant and Founder of Glarimy Technology Services– 1 Year as CEO at Sudhari IT Services, Bangalore– 1 Year as HoD at Sasi Institute of Technology and Engineering, Tadepalligudem

• Proven Delivery– Web 2.0: ExtJS, Dojo, Jquery Frameworks, HTML5, CSS3, XML– Enterprise Java: Spring, Hibernate, EJB, JSF, OSGi, Web Services– Design Patterns, Architectural Patterns, TDD

• Technology Expertise– Distributed Systems and Network Management Systems– Object Oriented Systems Development– Infrastructure, Middleware and Web Layers with Java and Javascript

• Academics– M.Tech (Computer Science & Tech) from Andhra University, Visakhapatnam– BE (Electronics & Comm. Engg) from SRKR Engg. College, Bhimavaram

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 6: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Agenda

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 7: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Introduction• Struts2 is an Apache product

– Open Source

– Industry grade with wide deployment

– Built on top of Xworks/Webworks and Struts1 legacy

• Struts 2 is an MVC Framework– Model is to structure the data

– View is to interface with the end-user

– Controller is to connect the models and views with actions

– Action is to interface with the business layer

• Struts 2 is built on latest Java Technology– Supports Dependency Injection

– Supports Aspect Oriented Programming

– Supports Annotations

– Supports Declarative Validation

– Supports Internationalization

– Supports REST and AJAX with JSON Views

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 8: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Architecture

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 9: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Struts Controller• Acts as the Front Controller and Dispatcher

– Receives the incoming HTTP Requests

– Identifies the ‘action’ from the URL

– Consults the struts.xml for locating configured Action class

– Obtains the Action object• In fact, a proxy to the action object

– Runs the request through series of interceptors• To inject input parameters to the action object

• To perform any type conversions

• To perform any validations and etc.,

– Finally calls the specified action method

– Obtains the view result from the action method

– Consults the struts.xml for locating the configured View against the result

– Invokes the View template

– Builds and sends back the HTTP Response

• The actual flow is controlled by the interceptor stack– Everything is flexible and configurable

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 10: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

A Struts Application• Is a JEE web application with

– Web.xml with Struts Controller Filter registered• org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFi

lter

– Usual Web Content • HTML, CSS, JavaScript files & libraries and other resources like images and etc.,

– Struts specific web content• JSP Templates with Struts Tags and other tags, as needed

– Java Resources• Action classes to connect with Business Layer (outside of Struts world)

• Set of custom interceptors, custom validators and custom type-convertors

– Configuration files• struts.xml for struts configuration (can include several modular xml files)

• Optionally a Validators.xml for registering custom validators

• Optionally any number of Validation.xml files for declarative validation rules

• Optionally struts.properties and log4j.properties or log4j.xml as needed

• Optionally applicationContext.xml for spring integration

• Optionally i18n resource bundles

– The struts libraries as required

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 11: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

The Maven Project• The src/main/java

– API, Service & Peristance Layer and Struts Actions

– Custom artifacts like Interceptors, Convertors and Validators

• The src/main/resources– Struts.xml, property files, resource bundles

• The src/main/webapp– JSP files and other web resources

• The src/main/webapp/WEB-INF– web.xml

• The pom.xml<dependency>

<groupId>org.apache.struts</groupId>

<artifactId>struts2-core</artifactId>

<version>${struts2.version}</version>

</dependency>

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 12: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Agenda

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 13: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Action• An interface between Struts and Business Layer• A simple POJO and confirms to Java Bean Specification

– Public default constructor (explicit or implicit)– Private state properties with public getters and setters, wherever applicable

• An object with one or more action methods– Name can be anything– No parameters– Must return String

• An object that accept or provide models– Every model property to be accepted (input parameters) must have a setter– Every model property to be provided (output parameters) must have a getter

• An object that works in the request scope– Gets created/destroyed for every request

• May extend ActionSupport class– For constants and programmatic validation and ets.,

• May implement other interfaces– For accessing session, servlet and HTTP contexts

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 14: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Action• The Model Class

public class Contact {

protected String firstName, lastName;

protected long phoneNumber;

// Add getters and setters

}

• The Action Classpublic class DirectoryAction extends ActionSupport {

// Incoming and outgoing models; Add getters and setters

private Contact contact;

private String message;

//Action Method: Access the business layer and prepare the results

public String add() {

Directory directory = GlarimyDirectory.getInstance();

directory.add(contact);

message = "Done with adding!";

return SUCCESS;

}

}

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 15: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Action• Configuration: struts.xml

<package name="public" namespace="/" extends="struts-default">

<action name="add" class="com.glarimy.struts.web.DirectoryAction"

method="add">

<result>/result.jsp</result>

</action>

</package>

• Input Page: addForm.jsp<%@ taglib prefix="s" uri="/struts-tags"%>

<s:form action="add">

<s:textfield label="First Name" name="contact.firstName" />

<s:textfield label="Last Name" name="contact.lastName" />

<s:textfield label="Phone Number" name="contact.phoneNumber" />

<s:submit value="Add Contact" />

</s:form>

• Output Page: result.jsp<s:property value="message" />

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 16: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Type Conversion• Struts interceptor performs default conversions

– Between Strings and Java Types • Automatically if Java Type is a primitive type

• With the help of Custom Converter, in other cases

– HTTP is a text based protocol• Every input parameter is a String

• Every output will have to be converted as String

– Java is a strongly typed language• The incoming strings needs to be converted into Java types in the model while

preparing for invoking action method

• The Java types in the model needs to be converted into strings while building the view

• Custom Convertors– Meant to be plugged-in for conversion between Strings and Non-

primitive Java Objects• Implement the StrutsTypeConverter• Register the converter in the classpath with xwork-converision.properties• And, that’s it. Rest is taken care, automatically

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 17: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Type Conversion• A non-primitive type: Java Object

public class Name {

private String firstName, lastName;

//Add getters and Setters

}

• A Convertor between String and Java object// The form of incoming/outgoing string: <first name><space><last name>

public class NameConverter extends StrutsTypeConverter {

public Object convertFromString(Map ctx, String[] values, Class c) {

Name name = new Name();

StringTokenizer st = new StringTokenizer(values[0], " ");

name.setFirstName(st.nextToken());name.setLastName(st.nextToken());

return name;

}

public String convertToString(Map context, Object o) {

Name name = (Name) o;

return name.getFirstName() + " " + name.getLastName();

}

}

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 18: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Type Conversion• Registration of Convertor

com.glarimy.struts.api.Name=com.glarimy.struts.web.NameConverter

• Usage of the Convertor– While sending the request

<s:textfield label=“Name (First-Name Last-Name)" name="name" />

– In the Actionpublic class Contact {

protected Name name;

//Getters and Setters

}

public class DirectoryAction implements ModelDriven<Contact> {

private Contact contact = new Contact();

public Contact getModel() {

return contact;

}

}

– While processing the responseName: <s:property value='contact.name' />

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 19: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Validation• Programmatic Validation

– Action Class• Extend ActionSupport and override validate() method• Add field errors to the error queue by calling addFieldError()• Add multi-field errors to the error queue by calling addActionError()public void validate() {

if (contact.getLastName() == null)

addFieldError("contact.lastName", “Invalid Name!");

if(contact.getFirstName()==(contact.getLastName()))

addActionError("First and Last Names can not be same!");

if (contact.getPhoneNumber() < 0)

addFieldError("contact.phoneNumber", "Invalid Number");

}

– Validator interceptor• Calls the validate() method• Makes sure that the queue is empty before proceeding to the action method• Returns “input” as the result to the controller, otherwise

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 20: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Validation• Declarative Validation with XML

– Validation rules are specific to an action class• required: The field mandatory• int: Only integer values are allowed• stringlength: Checks against the specified min and max lengths• expression: Checks if the expression returns true, good for multi-field

validation• conversion: Checks if the type conversion successful• email: Checks for the email format

– Rule file must be named as <ActionClass>-validation.xml

– Action class and rule file must be in the same package

• Declarative Validation with Annotations– Annotate the Model class

• Custom Validator– Extend FieldValidatorSupport and override validate()– Register the validator in the classpath with valdiators.xml

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 21: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Validation• Declarative Validation with XML

– Rule File<field name=“contact.name">

<field-validator type="conversion">

<message>Format of FirstName LastName</message>

</field-validator>

</field>

<field name=“contact.address.pin">

<field-validator type="required">

<message>The PIN can not be empty</message>

</field-validator>

<field-validator type="int">

<message>Invalid PIN</message>

</field-validator>

</field>

<field name=“contact.email">

<field-validator type="email">

<message>The E-mail is not valid</message>

</field-validator>

</field>

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 22: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Validation• Custom Validator

public class PasswordValidator extends FieldValidatorSupport{

public void validate(Object object) throws ValidationException {

String field = getFieldName();

String value = (String) getFieldValue(field, object);

if (value.startWith ("glarimy"))

this.addFieldError(field, object);

}

}

• Registering custom validator with validators.xml<validators>

<validator name="password" class="com.glarimy.PasswordValidator"/>

</validators>

• Using custom validator in <ActionClass>-validation.xml<field name="pwd">

<field-validator type="password">

<message>Password can not start with glarimy</message>

</field-validator>

</field>

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 23: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Validation• Reporting Validation Errors

– Struts.xml• Specify the view for “input” result against the action<action name="add" class="com.glarimy.struts.web.DirectoryAction“

method="add">

<result>/result.jsp</result>

<result name="input">/addForm.jsp</result>

</action>

– JSP Input Form• Use only s:form and s:textfield and etc., for reporting validation errors,

if any<s:actionerror />

<s:form action="add">

<s:textfield label="First Name" name="contact.firstName" />

<s:textfield label="Last Name" name="contact.lastName" />

<s:textfield label="Phone Number" name="contact.phoneNumber" />

<s:submit value="Add Contact" />

</s:form>

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 24: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Accessing Sessions• Accessing Session in Action

– Make Action class to implement SessionAware interface– Session gets injected into Action as a Map through the setter– Use the get() and put() methods to access the session

public class DirectoryViewAction implements SessionAware {

private Map<String, Object> session;

public void setSession(Map<String, Object> session) {

this.session = session;

}

public String view() {

if((String)session.get("name").equals("krishna");

session.put("email", "[email protected]");

return "success";

}

}

• Accessing Session in View– The OGNL property session refers to the current session

<s:property value="session.email" />

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 25: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Interceptors• An interceptor takes care of a cross cutting concern

– These concerns are usually secondary concerns

– They wrap the primary concerns as pre and post processing calls• Completes designated pre-processing

• May alter the request parameters or context variables, if needed

• Passes control to the next interceptor in the chain (stack), if everything is OK

• Receives the results back from the next interceptor

• Optionally change the results

• Complete the post-processing and passes the results to the caller

– AOP sees the systems as a collection of interceptors plus service objects• Examples: Logging, Validation, Transactions and etc.,

• Struts uses several interceptors– The default stack is already defined

– The order of interceptors can be configured

– Every action declares the interceptors, implicitly or explicitly

– Interceptors are designed to be unaware of other interceptors

– Custom interceptors can be developed and registered

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 26: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Interceptors• Developing Custom Interceptor

public class Tracker implements Interceptor {

public String intercept(ActionInvocation ctx) throws Exception {

if (ctx.getInvocationContext().getSession().get("email") == null)

return Action.LOGIN;

return invocation.invoke();

}

}

• Registering Custom Interceptor: struts.xml<interceptors>

<interceptor name="tracker" class="com.glarimy.Tracker" />

</interceptors>

• Configuring Interceptors for an Action: struts.xml<action name="view" class="com.glarimy.DirectoryViewAction">

<interceptor-ref name="tracker" />

<interceptor-ref name="defaultStack" />

<result>/viewResult.jsp</result>

<result name="login">/emailForm.jsp</result>

</action>

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 27: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Agenda

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 28: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Internationalization• As expected, through the usual resource bundles

– One bundle as the default bundle, say glarimy.propertiesglarimy.welcome=Welcome to Glarimy Technology Services

contact.name=First Name

– Other bundles with ISO language codes, say glarimy_ka.properties

– Register the global resource bundle in struts.xml<constant name="struts.custom.i18n.resources"

value="glarimy.properties" />

– Action specific bundles• To be named after the action class name

• To be placed along with the action classes

• Externalize all strings– In Action classes that extend ActionSupport

setMessage(getText("glarimy.welcome"));

– In JSP Views<%@ page contentType="text/html;charset=UTF-8" %>

<s:text name="glarimy.welcome"/>

<s:textfield key="contact.name" name="name" />

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 29: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Exception Handling• Handle the exceptions, wherever possible

– Printing the stack trace or logging is not handling – Choose an appropriate result name for exceptions in action

methods

• Redirect to an error page, for unhandled exceptions– Register the global exception settings in struts.xml

<global-results>

<result name="error">/error.jsp</result>

</global-results>

<global-exception-mappings>

<exception-mapping exception="java.lang.Exception"

result="error"/>

</global-exception-mappings>

– exception object is accessible from the OGNL stack• However, refrain from showing the exceptions as they are• View must give a message sensible to the end-user

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 30: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Dependency Injection• Always separate Struts and Service Layers

– Inject the Service objects into actions

• Spring is a industry-grade IoC container– Struts has a spring plug-in for dependency injection

• Let Spring inject service objects into Action– Register the Spring Listener: src/webapp/WEB-INF/web.xml

org.springframework.web.context.ContextLoaderListener

– Register the Beans: src/java/resources/applicationContext.xml<bean id=‘directory’ class=‘com.glarimy.SimpleDirectory’>

– Just declare the dependency on service objectspublic class DirectoryAction {

private Directory directory; // Do not initialize service objects

// Add getters and setters

public String execute(){

directory.update(); // Go and use the service object

return “SUCCESS”

}

}

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 31: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Agenda

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 32: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Unit Testing• Design for Testability

– Separate Service Layer from Struts– Let an action method make only one call to service layer– Delegate secondary concerns to Interceptors– Dependency Injection provides better testability

• Unit Testing Actions– Test the service layer independently– Mock the service layer while testing Actions– Call the setters and getters on Action– Check the result

• Unit Testing Validators & Convertors– No special set-up required

• Unit Testing Interceptors– Worth considering StrutsTestCase

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 33: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Unit Testing• Testing with just JUNIT and Mocking• Pass the parameters using setters• Verify the post-execute state using getters

import static org.mockito.Mockito.*;

import org.junit.Assert.*;

import com.opensymphony.xwork2.*;

public class DirectoryActionTest {

public void testAdd() throws Exception {

Directory dir = mock(Directory.class);

when(dir.search("Krishna")).thenReturn(9731423166L);

DirectoryAction action = new DirectoryAction();

action.setContact(new Contact("Krishna"));

action.setDirectory(dir);

assertEquals("Invalid result", "success", result);

assertTrue("Contact number is wrong",

9731423166L==action.getContact().getPhoneNumber);

}

}

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 34: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Unit Testing• Testing with StrutsTestCase using JUNIT3

import static org.mockito.Mockito.*;

import org.apache.struts2.StrutsTestCase;

import org.junit.Assert.*;

import com.opensymphony.xwork2.*;

public class DirectoryActionTest extends StrutsTestCase {

public void testAdd() throws Exception {

Directory dir = mock(Directory.class);

when(dir.search("Krishna")).thenReturn(9731423166L);

request.setParameter("contact.name", "Krishna");

ActionProxy actionProxy = getActionProxy("/find.action");

DirectoryAction action=(DirectoryAction) actionProxy.getAction();

assertNotNull("Null Action!", action);

action.setDirectory(dir);

String result = actionProxy.execute();

assertEquals("Invalid result", ActionSupport.SUCCESS, result);

assertTrue(“Contact number is wrong", 9731423166L==action.find());

}

}

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 35: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Unit Testing• Testing with StrutsTestCase using JUNIT4

import static org.mockito.Mockito.*;

import org.apache.struts2.StrutsJUnit4TestCase;

import org.junit.Assert.*;

import com.opensymphony.xwork2.*;

public class DirectoryActionTest extends StrutsJUunit4TestCase {

@Test

public void positiveTestcase() throws Exception {

Directory dir = mock(Directory.class);

when(dir.search("Krishna")).thenReturn(9731423166L);

request.setParameter("contact.name", "Krishna");

ActionProxy actionProxy = getActionProxy("/find.action");

DirectoryAction action=(DirectoryAction)actionProxy.getAction();

assertNotNull("Null Action!", action);

action.setDirectory(dir);

String result = actionProxy.execute();

assertEquals("Invalid result", ActionSupport.SUCCESS, result);

assertTrue(“Contact number is wrong", 9731423166L==action.find());

}

}

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 36: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Integration Testing• Testing with StrutsSpringJUnit4TestCase

– Spring injects the service objects– Spring can inject even the mock objects as well@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations = { "/applicationContext.xml" })

public class DirectoryActionJunit4Test extends

StrutsSpringJUnit4TestCase<DirectoryAction> {

@Test

public void testAdd() throws Exception {

request.setParameter("contact.name", "Krishna");

ActionProxy actionProxy = getActionProxy("/find.action");

DirectoryAction action=(DirectoryAction)actionProxy.getAction();

assertNotNull("Null Action!", action);

String result = actionProxy.execute();

assertEquals("Invalid result", ActionSupport.SUCCESS, result);

assertTrue(“Contact number is wrong", 9731423166L==action.find());

}

}

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 37: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Integration Testing• Testing Struts Environment

– Proxy tests the struts interceptors, validators and convertors– No special code required for setup, Just write the appropriate

assertions@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations = { "/applicationContext.xml" })

public class DirectoryActionJunit4Test extends

StrutsSpringJUnit4TestCase<DirectoryAction> {

@Test

public void testAdd() throws Exception {

request.setParameter("contact.name", "Krishna");

ActionProxy actionProxy = getActionProxy("/find.action");

DirectoryAction action=(DirectoryAction)actionProxy.getAction();

assertNotNull("Null Action!", action);

String result = actionProxy.execute();

assertTrue(action.getFeildErrors().size()==0);

assertEquals("Invalid result", ActionSupport.SUCCESS, result);

assertTrue("Contact number is wrong", 9731423166L==action.find());

}

}

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 38: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Summary

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Page 39: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com

Glarimy Technology Services

Page 40: G l a r I m y Presentation on Apache Struts 2.3 Krishna Mohan Koyya Proprietor & Principle Consultant Glarimy Technology Services | Benguluru | Bharat

Thank YouGlarimy Technology Services

Consulting & Corporate Training: http://www.glarimy.com

Weekend Executive Workshops: http://workshops.glarimy.com

Queries: [email protected]

Twitter: @Glarimy

G l a r i m y

© 2014, Glarimy. All rights reserved. http://www.glarimy.com