jedi course notes-mobile application devt-lesson07-j2me and enterprise computing

Upload: meljun-cortes-mbampa

Post on 04-Apr-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    1/28

    J.E.D.I.

    J2ME and Enterprise Computing

    1 Objectives

    In this section, we will be learning how to write Servlets, use JSP and JSTL, access adatabase using JDBC and create and parse XML documents.

    After finishing this lesson, the student should be able to:

    write simple Servlets

    write simple JavaServer Pages (JSP) using JSTL

    write JSTL code using Expression Language (EL)

    access a database using JDBC

    generate XML

    parse the XML on the Mobile client

    2 Servlets

    A servlet is a server-side Java class for implementing a request-response typetransaction. With servlets, Java provides a better and portable alternative to CGI(Common Gateway Interface) scripts. Compared to CGI scripts (written in Perl, sheelscripts, or other scripting languages), Java servlets provide a scalable, platformdependent technology that deliver dynamic content.

    A servlet has two methods for processing a request, the doGet() and doPost() methods.These methods are called when the web client (browser) issues a "GET" or "POST"command. These methods have identical parameters. These parameters are normallyhanded off to a common method so that both GET and POST request are handled the

    same way.

    protected void doGet(

    HttpServletRequest request,

    HttpServletResponse response)

    throws ServletException, IOException {

    // process request ...

    }

    Mobile Application Development 1

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    2/28

    J.E.D.I.

    protected void doPost(

    HttpServletRequest request,

    HttpServletResponse response)

    throws ServletException, IOException {

    // process request ...

    }

    import java.io.*;

    import java.net.*;

    import javax.servlet.*;import javax.servlet.http.*;

    public class SampleServlet extends HttpServlet {

    protected void processRequest(

    HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

    response.setContentType("text/html;charset=UTF-8");

    PrintWriter out = response.getWriter();

    out.println("");

    out.println("");

    out.println("Servlet SampleServlet");

    out.println("");

    out.println("");

    out.println("Servlet SampleServlet at "

    + request.getContextPath () + "");

    out.println("");

    out.println("");

    out.close();

    }

    Mobile Application Development 2

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    3/28

    J.E.D.I.

    protected void doGet(

    HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

    processRequest(request, response);

    }

    protected void doPost(

    HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

    processRequest(request, response);}

    /** Returns a short description of the servlet.

    */

    public String getServletInfo() {

    return "Short description";

    }

    }

    Mobile Application Development 3

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    4/28

    J.E.D.I.

    To create a new Web Project, click File -> New Project... ->Web: Web Application. Selectand input a name for your project and click finish.

    Mobile Application Development 4

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    5/28

    J.E.D.I.

    To create a new Servlet, click on File -> New File.. -> Web: Servlet

    Mobile Application Development 5

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    6/28

    J.E.D.I.

    3 JSP/JSTL

    The primary goal of the JavaServer Pages Standard Tag Library (JSTL) is to help authorssimplify scripting on JSP pages. JSTL briges the gap between programmers and (non-programmer) page authors by providing a simple expression language for JSP pages.

    Aside from the expression language support actions and crontrol flow actions, JSTL alsoprovides functionality for accessing URL-based resources, internationalization andnumber and date formatting, database access and XML processing.

    JTSL is composed of several tag libraries, grouped by functional area.

    Area Prefix URI Example code snippet

    core c http://java.sun.com/jstl/core

    I18N formatting fmt http://java.sun.com/jstl/fmt

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    7/28

    J.E.D.I.

    pop-up menu:

    2. Select "JSTL 1.1" and click "Add Library". "JSTL 1.1 standard.jar" and "STL

    1.1 jstl.jar" would be added to your projects library.

    Mobile Application Development 7

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    8/28

    J.E.D.I.

    3.2 Hello, world!

    A JSP page is just an HTML page with codes and/or tags. Here is a very minimal JSPpage. Save this code snippet to hello.jsp under the Web Pages directory, right click onthe filename and choose "Run File" to display the output of this JSP page in your webbrowser:

    Mobile Application Development 8

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    9/28

    J.E.D.I.

    3.3 Transferring control from Servlet to JSP

    import java.io.*;

    import java.net.*;

    import javax.servlet.*;

    import javax.servlet.http.*;

    public class SampleServlet2 extends HttpServlet {

    /** Processes requests for both HTTP GET

    * and POST methods.

    * @param request servlet request

    * @param response servlet response

    */

    protected void processRequest(

    HttpServletRequest request,

    HttpServletResponse response)

    throws ServletException, IOException {

    String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday"};

    request.setAttribute("days", days);

    Mobile Application Development 9

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    10/28

    J.E.D.I.

    request.setAttribute("message", "hello, world!");

    RequestDispatcher dispatcher = request.

    getRequestDispatcher("/control.jsp");

    // transfer control to JSP page

    if (dispatcher != null)

    dispatcher.forward(request, response);

    }

    /** Handles the HTTP GET method.

    * @param request servlet request* @param response servlet response

    */

    protected void doGet(

    HttpServletRequest request,

    HttpServletResponse response)

    throws ServletException, IOException {

    processRequest(request, response);

    }

    /** Handles the HTTP POST method.

    * @param request servlet request

    * @param response servlet response

    */

    protected void doPost(

    HttpServletRequest request,

    HttpServletResponse response)

    throws ServletException, IOException {

    processRequest(request, response);

    }

    /** Returns a short description of the servlet.

    */

    public String getServletInfo() {

    Mobile Application Development 10

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    11/28

    J.E.D.I.

    return "Short description";

    }

    }

    3.4 Expression Language

    3.4.1 Accessing Variables, Properties and Collections

    In order to access a variable, the syntax is: ${var}

    Example: output the value of the variable username

    JSTL unifies access to Java bean properties and collection values. The expressionvarX.varY is equivalent to varX[varY] in JSTL. The expression varX.varY (or varX[varY])would evaluate depending on the type of varX:

    Mobile Application Development 11

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    12/28

    J.E.D.I.

    1. If varX is a JavaBean: varY would be converted to String. If varY is a readableproperty of varX, it would return the result of the getter call: varX.getVarY()

    2. If varX is a List: varY is coerced to int. Evaluates to: varX.get(varY)

    3. If varX is an array: varY is coerced to int. Evaluates to: Array.get(varX, varY)

    4. If varX is a Map: Evaluates to: varX.get(varY)

    Variables can have page, request, session and application scope. The expressionlanguage would look for the identifier in these scopes. If the identifier is not found, nullis returned.

    3.4.2 Implicit Objects

    JSTL automatically initializes several Map variables with values from different sources.These variables are available to the JSP pages without any initialization from the user.For example, the variable param contains mappings of parameters' names and valuesfrom the request. These names and values (param) are from HTML form submissionssubmitted either via HTTP GET or POST methods.

    Implicit Object Contents

    pageScope a Map containing a mapping of page-scoped attibute names to their values

    requestScope a Map containing a mapping of request-scoped attibute names to their values

    sessionScope a Map containing a mapping of session-scoped attibute names to their values

    applicationScope a Map containing a mapping of application-scoped attibute names to theirvalues

    param a Map containing a mapping of parameternames to its parameter value (String).equivalent toServletRequst.getParameter(String)

    header a Map containing a mapping of headernames to a its value (String). Equivalent toServletRequst.getHeader(String)

    cookie a Map containing a mapping of cookienames to their cookie values. Equivalent toHttpServletRequest.getCookie(String)

    3.4.3 Operators

    Mobile Application Development 12

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    13/28

    J.E.D.I.

    The JSTL Expression Language (EL) supports relational, arithmetic and logical operators.

    The supported relational operators are:

    == (or eq)

    != (or ne)

    < (or lt)

    > (or gt)

    = (or ge)

    The logical operators are:

    && (or and)

    || or (or)

    ! (or not)

    And the arithmetic operators of EL are:

    + (addition)

    - (subtraction)

    * (multiplication)

    / (division)

    % or mod (remainder or modulus)

    The additional empty operator is very useful for testing null or empty values.

    No username

    3.4.4 Exceptions and Default Values

    To simplify JSP pages, simple errors will not generate exceptions. Displaying a variablewith a null value will simply display "(null)" instead of generating a

    NullPointerException.

    Username:

    Mobile Application Development 13

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    14/28

    J.E.D.I.

    Undefined variables used in expressions take 0 (zero) as their default value. Thisexpression would evaluate to 1 if the parameter "start" is not set:

    3.5 core tag library

    3.5.1 c:out

    The c:out tag evaluates an expression and outputs its result.

    Syntax:

    vvalue"

    Name Dynamic Required Type Description

    value yes yes Object The expression to be evaluated

    escapeXml yes no boolean If true, the characters , &, ' and "are converted to their character entitycodes (eg: > converts to >). Defaultvalue is true.

    default yes no Object The default value if the result value isnull

    Examples:

    Rows:

    Description:

    Mobile Application Development 14

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    15/28

    J.E.D.I.

    3.5.2 c:set

    Sets the value of a (scoped) variable.

    Syntax:

    Name Dynamic Required Type Description

    value yes yes Object The expression to be evaluated

    var no yes String The name of the exported variable thatwill hold the value of the expression. Thetype of the variable follows the type ofthe result of the expression

    scope no no String The scope of var

    Example:

    3.5.3 c:remove

    Removes (undefines) a (scoped) variable

    Syntax:

    Name Dynamic Required Type Description

    var no yes String The name of the variable to be deleted

    scope no no String The scope of var

    Example:

    Mobile Application Development 15

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    16/28

    J.E.D.I.

    Mobile Application Development 16

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    17/28

    J.E.D.I.

    3.5.4 c:if

    Conditional evaluation. Will process the body content if the test condition evaluates totrue.

    Syntax:

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    18/28

    J.E.D.I.

    body content

    Name Dynamic Required Type Description

    test yes yes boolean The test condition that determines if thebody content should be processed.

    Example:

    Male

    Female

    Unknown

    3.5.6 c:forEach

    c:forEach iterates over the contents of a collection. The collection can be any of thesubclasses of java.util.Collection and java.util.Map. Arrays of objects and primitive typesare also supported. A String of comma separated values ("True,False") can also be usedfor the iteration. As long as there are items in the collection, the body content isprocessed.

    c:forEach can also be used to iterated for a fixed number of times.

    The varStatus is of type javax.servlet.jsp.jstl.core.LoopTagStatus.It has the properties index (index of the current iteration, zero-based) and count (the count of the current iteration, one-based, eg. if the begin index is20, the end index is 80 and the step is 10, the count would be 1,2,3,4,5,6,7). Theboolean properties first and last denote if the currrent iteration is the first or last,respectively. There are also the begin, end and step properties which hold the values ofthe begin, end and step parameters of the c:forEach loop.

    Syntax:

    [vvarName"]icollection"[varStatusvarStatusName"][begin"][eend"][step"]

    Mobile Application Development 18

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    19/28

    J.E.D.I.

    body content

    or

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    20/28

    J.E.D.I.

    Syntax:

    istringOfTokens"ddelimiters"[vvarName"][varStatus="varStatusName" ][begin"]end"]step" ]body content

    Name Dynamic Required Type Description

    var no no varies The name of the exported variable forevery iteration/token

    items yes yes String String of tokens

    delims yes yes String Delimiters, characters that separatesthe tokens in the items String

    varStatus no no String The name of the exported variable forthe status of the operation. Theobject exported is of type javax.servlet.jsp.jstl

    begin yes no int beginning index (zero-based) of theiteration. If not specified, iterationwill begin with the first token.

    end yes no int end index of the iteration

    step yes no int The loop will only process every"step" tokens of the iteration, startingwith the first token

    Example:

    Mobile Application Development 20

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    21/28

    J.E.D.I.

    4 JDBC

    In this section, we will be discussing how to persist data or objects. For this functionality,we will need a (relational) database. The JDBC API lets you perform queries and updateson a database. Before we can use JDBC, we need to make sure that three prerequisitesare met:

    JDBC library - included in the JDK

    The Database Server - we will use MySQL (mysql.com)

    JDBC Driver - comes with your DBMS, install the jar mysql-connector-java-3.x.x-bin.jar for JDBC 3.0

    The table used in these examples can be recreated using this SQL CREATE AND INSERTstatements:

    CREATE TABLE `task` (

    `id` bigint(20) unsigned NOT NULL auto_increment,

    `task` varchar(128) NOT NULL default '',

    `duration` int(11) NOT NULL default '0',

    `assignedTo` varchar(64) NOT NULL default '',

    `status` char(1) NOT NULL default '',

    PRIMARY KEY (`id`)

    );

    INSERT INTO `task`

    (`id`, `task`, `duration`, `assignedTo`, `status`)

    VALUES

    (1,'connect to database',2,'alex','0'),

    (2,'list table rows',4,'alex','0'),

    Mobile Application Development 21

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    22/28

    J.E.D.I.

    (3,'update row',8,'you','0');

    4.1 Loading the Driver

    To use the JDBC driver for a particular database, we have to load it usingClass.forName(). The driver name is dependent on the database driver that we will beloading. In our case, we are loading the mysql jdbc driver:

    String driver = "com.mysql.jdbc.Driver";

    Class.forName(driver);

    4.2 Establishing a Connection

    To establish a connection to the database, we will need the URL to the database. We willalso need access to that database. A working username and password are required toestablish a connection.

    String url = "jdbc:mysql://localhost:3306/jedi";

    String username = "root";

    String password = "password";

    conn = DriverManager.getConnection(url, username, password);

    4.3 Executing SQL queries

    executeQuery returns a ResultSet object. To iterate on all the rows returned by thequery, we use the next() method. There are several methods that return the columns ofthe current row, each for a specific datatype. In this example, we retrieved String andinteger variables using getString() and getInt():

    statement = conn.createStatement();

    String query = "SELECT task,duration,duration FROM task";

    ResultSet rs = statement.executeQuery(query);

    out.println("");

    out.println("");

    out.println("Task");

    out.println("Duration");

    out.println("Assigned to");

    Mobile Application Development 22

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    23/28

    J.E.D.I.

    out.println("");

    while (rs.next()) {

    String task = rs.getString("task");

    int duration = rs.getInt("duration");

    String assignedTo = rs.getString("assignedTo");

    out.println("");

    out.println("" + task + "");

    out.println("" + duration + "");

    out.println("" + duration + "");

    out.println("");

    }

    out.println("");

    4.4 Updating tables

    To update tables (UPDATE, INSERT, DELETE), the Statement.executeUpdate() is used.

    String task = (String) request.getParameter("task");

    String duration = (String) request.getParameter("duration");

    String assignedTo = (String) request.getParameter("assignedTo");

    String status = (String) request.getParameter("status");

    Long id = new Long(idStr);

    String updateQuery;

    ResultSet rs = dao.query("SELECT id from task WHERE id ='" + id + "'");

    if (rs.next()){

    Mobile Application Development 23

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    24/28

    J.E.D.I.

    // update task entry

    updateQuery = "UPDATE task SET"

    + " task='" + (task != null? task:"") + "'"

    + ",duration='" + (duration != null ? duration:"") + "'"

    + ",assignedTo='" + (assignedTo != null ? assignedTo:"") + "'"

    + ",status='" + (status != null ? status:"") + "'"

    + " WHERE id=" + id;

    } else {

    // new task entry

    updateQuery = "INSERT INTO task (task, duration, assignedTo, status) "

    + "VALUES ("

    + "'"+task+"',"+ "'"+duration+"',"

    + "'"+assignedTo+"',"

    + "'"+status+"'"

    + ")";

    }

    statement.executeUpdate(updateQuery);

    5 XML

    XML, the eXtensible Markup Language, is a text-based markup language. With XML, youcan present data in a structured text document.

    Just like HTML, XML tags are defined using the angled brackets: . Unlike HTMLthough, XML is easier to parse. An XML document is structured, with entities forming atree structure.

    You can use any appropriate tag name that you like, as long as all the applications usingthe XML document will use the same tag names. Tags can contain attributes. In theexample below, the first "task" has an "id" attribute of "1" while the second "task" has an"id" attribute of "2".

    connect to database

    Mobile Application Development 24

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    25/28

    J.E.D.I.

    2

    alex

    0

    list table rows

    4

    alex

    4

    5.1 Parsing XML

    As of the time of this document's writing, there have been no standard libraries definedby a JCP process for parsing XML in CLDC. However, there are several XML libraries thatwork with CLDC. One of them is NanoXML (http://nanoxml.sourceforge.net/). Theoriginal version of NanoXML does not work with CLDC. You must download the sourcecode of the modified version that works with CLDC athttp://www.ericgiguere.com/nanoxml and include it in your mobile project under thepackage name "nanoxml".

    import java.io.*;

    import java.util.*;

    import nanoxml.*;

    ...

    public String[] parseXml(String xml){

    kXMLElement root = new kXMLElement();

    try {

    root.parseString(xml);

    Vector taskList = root.getChildren();

    Vector items = new Vector();

    for (int i=0; i

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    26/28

    J.E.D.I.

    String tagName = task.getTagName();

    if (tagName != null && tagName.equalsIgnoreCase("task")){

    Vector taskProperties = task.getChildren();

    String[] fieldNames = {

    "name", "duration", "assignedTo", "status"

    };

    String[] fields = new String[fieldNames.length];

    String id = task.getProperty("id", "0");

    for (int j=0; j

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    27/28

    J.E.D.I.

    6 Exercises

    6.1 Headers in a table w/ alternating row color

    Write a JSTL code that will iterate over the implicit Map "header" and display the headerkey/name and value in an HTML table. Odd numbered rows should have the backgroundcolor of lightyellow (...). Note that the varStatus index startwith zero. Note that the (header) Map has the property "key" and "value".

    Sample Output:

    accept-encoding

    gzip,deflate

    connection keep-alive

    accept-language

    en-us,en;q=0.5

    host localhost:8084

    accept-charset ISO-8859-1,utf-8;q=0.7,*;q=0.7

    user-agentMozilla/5.0 (Linux; U; Linux v0.99; en-US) Gecko/20050511Firefox/1.2.3

    accept

    text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/

    plain;q=0.8,image/png,*/*;q=0.5

    keep-alive 300

    6.2 Servlets and JSP

    Create a servlet and JSTL application that will display in XML format an array of objects.The object properties are: name and ip address. The Java class should look like this:

    public class Host {private String name;

    private String ip;

    public Host(String name, String ip) {

    this.name = name;

    this.ip = ip;

    }

    Mobile Application Development 27

  • 7/29/2019 JEDI Course Notes-Mobile Application Devt-Lesson07-J2ME and Enterprise Computing

    28/28

    J.E.D.I.

    public String getName(){ return(name); }

    public String getIp(){ return(ip); }

    public void setName(String name){ this.name = name; }

    public void setIp(String ip){ this.ip = ip; }

    }

    You should pass a static array of Hosts from the Servlet into the JSP usingrequest.setAttribute().

    Host[] hosts = {

    new Host("localhost", "127.0.0.1"),

    new Host("java.sun.com", "1.2.3.4")

    };

    The XML output should look like this:

    127.0.0.1

    1.2.3.4

    Mobile Application Development 28