CS3220: Web and Internet Programming

Lecture 4: Introduction to Back-End Development with J2EE


Michael Hsu

CSULA

Getting the Lecture Slides and Code Examples:


git clone https://github.com/mhsu0020/CSULA-CS3220-Fall2016.git
            

Getting Subsequent Updates:


git pull
            

Recall Dynamic Web Diagram from Last Week

The past two weeks we focued on client side development. The next couple of weeks we will focus on server side development (you will still use client side concepts.)

Table of Contents (Click to Jump to Section)

Introduction to Back-End Development

  • Three basic components: server, application, and datahbase
  • server: The remote computer that the browser talks to, can be an actual physical server or virtual
  • application: The web application running on the server. It handles user requests, retrieves information from the database(depends on usecase), and returns a response to the client request.
    We will be writing web applications for this class using Java
  • database: The DBMS (database management system), or database, is an application that can run on the same server as the web application or a seperate server. It stores information, allows clients to query and update information as needed.
    We will be using MySQL and MongoDB for this class.

Common components of an dynamic web application include controllers, for controlling routing of user requests and responses; models, for data modeling (think java data objects); and views, usually some kind of templating language that allows generation of HTML code using model

Popular Back-End Frameworks

  • PHP
    PHP is a server-side scripting language. Powers Wordpress, used by Facebook and many others. Zend Framework and Laravel are popular PHP frameworks
  • ASP.NET
    .NET Framework (C# and many other languages) based technology by Microsoft
  • Ruby on Rails(Rails)
    Ruby-based framework that is often used by new companies. Easy to get up and running, but rather "opinionated"
  • Django
    the most popular Python web framework, requires some effort to setup. A popular lightweight alternative is Flask
  • Node.js with Express
    hottest new kid on the block. JavaScript web framework and probably requires the least amount of code to get up and running
  • Spring Framework
    popular and monstrous Java framework with many modules. The web modules are based on J2EE

Why J2EE?

  • We picked J2EE for this class for the following reasons:
    • Our department uses Java for Intro to Programming
    • A standard framework that is relatively stable and documented. Many of the "bleeding edge" frameworks have major changes between newer versions.
    • Still fairly popular in the enterprise sector. Chances are you will work on a Java-based web app if you work at an established company
    • Large amount of legay enterprise apps are done in J2EE
    • Web frameworks, concept wise, are more or less the same with the request-response model. You should able to learn other web frameworks on your own fairly quickly

J2EE Intro

  • J2EE Wiki
  • Stands for Java Platform, Enterprise Edition. Also known as Java EE
  • Provides an API and runtime environment for writing enterprise applications
  • The J2EE API defines standard interfaces that application servers can implement
  • We will be using Apache Tomcat, a popular application server that implements several Java EE specs
  • APIs that we will be touching on today:
  • javax/servlet: defines a set of APIs to handle HTTP requests. Include the JavaServer Pages(JSP) specs
  • javax/el: defines the Expression Language, used for binding Java objects in JSPs to generate HTML content

The JSP Model 2 Architecture

  • Today we will be creating Java Servlets, JSPs, and Java data objects
  • The "Server" box represents the J2EE app that we create and run on Tomcat

Components of a J2EE Application

  • Compiled Java classes (.class files) Servlets, beans, filters, ...
  • Addtional Java libraries (.jar files)
  • JavaServer Pages (JSPs)
  • Static resources HTML, CSS, images, ...
  • Metadata files web.xml, ...

Hello World Servlet

http://localhost:8080/HelloExample/HelloWorld


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

//Handles the resource path HelloWorld
@WebServlet( "/HelloWorld" )
public class HelloWorld extends HttpServlet {
    public void doGet( HttpServletRequest request,
			  HttpServletResponse response )
        throws ServletExceptoin, IOException
    {
        PrintWriter out = response.getWriter();
        out.println( "Hello World" );
    }
}
            

Some observations:

  • Inherits from HttpServlet. No main method
  • The doGet method handles HTTP GET requests for this Servlet. GET requests by convention are used for retrieving information.
  • Other types of HTTP requests include, POST, PUT, DELETE, UPDATE, etc
  • HttpServletRequest: request from brower, HttpServletResponse: response back to browser
  • Annotations allow us to map a resource path to a Servlet

Outputting Valid HTML

HTML example from lecture 3


import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//Setting the Content-Type Header
		response.setHeader("Content-Type", "text/html");
		response.getWriter().append(
    "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>CS3220 Rocks!</title></head><body><h1>CS3220 is Awesome!!!</h1><p>This class is lit</p></body>");
	}

}
            

