lecture 5 jstl, custom tags, maven

69
JEE - JSTL, Custom Tags and Maven Fahad R. Golra ECE Paris Ecole d'Ingénieurs - FRANCE

Upload: fahad-golra

Post on 17-Jul-2015

368 views

Category:

Software


1 download

TRANSCRIPT

Page 1: Lecture 5   JSTL, custom tags, maven

JEE - JSTL, Custom Tags and Maven

Fahad R. Golra

ECE Paris Ecole d'Ingénieurs - FRANCE

Page 2: Lecture 5   JSTL, custom tags, maven

Lecture 4 - JSTL, Custom Tags & Maven

• JSTL • MVC • Tag Libraries

• Custom Tags • Basic Tags with/without body • Attributes in custom tags

• Maven

2 JEE - JSTL, Custom Tags & Maven

Page 3: Lecture 5   JSTL, custom tags, maven

Best practices

• Modularity • Separation of concerns • Loose-coupling

• Abstraction • Encapsulation

• Reuse

3 JEE - JSTL, Custom Tags & Maven

Page 4: Lecture 5   JSTL, custom tags, maven

Web Application Development

• Model-View-Controller (MVC) Architecture

• Model • Business objects or domain objects • POJOs & JavaBeans

• View • Visual representation of model • JSP, JSF

• Controller • Navigation Flow & Model-view integration • Servlets

4 JEE - JSTL, Custom Tags & Maven

Page 5: Lecture 5   JSTL, custom tags, maven

JavaBeans [Model]

• Must follow JavaBeans Conventions

• Public Default Constructor (no parameter) • Accessor methods for a property p of Type T

• GET: public T getP() • SET: public void setP(T) • IS: public boolean isP()

• Persistence - Object Serialization

• JavaBean Conventions: http://docstore.mik.ua/orelly/java-ent/jnut/ch06_02.htm

5 JEE - JSTL, Custom Tags & Maven

Page 6: Lecture 5   JSTL, custom tags, maven

JavaBean Example (Recall)

package com.ece.jee;

public class PersonBean implements java.io.Serializable {

private static final long serialVersionUID = 1L;private String firstName = null;private String lastName = null;private int age = 0;

public PersonBean() {}

public String getFirstName() {return firstName;

}

public String getLastName() {return lastName;

}6

Page 7: Lecture 5   JSTL, custom tags, maven

JavaBean Example (Recall)

public int getAge() {return age;

}

public void setFirstName(String firstName) {this.firstName = firstName;

}

public void setLastName(String lastName) {this.lastName = lastName;

}

public void setAge(Integer age) {this.age = age;

}}

7

Page 8: Lecture 5   JSTL, custom tags, maven

JSP [View]

• Best practice goals • Minimal business logic • Reuse

• Design options • JSP + Standard Action Tags + JavaBeans • JSP + Standard Actions + JSTL + JavaBeans

8 JEE - JSTL, Custom Tags & Maven

Page 9: Lecture 5   JSTL, custom tags, maven

JSTL

• Conceptual extension to JSP Standard Actions • XML tags • Supports common structural tasks such as

iterations and conditions, tags for manipulating XML documents, internationalization tags, and SQL tags.

• JSP Standard Tag Library • Defined as Java Community Process • Custom Tag Library mechanism (discuss soon) • Available within JSP/Servlet containers

9 JEE - JSTL, Custom Tags & Maven

Page 10: Lecture 5   JSTL, custom tags, maven

JSTL Library

• JSTL is installed in most common Application Servers like JBoss, Glassfish etc.

• Note: Not provided by Tomcat

• Installation in Tomcat • Download from https://jstl.java.net/download.html • Drag the JSTL API & Implementation jars in the /WEB-INF/lib

folder of eclipse project.

10 JEE - JSTL, Custom Tags & Maven

Page 11: Lecture 5   JSTL, custom tags, maven

Example using scriptlet

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Count to 10 using JSP scriptlet</title></head><body>

<% for (int i = 1; i <= 10; i++) { %><%=i%><br /><% } %>

