Introduction

JAVA EE

Java EE is an open, standards-based development and deployment platform for creating distributed, transactional, reliable, secure, multitiered, web-based, server-centric, component-based enterprise applications

JAVA EE Version

Getting Started

Hello World

In this section you can see an example of HelloWorld program using Java Servlets.


// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class
public class HelloWorld extends HttpServlet {


  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // Set response content type
      response.setContentType("text/html");

      // Actual logic goes here.
      PrintWriter out = response.getWriter();
      out.println("<h1> Hello From Java!</h1>");
  }

}

To run this program on Netbeans just click on the Run button and it automatically opens the default browser.

Servlet

Session

Headers


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ModHelloWorld extends HttpServlet{
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
                response.setHeader("Location", "www.webtek.com");
                response.setContentType("text/html");
                PrintWriter pw = response.getWriter();
                pw.println("<html><head><title>Hello Webtek</title></head><body>");
                pw.println("<h1>");
                pw.println(getInitParameter("message"));
                pw.println("</h1>");
                pw.println("</body></html>");
                pw.close();
        }
}
    
        

Redirection


            import java.io.*;
            import java.sql.Date;
            import java.util.*;
            import javax.servlet.*;
            import javax.servlet.http.*;

            public class Redirect extends HttpServlet{

              public void doGet(HttpServletRequest request,
                                HttpServletResponse response)
                        throws ServletException, IOException
              {
                  response.setContentType("text/html");

                  String site = new String("http://www.webtek.com");

                  response.setStatus(response.SC_MOVED_TEMPORARILY);
                  response.setHeader("Location", site);    
                }
            } 
        

JSP

JSP are essentially Servlets, they are created for programmers, since writing html code in Servlets is quite tedious and impractical, the Java engineers made JSPs (Java Server Pages) which can contain both HTML and java code altogether. Upon execution JSPs go back with their original form - as a Servlet

JSP pages

  • are webpages that contain both static and dynamic contents.
  • static contents refer to page contents that are written in html, xml, etc.
  • dynamic contents of the page are constructed using jsp elements.

JSP page life cycle

  • JSP page translation and compilation - a code for writing out data into response stream is generated from translating the static data.
  • Classloading - classloader loads the classfile.
  • Instantiation - generated servlet creates object.
  • Initialzation - container invokes jsp method jspInit().
  • Request processing - container invokes jsp method _jspService(), request and response objects are passed.
  • Destroy - container calls jsp method jspDestroy() to remove the servlet from JSP page.
  • Execution - page directives are used to control executions of various JSP pages.
    • Buffering - automatically buffers output written to response object upon JSP page execution.
    • JSP page Error Handling - if specified, exception occurences causes container to forward control to error page.

Creating JSP page

  • create an html file having jsp contents enclosed in <% %>
  • save the file with .jsp extension
  • example
    <% out.print("hello world"); %>
  • Creating Static Content - simply write the content in html, xml, etc.
  • Response and Page Encoding
    • specify response encoding using contentType attribute.
      <%@ page contentType="text/html; charset=UTF-8" %>
    • use page directive to set page source encoding.
      <%@ page pageEncoding="UTF-8" %>
  • Creating Dynamic Content
    • Using Implicit Objects
      • implicit objects are web container-created objects containing request, page, session or application-related information.
    • Using Application-specific Objects
      • objects created in java.
  • Custom Tags
    • custom tags refer to user-defined elements encapsulating recurring tasks specified.
    • written using JSP language.
    • syntax for custom tags
        <prefix:tag attribute="value" ... attrributeName="value" />
      <prefix:tag attribute="value" ... attributeName="value"> </prefix:tag> 
      • prefix refers to tags for the library
      • attribute and attributeName refers to attributes that can modify tag behavior.

Running JSP page

  • create an html file having jsp contents enclosed in <% %>
  • save the file with .jsp extension
  • start server
  • copy or move the file to a folder in the server.
  • check if it is working properly by visiting its URL in the server using a browser.

JavaServer Pages Standard Tag Library (JSTL)