Servlet Mapping

@WebServlet(URL_Pattern)

Request URL: http://host/app/path

  • Can be specified either through XML definitions or annotations(preferred)
  • Some other examples of annotations: @Override,@SuppressWarnings
  • @WebServlet Documentation
  • Note the list of elements in the documentation:
  • For mapping, specify either a single value(like the example) or a list of urlPatterns
  • If using additional attributes (we will use loadOnStartup), specify the urlPatterns property
  • Just value:
    @WebServlet("/HelloWorld")

    Mapping to multiple patterns:
    @WebServlet(urlPatterns={"/HelloWorld", "/Example", "/hahahaha"})

    Additional Props:
    @WebServlet(urlPatterns="/HelloWorld", loadOnStartup=1)

Code Example: RequestCounter

Diplay the number of visitors for the Servlet

Where do we initialize the variable?

Servlet Life Cycle

  • init():
    Similar to how constructors. Executed only once. call super.init(config) first. Very handy for setting up shared variables between servlets
  • service():
    Per request, dispatches to doGet(), doPost(), etc
  • destroy(): When the Servlet is unloaded

Application Scope

  • A "storage area" where data can stored and accessed
  • Data in application scope will remain there as long as the application is running
  • Data in application scope is shared by all servlets
  • Data is gone after Servlet app shuts down/restarts. Using databases will allow persisting of data

Application Scope: Storing and Retrieving Data

Frist step: retrieve the ServletContext

getServletContext(): returns the HttpServletContext object

useful HttpServletContext instance methods:

  • setAttribute(String name, Object value):
    Give any object a name and save it to application scope
  • getAttribute(String name):
    Retrieve object from application scope using the name
  • You can create Java objects, store them in ArrayLists, access and modify them in different Servlets
  • And of course, the names are case sensitive

loadOnStartup

  • By default, a Servlet is not created until it is accessed for the first time
  • If we want to make sure the Servlet that contains the init gets run first, we can use the loadOnStarup element of @WebServlet to have it created during application startup
  • The value for loadOnStartup is the order which the application will start the servlets

@WebServlet(urlPatterns="/HelloWorld", loadOnStartup=1)

init() Example:


@Override
public void init( ServletConfig config ) throws ServletException
  {
      // When you override init(), don't forget to call the super class
      // init() first.
      super.init( config );

      // Note that Java automatically converts between int and Integer
      // (i.e. the "Autoboxing and Unboxing" feature since JDK 1.5.
      int counter = 0;
      getServletContext().setAttribute( "counter", counter );
  }
          

Full Example: Shared counter between Servlets, and Quizzes

Introduction to JavaServer Pages(JSP)

  • It's a pain to generate HTML using printWriter methods
  • Prone to error, hard to maintain
  • Presentation should be seperated from processing, just like what you did in JavaFX
  • We can use Java Code embedded in HTML documents to dynamically create the elements using Java object data

HelloJSP1.jsp


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD><TITLE>Hello JSP 1</TITLE></HEAD>
<BODY>A JSP without J or S.</BODY>
</HTML>
          

HelloJSP2.jsp


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD><TITLE>JSP Hello World</TITLE></HEAD>
<BODY>Hello World on <%= new java.util.Date() %>.
</BODY>
</HTML>
          

How does JSP Work?

JSP Components

  • HTML Template Text
  • Code Elements of Java:
    • Directives: look like <%@ type attr=“value” ... %>
    • Comments:
      <%-- Hidden Comments --%> and <!-- Output (HTML) Comments -->
    • Scripting elements
    • Beans
    • Expression language
    • Custom tag libraries

Simple JSTL Example


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

<html><head><title>JSTL Hello</title></head>
<body>