</body></html>

11

Page 12: Lecture 5   JSTL, custom tags, maven

Example using JSTL

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Count to 10 using JSTL</title><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %></head><body>

<c:forEach var="i" begin="1" end="10" step="1"><c:out value="${i}" /><br />

</c:forEach></body></html>

12

Page 13: Lecture 5   JSTL, custom tags, maven

The JSTL Tag Libraries

• Core Tags • Formatting Tags • SQL Tags • XML Tags • JSTL Functions

13 JEE - JSTL, Custom Tags & Maven

Page 14: Lecture 5   JSTL, custom tags, maven

Tag Library Prefix & URI

14 JEE - JSTL, Custom Tags & Maven

Library URI Prefix Core http://java.sun.com/jsp/jstl/core c XML Processing http://java.sun.com/jsp/jstl/xml x Formatting http://java.sun.com/jsp/jstl/fmt fmt Database Access http://java.sun.com/jsp/jstl/sql sql Functions http://java.sun.com/jsp/jstl/functions fn

<%@taglib prefix=�c��uri=�http://java.sun.com/jsp/jstl/core� %>

where to find the Java class or tag file that implements the custom action

which elements are part of a custom tag library

Page 15: Lecture 5   JSTL, custom tags, maven

Core Tag Library

• Contains structural tags that are essential to nearly all Web applications.

• Examples of core tag libraries include looping, expression evaluation, and basic input and output.

• Syntax:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

15 JEE - JSTL, Custom Tags & Maven

Page 16: Lecture 5   JSTL, custom tags, maven

Core Tag Library

16

Tag! Description !<c:out >! Like <%= ... >, but for expressions. !

<c:set >! Sets the result of an expression evaluation in a 'scope'!

<c:remove >! Removes a scoped variable (from a particular scope, if specified). !

<c:catch>! Catches any Throwable that occurs in its body and optionally exposes it.!

<c:if>! Simple conditional tag which evalutes its body if the supplied condition is true.!

<c:choose>! Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by <when> and <otherwise> !

<c:when>! Subtag of <choose> that includes its body if its condition evalutes to 'true'.!

Page 17: Lecture 5   JSTL, custom tags, maven

Core Tag Library

17

Tag! Description !<c:otherwise >! Subtag of <choose> that follows <when> tags and

runs only if all of the prior conditions evaluated to 'false'.!

<c:import>! Retrieves an absolute or relative URL and exposes its contents to either the page, a String in 'var', or a Reader in 'varReader'.!

<c:forEach >! The basic iteration tag, accepting many different collection types and supporting subsetting and other functionality .!

<c:forTokens>! Iterates over tokens, separated by the supplied delimeters.!

<c:param>! Adds a parameter to a containing 'import' tag's URL.!

<c:redirect >! Redirects to a new URL.!

<c:url>! Creates a URL with optional query parameters!

Page 18: Lecture 5   JSTL, custom tags, maven

• Catches an exception thrown by JSP elements in its body

• The exception can optionally be saved as a page scope variable

• Syntax: <c:catch> JSP elements </c:catch>

18 JEE - JSTL, Custom Tags & Maven

<c: catch>

Page 19: Lecture 5   JSTL, custom tags, maven

• only the first <c:when> action that evaluates to true is processed

• if no <c:when> evaluates to true <c:otherwise> is processed, if exists

• Syntax: <c:choose> 1 or more <c:when> tags and optionally a <c:otherwise> tag

</c:choose>

19 JEE - JSTL, Custom Tags & Maven

<c: choose>

Page 20: Lecture 5   JSTL, custom tags, maven

• Evaluates its body once for each element in a collection – java.util.Collection, java.util.Iterator, java.util.Enumeration,

java.util.Map – array of Objects or primitive types

• Syntax: <c:forEach items=“collection” [var=“var”] [varStatus=“varStatus”] [begin=“startIndex”] [end=“endIndex”] [step=“increment”]>

JSP elements

</c:forEach>

20 JEE - JSTL, Custom Tags & Maven

<c: forEach>