Definition

  • JavaServer Pages Standard Tag Library contains useful JSP tags for common JSP application functionalities.
  • JSTL supports common structural tasks such as conditions and iterations as well as XML document manipulation, tag internationalization, and tags for SQL.

Classification of tags

  • Core Tags
    • group of JSTL tags most commonly used
    • tag descriptions
      • <c:out> - displays an expression's result.
      • <c:set> - sets expression evaluation result.
      • <c:remove> - removes a variable.
      • <c:catch> - catches throws.
      • <c:if> - conditional tag that simply evaluates if specified condition is true.
      • <c:choose> - similar to switch in java.
      • <c:when> - similar to case in java switch statement.
      • <c:otherwise> - works somehow similar to else for choose tag.
      • <c:import> - includes contents from specified URL.
      • <c:forEach> - common iteration used for jstl.
      • <c:forTokens> - iterates over strings called tokens which are separated by delimiters.
      • <c:param> - adds parameters to import tag.
      • <c:redirect> - redirects to URL specified.
      • <c:url> - creates URL.
  • Formatting Tags
    • group of JSTL tags for formatting text displays and some variables.
    • tag descriptions
      • <fmt:formatNumber> - formats number to specified format.
      • <fmt:parseNumber> - parses string specified as numbers.
      • <fmt:formatDate> - formats date specified.
      • <fmt:parseDate> - parses date using specified pattern.
      • <fmt:setLocale> - stores given locale.
      • <fmt:timeZone> - specify timezone for time formatting.
      • <fmt:setTimeZone> - stores gien timezone.
      • <fmt:message> - displays internationalized message.
      • <fmt:requestEncoding> - sets encoding of request character.
  • SQL Tags
    • group of JSTL tags for SQL.
    • tag descriptions
      • <sql:setDataSource> - creates data source.
      • <sql:query> - executes query specified.
      • <sql:update> - update tables in database.
      • <sql:param> - sets SQL statement parameters.
      • <sql:dateParam> - sets specified date value in an SQL parameter.
      • <sql:transaction> - nested database action which can be executed as a single transaction.
  • XML tages
    • group of JSTL tags for manipulating XML documents.
    • tags
      • <x:out>
      • <x:parse>
      • <x:set>
      • <x:if>
      • <x:forEach>
      • <x:choose>
      • <x:when>
      • <x:otherwise>
      • <x:transform>
      • <x:param>

JSTL Functions

  • common JSTL functions.
  • function descriptions
    • fn:contaoins() - check if contains specified string.
    • fn:containseIgnoreCase() - check if contains specified string regardless of case.
    • fn:endsWith() - checks if ends with specified suffix.
    • fn:escapeXml() - escapes characters that can be misinterpreted as xml markup
    • fn:indexOf() - returns index of first occurence of string specified
    • fn:join() - joins array elements into a single string
    • fn:length() - returns number of items in an array or characters in a string
    • fn:replace() - returns string result from replacing a string using specified string
    • fn:split() - splits string to array of substrings using delimiter specified
    • fn:startsWith() - tests if inputs starts with specified prefix.
    • fn:substring() - returns substring of a string
    • fn:substringAfter() - returns string following a specific substring
    • fn:substringBefore - returns string before specified substring
    • fn:toLowerCase() - converts string to lower case
    • fn:toUpperCase() - converts substring to lower case
    • fn:trim - remove white spaces from string.

Expression Language

  • uses$ { }
  • Expression Language (EL) - enables communiation between presentation and application layer
  • Immediate and Deferred Evaluation
    • Immediate Evaluation - read-only-valued expressions that use ${} are immediately evaluated.
      example:
      <fmt:formatNumber value="${sample.count.number}"/>
  • Immediate and Deferred Evaluation
    • Deferred Evaluation - expressions that use #{expr} can be evaluated at later phases of the page. expr specifies the expression.
      example:
      <h:sampleText id="sample" value="#{sample.example}" />
  • Implicit EL objects
    • pageContext
    • pageScope
    • requestScope
    • sessionScope
    • applicationScope
    • param, paramValues
    • header, headevalues
    • cookie
    • initparam

Frameworks

References