<c:out value="Hello World in JSTL." />

</body>
</html>
          

tablib Directive

URI

  • A unique identifier for the tag library
  • Not a real URL

Prefix

  • A short name for the tag library
  • Could be an arbitrary name

JSP Standard Tag Library(JSTL)

LibraryURIPrefix
Corehttp://java.sun.com/jsp/jstl/corec
XML Processinghttp://java.sun.com/jsp/jstl/xmlxml
I18N Formattinghttp://java.sun.com/jsp/jstl/fmtfmt
Database Accesshttp://java.sun.com/jsp/jstl/sqlsql
Functionshttp://java.sun.com/jsp/jstl/functionsfn

Docks: http://download.oracle.com/docs/cd/E17802_01/products/products/jsp/jstl/1.1/docs/tlddocs/index.html

JSTL Core: Useful Tags

Flow control

  • c:if
  • c:choose
    • c:when
    • c:otherwise
  • c:forEach
  • c:forToken

URL

  • c:url
  • c:redirect
  • c:import
  • c:param

Output

  • c:out

EL Brief Intro

Expression Language (EL)

  • Java's answer to scripting languages
  • Syntax: ${ expression }
  • Use EL to access the bean properties
    ${bean_name.property_name}
  • More to come in later lectures
  • You can access attributes from requestScope, set via request.setAttribute
  • In-Depth Guide: http://www.ibm.com/developerworks/library/j-jstl0211/

Branch Tags


<%-- single if --%>
No Quizzes.

<%-- if else branching --%>

    
        No quizzes yet.
    
    
        <%-- display the quizzes --%>
    

          

Code example: Quiz.jsp

Loop Tags



<%-- The varStatus property gives information about the current loop.--%>
<%-- remember loop.index calls getIndex --%>

    ${quiz.questionText}
  
    

          

Code example:Quizzes.jsp

see http://docs.oracle.com/javaee/6/api/javax/servlet/jsp/jstl/core/LoopTagStatus.html

Format Date and Time



<fmt:formatDate value="${date}" type="date" />

<fmt:formatDate value="${date}" type="time" />

<fmt:formatDate value="${date}" type="both" />

<fmt:formatDate value="${date}" pattern="yyyy-MM-dd hh:mm:ss a" />

          

Code example: Controller and View

see http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

JSTL Functions

  • fn:length()
  • fn:contains()
  • fn:containsIgnoreCase()
  • fn:startWith()
  • fn:endsWith()
  • fn:indexOf()
  • fn:replace()
  • fn:trim()
  • fn:toUpperCase()
  • fn:toLowerCase()
  • fn:substring()
  • fn:substringAfter()
  • fn:substringBefore()
  • fn:split()
  • fn:join()
  • fn:escapeXML()

Java Web Application

  • Servlets
  • Beans
  • JSPs
    Scripting elements, EL, JSTL
  • Static resources
    HTML,CSS,images, ...
  • Metadata files
    web.xml,...

Recall Model 2 Architecture

MVC Architecture

MVC: Order of Execution

  1. Browser sends a request to controller
  2. Controller processes the request, updates some data
  3. Controller forwards the request and data to view
  4. View generates the response that is sent back to the client

Quiz Example Using MVC

Model

  • Quiz.java

View

  • Quizzes.jsp, ViewQuiz.jsp
  • Redirect

Controller

  • ViewQuiz.java, ViewQuizzes.java

MVC: Points of Emphasis

  • One operation, one controller
  • Requests always go to controllers first. "Hide" JSPs under /WEB-INF/
  • Controllers do not generate HTML. No out.println()
  • JSPs are only used for display. No scripting elements in JSP

Forward Request From Controller to View


            request.getRequestDispatcher( "/WEB-INF/myJsp.jsp" )
	 .forward( request, response );
          

Forward vs. Redirect

Send Data From Controller to View

  • Objects in application and session scope are shared by all servlets and JSPs of the application
  • Additional data can be passed from servlet to JSP in request scope

request.setAttribute( "objName", obj );
request.getRequestDispatcher( "/WEB-INF/yourJSP.jsp" )
.forward( request, response );