Page 21: Lecture 5   JSTL, custom tags, maven

• Evaluates its body once for each token n a string delimited by one of the delimiter characters

• Syntax: <c:forTokens items=“stringOfTokens” delims=“delimiters” [var=“var”] [varStatus=“varStatus”] [begin=“startIndex”] [end=“endIndex”] [step=“increment”]>

JSP elements

</c:forTokens>

21 JEE - JSTL, Custom Tags & Maven

<c: forTokens>

Page 22: Lecture 5   JSTL, custom tags, maven

• Evaluates its body only if the specified expression is true

• Syntax1: <c:if test=“booleanExpression” var=“var” [scope=“page|request|session|application”] />

• Syntax2: <c:if test=“booleanExpression” > JSP elements </c:if>

22 JEE - JSTL, Custom Tags & Maven

<c: if>

Page 23: Lecture 5   JSTL, custom tags, maven

• imports the content of an internal or external resource like <jsp:include> for internal resources however, allows the import of external resources as well (from a different application OR different web container)

• Syntax: <c:import url=“url” [context=“externalContext”] [var=“var”] [scope=“page|request|session|application”] [charEncoding=“charEncoding”]>

Optional <c:param> actions

</c:import>

23 JEE - JSTL, Custom Tags & Maven

<c: import>

Page 24: Lecture 5   JSTL, custom tags, maven

• Nested action in <c:import> <c:redirect> <c:url> to add a request parameter

• Syntax 1: <c:param name=“parameterName” value=“parameterValue” />

• Syntax 2: <c:param name=“parameterName”> parameterValue </c:param>

24 JEE - JSTL, Custom Tags & Maven

<c: param>

Page 25: Lecture 5   JSTL, custom tags, maven

• Adds the value of the evaluated expression to the response buffer

• Syntax 1: <c:out value=“expression” [excapeXml=“true|false”] [default=“defaultExpression”] />

• Syntax 2: <c:out value=“expression” [excapeXml=“true|false”]>

defaultExpression </c:out>

25 JEE - JSTL, Custom Tags & Maven

<c: out>

Page 26: Lecture 5   JSTL, custom tags, maven

• Sends a redirect response to a client telling it to make a new request for the specified resource

• Syntax 1: <c:redirect url=“url” [context=“externalContextPath”] />

• Syntax 2: <c:redirect url=“url” [context=“externalContextPath”] > <c:param> tags

</c:redirect>

26 JEE - JSTL, Custom Tags & Maven

<c: redirect>

Page 27: Lecture 5   JSTL, custom tags, maven

• removes a scoped variable • if no scope is specified the variable is removed from

the first scope it is specified • does nothing if the variable is not found

• Syntax: <c:remove var=“var” [scope=“page|request|session|application”] />

27 JEE - JSTL, Custom Tags & Maven

<c: remove>

Page 28: Lecture 5   JSTL, custom tags, maven

• sets a scoped variable or a property of a target object to the value of a given expression

• The target object must be of type java.util.Map or a Java Bean with a matching setter method

• Syntax 1: <c:set value=“expression” target=“beanOrMap” property=“propertyName” />

• Syntax 2: <c:set value=“expression” var=“var” scope=“page|request|session|application” />

28 JEE - JSTL, Custom Tags & Maven

<c: set>

Page 29: Lecture 5   JSTL, custom tags, maven

• applies encoding and conversion rules for a relative or absolute URL – URL encoding of parameters specified in <c:param> tags – context-relative path to server-relative path – add session Id path parameter for context- or page-relative

path • Syntax:

<c:url url=“url” [context=“externalContextPath”] [var=“var”] scope=“page|request|session|application” >

<c:param> actions

</c:url>

29 JEE - JSTL, Custom Tags & Maven

<c: url>

Page 30: Lecture 5   JSTL, custom tags, maven

Formatting Tag Library

• Contains tags that are used to parse data. • Some of these tags will parse data, such as dates,

differently based on the current locale.

• Syntax:

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

30 JEE - JSTL, Custom Tags & Maven

Page 31: Lecture 5   JSTL, custom tags, maven

Formatting Tag Library

31 JEE - JSTL, Custom Tags & Maven

Tag Description

<fmt:formatNumber> To render numerical value with specific precision or format.

<fmt:parseNumber> Parses the string representation of a number, currency, or percentage.

<fmt:formatDate> Formats a date and/or time using the supplied styles and pattern

<fmt:parseDate> Parses the string representation of a date and/or time

<fmt:bundle> Loads a resource bundle to be used by its tag body.

<fmt:setLocale> Stores the given locale in the locale configuration variable.

Page 32: Lecture 5   JSTL, custom tags, maven

Formatting Tag Library

32 JEE - JSTL, Custom Tags & Maven

Tag Description

<fmt:formatNumber> To render numerical value with specific precision or format.

<fmt:parseNumber> Parses the string representation of a number, currency, or percentage.

<fmt:formatDate> Formats a date and/or time using the supplied styles and pattern

<fmt:parseDate> Parses the string representation of a date and/or time

<fmt:bundle> Loads a resource bundle to be used by its tag body.

<fmt:setLocale> Stores the given locale in the locale configuration variable.

Page 33: Lecture 5   JSTL, custom tags, maven

Database Tag Library

• Contains tags that can be used to access SQL databases.

• These tags are normally used to create prototype programs only. This is because most programs will not handle database access directly from JSP pages.

• Syntax:

<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

33 JEE - JSTL, Custom Tags & Maven

Page 34: Lecture 5   JSTL, custom tags, maven

Database Tag Library

34 JEE - JSTL, Custom Tags & Maven

Tag Description

<sql:setDataSource> Creates a simple DataSource suitable only for prototyping

<sql:query> Executes the SQL query defined in its body or through the sql attribute.

<sql:update> Executes the SQL update defined in its body or through the sql attribute.

<sql:param> Sets a parameter in an SQL statement to the specified value.

<sql:dateParam> Sets a parameter in an SQL statement to the specified java.util.Date value.

<sql:transaction > Provides nested database action elements with a shared Connection, set up to execute all statements as one transaction.

Page 35: Lecture 5   JSTL, custom tags, maven

XML Tag Library

• Contains tags that can be used to access XML elements.

• XML is used in many Web applications, XML processing is an important feature of JSTL.

• Syntax:

<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

35 JEE - JSTL, Custom Tags & Maven

Page 36: Lecture 5   JSTL, custom tags, maven

XML Tag Library

36 JEE - JSTL, Custom Tags & Maven

Tag Description

<x:out> Like <%= ... >, but for XPath expressions.

<x:parse> Use to parse XML data specified either via an attribute or in the tag body.

<x:set > Sets a variable to the value of an XPath expression.

<x:if > Evaluates a test XPath expression and if it is true, it processes its body. If the test condition is false, the body is ignored.

<x:forEach> To loop over nodes in an XML document.

Page 37: Lecture 5   JSTL, custom tags, maven

XML Tag Library

37 JEE - JSTL, Custom Tags & Maven

Tag Description

<x:choose> Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by <when> and <otherwise>

<x:when > Subtag of <choose> that includes its body if its expression evalutes to 'true'

<x:otherwise > Subtag of <choose> that follows <when> tags and runs only if all of the prior conditions evaluated to 'false'

<x:transform > Applies an XSL transformation on a XML document

<x:param > Use along with the transform tag to set a parameter in the XSLT stylesheet

Page 38: Lecture 5   JSTL, custom tags, maven

JSTL Functions

• JSTL includes a number of standard functions, most of which are common string manipulation functions.

• Syntax:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

38 JEE - JSTL, Custom Tags & Maven

Page 39: Lecture 5   JSTL, custom tags, maven

JSTL Functions

39

Function Description fn:contains() Tests if an input string contains the specified substring.

fn:containsIgnoreCase() Tests if an input string contains the specified substring in a case insensitive way.

fn:endsWith() Tests if an input string ends with the specified suffix.

fn:escapeXml() Escapes characters that could be interpreted as XML markup.

fn:indexOf() Returns the index within a string of the first occurrence of a specified substring.

fn:join() Joins all elements of an array into a string.

fn:length() Returns the number of items in a collection, or the number of characters in a string.

fn:replace() Returns a string resulting from replacing in an input string all occurrences with a given string.

fn:split() Splits a string into an array of substrings.

Page 40: Lecture 5   JSTL, custom tags, maven

Custom Tags

• User defined JSP language elements (as opposed to standard tags)

• Encapsulates recurring tasks

• Distributed in a “custom made” tag library

40 JEE - JSTL, Custom Tags & Maven

Page 41: Lecture 5   JSTL, custom tags, maven

Why use custom tags?

• Custom tags can be used for

• Generating content for a JSP page

• Accessing a page’s JavaBeans

• Introducing new JavaBeans

• Introducing new scripting variables

• Using the strength of Java

41 JEE - JSTL, Custom Tags & Maven

Page 42: Lecture 5   JSTL, custom tags, maven

Custom Tag Syntax

• Like the standard actions, custom tags follow XML syntax conventions

<prefix:name attribute=”value” attribute=”value”/>

<prefix:name attribute=”value” attribute=”value”> body content </prefix:name>

42 JEE - JSTL, Custom Tags & Maven

Page 43: Lecture 5   JSTL, custom tags, maven

Custom tags architecture

• Custom tag architecture is made up of:

• Tag handler class • Defines tag's behaviour

• Tag library descriptor (TLD) • Maps XML elements to tag handler class

• JSP file (user of custom tags) • Uses tags

43 JEE - JSTL, Custom Tags & Maven

Page 44: Lecture 5   JSTL, custom tags, maven

Tag Handlers

• A tag handler class must implement one of the following interfaces: • javax.servlet.jsp.tagext.Tag

• javax.servlet.jsp.tagext.IterationTag

• javax.servlet.jsp.tagext.BodyTag

• Usually extends utility class • javax.servlet.jsp.tagext.TagSupport

• javax.servlet.jsp.tagext.BodyTagSupport

• javax.servlet.jsp.tagext.SimpleTagSupport

• Located in the same directory as servlet class files • Tag attributes are managed as JavaBeans properties (i.e., via getters

and setters)

44 JEE - JSTL, Custom Tags & Maven

Page 45: Lecture 5   JSTL, custom tags, maven

Tag Library Descriptor

• Defines tag syntax and maps tag names to handler classes

• Specifies tag attributes • Attribute names and optional types • Required vs. optional • Compile-time vs. run-time values

• Specifies tag variables (name, scope, etc.) • Declares tag library validator and lifecycle

event handlers, if any

45 JEE - JSTL, Custom Tags & Maven

Page 46: Lecture 5   JSTL, custom tags, maven

How to implement, use & deploy

• Four steps to follow: • write tag handlers • write so called tag library descriptor (TLD) file • package a set of tag handlers and TLD file into tag

library • write JSP pages that use these tags. Then you deploy

the tag library along with JSP pages.

• Syntax to use custom Tags in JSP is same as JSTL

<%@ taglib prefix="myprefix" uri=”myuri” %>

46 JEE - JSTL, Custom Tags & Maven

Page 47: Lecture 5   JSTL, custom tags, maven

Example: HelloTag.java

package com.ece.jee;

import java.io.IOException;

import javax.servlet.jsp.JspException;import javax.servlet.jsp.JspWriter;import javax.servlet.jsp.tagext.SimpleTagSupport;

public class HelloTag extends SimpleTagSupport {public void doTag() throws JspException, IOException {

JspWriter out = getJspContext().getOut();out.println("Hello, I am body-less Custom Tag!");

}}

47

Page 48: Lecture 5   JSTL, custom tags, maven

Example: custom.tld

<?xml version="1.0" encoding="UTF-8"?><taglib version="2.1"

xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" >

<tlib-version>1.0</tlib-version><short-name>ex</short-name><uri>http://jee.ece.com</uri>

<tag><name>Hello</name><tag-class>com.ece.jee.HelloTag</tag-class><body-content>empty</body-content>

</tag></taglib>

48

Page 49: Lecture 5   JSTL, custom tags, maven

Example: hello.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><%@ taglib prefix="ex" uri="http://jee.ece.com"%><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>A sample custom tag</title></head><body>

<ex:Hello /></body></html>

49

Page 50: Lecture 5   JSTL, custom tags, maven

Custom Tags with Body

• The <body-content> specifies what type of content is allowed

• empty - no nested content • sriptless - text, EL & JSP without sriptlets & expressions • JSP - Everything allowed in JSP • tagdependent - tag evaluates itself

<tag><name>Hello</name><tag-class>com.ece.jee.HelloTag</tag-class><body-content>empty</body-content>

</tag>

50 JEE - JSTL, Custom Tags & Maven

Page 51: Lecture 5   JSTL, custom tags, maven

Custom Tags with Body

package com.ece.jee;

import java.io.IOException;import java.io.StringWriter;

import javax.servlet.jsp.JspException;import javax.servlet.jsp.tagext.SimpleTagSupport;

public class HelloBodyTag extends SimpleTagSupport {StringWriter sw = new StringWriter();

public void doTag() throws JspException, IOException {getJspBody().invoke(sw);getJspContext().getOut().println(sw.toString());

}}

51

Page 52: Lecture 5   JSTL, custom tags, maven

Custom Tags with Body

• custom.tld <tag>

<name>HelloBody</name><tag-class>com.ece.jee.HelloBodyTag</tag-class><body-content>scriptless</body-content>

</tag>

• hello.jsp <body>

<ex:Hello /><br/><ex:HelloBody>Hello! I am a custom Tag with body</ex:HelloBody>

</body>

52

Page 53: Lecture 5   JSTL, custom tags, maven

Custom Tags with attributes

public class HelloAttributeTag extends TagSupport {

private static final long serialVersionUID = 1L;private String message;

public void setMessage(String msg) {this.message = msg;

}

@Overridepublic int doStartTag() throws JspException {

JspWriter out = pageContext.getOut();if (message != null) {

try {out.println(message);

} catch (IOException e) {e.printStackTrace();

}}

return SKIP_BODY;}

}53

Page 54: Lecture 5   JSTL, custom tags, maven

Custom Tags with attributes

• custom.tld <tag>

<name>HelloAttribute</name><tag-class>com.ece.jee.HelloAttributeTag</tag-class><body-content>scriptless</body-content><attribute>

<name>message</name></attribute>

</tag>

• hello.jsp ……..<br/>

<ex:HelloAttribute message="This is a custom tag with attribute" /></body>

54

Page 55: Lecture 5   JSTL, custom tags, maven

Maven

• Java tool • build • project management

• Homepage • http://maven.apache.org • Reference Documentation for Maven & core

Plugins

55 JEE - JSTL, Custom Tags & Maven

Page 56: Lecture 5   JSTL, custom tags, maven

Common issues

• Managing multiple jars • Dependencies and versions • Maintaining project structure • Building, publishing and deploying

56 JEE - JSTL, Custom Tags & Maven

Page 57: Lecture 5   JSTL, custom tags, maven

Project Object Model (POM)

• Describes a project • Name and Version • Artifact Type • Source Code Locations • Dependencies • Plugins • Profiles (Alternate build configurations)

57 JEE - JSTL, Custom Tags & Maven

Page 58: Lecture 5   JSTL, custom tags, maven

Maven Project

• Maven project is identified using (GAV): • groupID: Arbitrary project grouping identifier (no spaces or

colons) • Usually loosely based on Java package

• artfiactId: Name of project (no spaces or colons) • version: Version of project

<?xml version="1.0" encoding="UTF-8"?><project> <modelVersion>4.0.0</modelVersion> <groupId>com.ece.jee</groupId> <artifactId>mavenApp</artifactId> <version>1.0</version></project>

58 JEE - JSTL, Custom Tags & Maven

Page 59: Lecture 5   JSTL, custom tags, maven

Packaging

• Specifies the “build type” for the project • Example packaging types:

• pom, jar, war, ear, custom • Default is jar

<?xml version="1.0" encoding="UTF-8"?><project> <modelVersion>4.0.0</modelVersion> <groupId>com.ece.jee</groupId> <artifactId>mavenApp</artifactId> <version>1.0</version>

<packaging>jar</packaging></project>

59 JEE - JSTL, Custom Tags & Maven

Page 60: Lecture 5   JSTL, custom tags, maven

POM Inheritence

• POM files can inherit configuration • groupId, version • Project Config • Dependencies • Plugin configuration, etc.

<?xml version="1.0" encoding="UTF-8"?><project> <parent>

<groupId>com.ece.jee</groupId> <artifactId>mavenApp</artifactId> <version>1.0</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>maven-training</artifactId> <packaging>jar</packaging></project>

60 JEE - JSTL, Custom Tags & Maven

Page 61: Lecture 5   JSTL, custom tags, maven

Maven Conventions

• Maven project structural hierarchy • target: Default work directory • src: All project source files go in this directory • src/main: All sources that go into primary artifact • src/test: All sources contributing to testing project • src/main/java: All java source files • src/main/webapp: All web source files • src/main/resources: All non compiled source files • src/test/java: All java test source files • src/test/resources: All non compiled test source

61 JEE - JSTL, Custom Tags & Maven

Page 62: Lecture 5   JSTL, custom tags, maven

Build Lifecycle

• Default lifecycle phases • generate-sources/generate-resources • compile • test • package • integration-test (pre and post) • Install • deploy

• Specify the build phase you want and it runs previous phases automatically

62 JEE - JSTL, Custom Tags & Maven

Page 63: Lecture 5   JSTL, custom tags, maven

Maven Goals

• mvn install • Invokes generate* and compile, test, package, integration-

test, install • mvn clean

• Invokes just clean • mvn clean compile

• Clean old builds and execute generate*, compile • mvn compile install

• Invokes generate*, compile, test, integration-test, package, install

• mvn test clean • Invokes generate*, compile, test then cleans

63 JEE - JSTL, Custom Tags & Maven

Page 64: Lecture 5   JSTL, custom tags, maven

Project Dependencies

• Dependencies consist of: • GAV • Scope: compile, test, provided (default=compile) • Type: jar, pom, war, ear, zip (default=jar)

<project> ... <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> </dependencies></project>

64 JEE - JSTL, Custom Tags & Maven

Page 65: Lecture 5   JSTL, custom tags, maven

Dependencies & repositories

• Dependencies are downloaded from repositories using HTTP

• Downloaded dependencies are cached in a local repository • Usually found in ${user.home}/.m2/repository

• Repository follows a simple directory structure • {groupId}/{artifactId}/{version}/{artifactId}-

{version}.jar

65 JEE - JSTL, Custom Tags & Maven

Page 66: Lecture 5   JSTL, custom tags, maven

Defining a repository

• Can be inherited from parent • Repositories are keyed by id • Downloading snapshots can be controlled

<project> ... <repositories> <repository> <id>main-repo</id> <name>ECE main repository</name> <url>http://com.ece.jee/content/groups/main-repo</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> </project>

66 JEE - JSTL, Custom Tags & Maven

Page 67: Lecture 5   JSTL, custom tags, maven

Maven Eclipse Plugin

• M2Eclipse provides: • Launching Maven builds from within Eclipse • Quick search dependencies • Automatically downloading required dependencies • Managing Maven dependencies

• Installation update site http://download.eclipse.org/technology/m2e/releases

67 JEE - JSTL, Custom Tags & Maven

Page 68: Lecture 5   JSTL, custom tags, maven

68 JEE - JSTL, Custom Tags & Maven

Page 69: Lecture 5   JSTL, custom tags, maven

References

• JSTLExample inspired from http://www.journaldev.com/2090/jstl-tutorial-with-examples-jstl-core-tags

• Further Reading: • http://docs.oracle.com/javaee/5/tutorial/doc/bnakc.html

69