You are on page 1of 49

Java

EE Servlet Tutorial
First Cookbook- Getting started with Model 2: Servlet and JSP

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Open%Source,%Reliable%and%Lightweight% Java%EE%Applica;on%Server%

RESIN PRO

Web Profile

Health System

Cloud Support

Thursday, May 3, 12

Cookbook: Intro to Serlvets and JSP


This cookbook in the Java EE Servlet tutorial covers
building a simple listing in JSP and Servlets.

This tutorial is part of Java EE Tutorial covering


JSP_2.2, and Servlets 3.0.

The WIKI and step by step detailed instructions live


here:

http://wiki4.caucho.com/
Building_a_simple_listing_in_JSP

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

About tutorial
Very liEle knowledge of HTML, Java and JSP is assumed HTML and Java not covered length, but pointers in the right
direc8on

Focus is Java Servlets and JSP (Java Server Pages) Use whatever IDE you would like, but direc8ons focus on
Eclipse

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

App you are building


Sorting

Remove

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Sidebar: Why Eclipse?


Best? No not really, best is IntelliJ Eclipse is free and supports Java EE well NetBeans and JDeveloper are from Oracle, they are good too

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Running tutorial app in Eclipse

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Windows? Try Linux...



Java is write once run anywhere, so you can develop Java anywhere Most companies deploy Java on some avor of Linux You can use Windows for development, but... Probably a good idea to get familiar with produc8on deployment environment anyway If you are a Windows or OSX users, I suggest installing Ubuntu (hEp:// www.ubuntu.com/) or CentOS on VMWare or Virtual Box and making that your main development environment You can make this tutorial work for you on OSX and Windows, but might be beEer just to go with a fric8onless approach. This way you can focus on the concepts instead of the congura8on woes Cloud deployment for the most part == Linux

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Outline

1 Optional: Getting started Eclipse Java EE IDE 2 Resources 3 What is going to be in the project 4 Creating model and Repository objects for books 4.1 Book model class 4.2 Are you new to Java? 4.3 BookRepository interface 5 Servlets / JSP 5.1 Servlet Background 5.2 Creating your rst Servlet 5.2.1 BookListServlet listing 5.2.2 Java EE / Servlets scopes (page, request, conversation, session, application) 6 Creating your rst JSP 6.1 Templates/JSTL versus Java scriptlets 6.1.1 /WEB-INF/pages/book-list.jsp listing 6.1.2 HTML background 6.1.3 JSTL c:forEach 7 Setting up CDI 7.1 CDI META-INF/beans.xml 8 Deploying with Eclipse 9 Deploying from the command line 10 Cookbooks and Tutorials

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Using Eclipse to setup Web Project



First go here to get Eclipse for Java EE: Install Guide for Eclipse for Java EE Indigo or higher. Screenshots to follows, but here is the basic steps to installing Eclipse and Java EE development environment in one go

Using Eclipse Indigo or higher Install Resin (lightweight, fast, easy to use Java EE 6 Web Prole server) plugin: 1. Go to File menu -> New Project -> Dynamic Web Project 2. In New Dynamic Web Project Dialog-> New Runtime... 3. In New Runtime Dialog -> Download Additional Server Adapters -> Select Resin (Java EE Web Prole) 4.0.x 4. (Click Next and Ok until it installs Resin runtime) 5. (Eclipse needs to restart) Setup new Web Project in Eclipse 1. 2. 3. 4. 5. File -> New Project -> Dynamic Web Project In New Dynamic Web Project Dialog-> New Runtime...->Select Resin->Check create local server checkbox Step 2 of New Runtime...->Click Download and Install (you only have to do this once) Fill out project name etc. (bookstore). (Click Next and Ok until you are done)

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Install Java EE 6 Web Prole



Go to File menu -> New Project -> Dynamic Web Project In New Dynamic Web Project Dialog-> New Run8me...

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Crea8ng a new web project

Click OK and Finish and Restart to restart Eclipse

Crea8ng a new Web Project

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Crea8ng a simple Book lis8ng for our bookstore



Create a new Java class as follows: Eclipse: Right Click "Java Resources" in Project Explorer -> New -> Class -> Package com.bookstore -> Class Name -> Book (That is the last 8me I will tell you how to create a class in Eclipse.) Add 8tle, descrip8on, price, pubDate and id proper8es, and the toString and cloneMe methods as follows:

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Are you new to Java?


If you are new to Java and the Book class seems foreign to
you,

Read up on Java a bit Ocial Java tutorial. Read the rst three trails (Ge>ng Started, Learning the Java
Language and EssenBal Java Classes),

Skip ahead to Java Beans. Skimming is ok. If you have programmed before, most things you will pick up on your
own.

Then come back here :)

Reminder: The methods public String getId() and public void


setId(String id) would dene a property called id

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Repository Interface
First step in tutorial not going to actually talk to a database
or use JDBC

For now, just using collec8on API Repository object encapsulates how an object gets persisted,
queried and updated (CRUD opera8ons)

Lets dene an interface for our CRUD opera8ons Later we use JDBC/RDBMS (MySQL), JTA/RDBMS, JCache,
MongoDB, etc. instead of collec8on API

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

BookRepository (DAO like object)

Eclipse: Right Click "Java Resources" in Project Explorer -> New -> Interface -> Package = com.bookstore -> Class Name = Book -> Click Finish

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

BookRepositoryImpl 1 of 4

Actual BookRepositoryImpl just uses Java collec8on to store in memory (skim dont read) Sets up some test data

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

BookRepositoryImpl 2 of 4

Helper methods to dene test data, add method

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

BookRepositoryImpl 3 of 4

Interface implementa8ons using collec8ons API

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

BookRepositoryImpl 4 of 4

listBooks and removeBooks

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

BookRepositoryImpl wrap up
This BookRepositoryImpl really basic class. Largely based on the collec8ons API You can nd out more informa8on about the Java collec8ons
API at this tutorial trail.

A full discussion of collec8on API out of scope for cookbook JDBC cookbook coming up in this tutorial series

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

@Applica8onScoped
One interesBng thing is BookRepositoryImpl uses
@Applica2onScoped annotaBon

AnnotaBons allow you to add meta-data to Java objects. (To


learn more see this annotaBons tutorial)

Applica2onScoped species a bean is applicaBon scoped Scoping denes a lifecycle


how long an object will be around
lifecycle of the Web ApplicaBon

ApplicaBonScoped means it will be around for the complete

This annotations has slightly different meanings depending on whether it is used with EJBs or Servlets. This annotation is part of the CDI support added to Java EE 6 to handle Java Dependency Injection. To learn more about CDI go see this tutorial Java Dependency Injection and this one part 2 both written by the same author that is writing this tutorial now.:)

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

@Applica8onScoped

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Model done, now controller


Now that we have a model
Book, BookRepository Servlet controller JSPs

Lets dene our web controller and view

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Servlet Background
A servlet is a Java class that handles HTTP requests A Java web applica8on consists of one or more servlet Servlets run inside of a container (like Caucho's Resin) End users typically use a Java Web Applica8on through a web
browser like Apple Safari, Google Chrome, Mozilla FireFox or Internet Explorer bundled together with any JSPs and Java classes it needs into a war le (Web Applica8on Archive le).

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Crea8ng your rst Servlet

Eclipse: Right Click "Java Resources" in Project Explorer -> New -> Servlet -> Package = com.bookstore.web -> Class Name = BookListServlet -> Click Next -> Remove URL mapping, create new mapping /book/

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Crea8ng your rst Servlet (part 2)

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

BookListServlet
Note: This applica8on uses the REST style URL mappings
URLs that end in / imply you are working with a list
(like a directory of les).

URI /book/ implies a collecBon of books

Perfect since we want to show a list of books

Modify generated Servlet to only handle the doGet method Change doGet method to forward to a JSP that we have not
created yet that lives in WEB-INF

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

BookListServlet

Looks up books using bookRepo (injected with @Inject CDI) Then forward to book-list.jsp to render book lis8ng

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Why JSP is in WEB-INF


WEB-INF is a meta directory folder for war les. JSPs in WEB-INF folder can never be loaded directly from a
browser

This allows us to force all JSPs to rst go through our Servlet We use model 2 throughout the tutorial Consider pumng JSPs in WEB-INF a best prac8ce.

8er (controllers) which is essen8al for a model 2 architecture (a form of MVC tailored for HTTP applica8ons),

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

@WebServlet annota8on (BookListServlet)



@WebServlet("/book/") allow us to map this Servlet to handle requests for the URI / book/ @WebServlet annota8on is a new feature of Servlets 3.0 Avoids a lot of XML congura8on

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

@Inject (BookListServlet)

Servlet uses repository model object to look up a list of BookRepository books. Java dependency injec8on used to inject BookRepository into the Servlet @Inject etc. added in Java EE 6

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

doGet (BookListServlet)

Servlet is controller in model 2 Controller talks to the model (BookRepository to get a list of Book), doGet method gets called when somebody loads the page from the browser and corresponds to HTTP GET doGet method uses the request object (HEpServletRequest request) to put the list of books into request scope using setAEribute as follows:

request.setAttribute puts books into request scope. But what is a scope?


Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Understanding scopes
Servlets and Java EE have various scopes page, request, conversa8on, session, applica8on Page scope (10 to 200 milliseconds) Request scope is around for one HTTP request (1/2 second to
several seconds) to 90 minutes)

Session scope is around for the en8re user session (5 minutes Conversa8on scope is around for one workow (user
registra8on, shopping cart, etc.).

Applica8on scope is around un8l web app shuts down


Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Background on JSP
JSP pages are also Servlets JSP is a templa8ng language to dene Servlets that allows
you to focus on the HTML instead of the Java code

JSP is like a Servlet turned inside out Essen8ally a JSP page is translated and compiled into a
servlets

JSP is similar to ASP and PHP in concept and scope ASP predates JSP and early JSP and ASP use a lot of the same
concepts

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

JSP scriptlets versus Templates


JSP allows mixing Java code and HTML (called Java scriptlets),
but dont

JSP adopted more of a classic templa8ng approach like


language

Freemarker, Velocity and Smarty (PHP based templaBng) Dont allow mixing the programming language with the templaBng Allows the templaBng language to be a simple view logic language, Keeps the templates smaller and more readable.

JSP uses JSTL and the Unied EL to accomplish things that


Smarty, Freemarker and Velocity accomplish prac8ce

Using JSTL/EL instead of Java scriptlets approach is a best


Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Crea8ng a JSP in Eclipse


Create a folder under WebContent/WEB-INF called pages Right click WebContent/WEB-INF/pages, then select New->JSP File use the file name book-list.jsp

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Modify book-list.jsp to match the following

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

book-list.jsp page direc8ve



Let's break this down some. First setup page using JSP page direc8ve: page direc8ve sayshow we want the characters encoded and what the mime type of the page is. Consider it boiler plate for now

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Using JSTL core library

Next we import the JSTL core library, under the tag c as follows:

HTML background Most of the page is boiler plate and simple HTML. If you are new to HTML, try this HTML tutorial. Then come back here.

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Using JSTL core c:forEach

Using c:forEach to iterate through the books in request scope

! ! ! ! ! ! ! !

<c:forEach var="book" items="${books}"> ! <tr> ! ! <td>${book.title}</td> ! ! <td>${book.description}</td> ! ! <td>${book.price}</td> ! ! <td>${book.pubDate}</td> ! </tr> </c:forEach>

Syntax like${books}, ${book.title}, ${book.price} ${book.pubDate} is Unied EL. EL is expression language

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

JSTL c:forEach

Where did the books come from? ${books} is the same books that we put into request scope in the

//BookListServlet.doGet method ! ! request.setAttribute("books", bookRepo.listBooks()); !

! ! ! ! ! ! ! !

<c:forEach var="book" items="${books}"> ! <tr> ! ! <td>${book.title}</td> ! ! <td>${book.description}</td> ! ! <td>${book.price}</td> ! ! <td>${book.pubDate}</td> ! </tr> </c:forEach>

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Semng up Java Dependency Injec8on



To setup Java Dependency Injec8on (CDI), you need to create a beans.xml le beans.xml need to go into META-INF

META-INF is a special directory for jar les and Java classpath entries to hold

beans.xml can be completely blank or just empty

$ pwd ~/workspace/javaee-tutorial/bookstore/src/META-INF $ touch beans.xml

To get Eclipse to quit complaining about the blank le not having the right format, ll it as follows:

META-INF/beans.xml

<?xml version="1.0" encoding="UTF-8"?> <beans 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/ beans_1_0.xsd"> </beans>
Note: the @Inject Java dependency injection will not work without this le.

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Deploying applica8on with Eclipse



Deploying with Eclipse Right click the BookListServlet in the Project Explorer Choose Run As->Run On Server... "Select Manually Dene a New Server" Choose Resin->Resin 4.0 from the Server List Click "Download addi8onal Server adapters

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Deploying applica8on with Eclipse



Right click BookListServlet in project explorer then choose Run -> Run On Server Select Resin then Click Next-> then click Download and Install

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Applica8on Running in Eclipse

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Applica8on Running in FireFox

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

Deploying from the command line

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server Thursday, May 3, 12

End of rst cookbook in tutorial


Cook books and Tutorials Building a simple lis8ng in JSP: covers model 2, Servlets, JSP intro. <You just
nished this one>

Java EE Servlet tutorial : Adding create, update and delete to the bookstore lisBng:
covers more interacBons. Java EE Servlet tutorial : Using JSPs to create header, footer area, forma>ng, and basic CSS for bookstore. Servlet tutorial : Adding validaBon and JSP tag les to bookstore example.

Java EE Servlet tutorial : Adding MySQL and JDBC to bookstore example.Java EE Java EE Servlet tutorial : Adding I18N support to bookstore example. Java EE Servlet tutorial : Load tesBng and health monitoring using bookstore
example.


Thursday, May 3, 12

Java EE Servlet tutorial : Se>ng up clustering and session replicaBon. Java EE Servlet tutorial : Se>ng up security for bookstore example. Java EE Servlet tutorial : File uploads for bookstore example. Java EE Servlet tutorial : Using JPA for bookstore example. Java EE Servlet tutorial : Using JCache for bookstore example.

Caucho Home | Contact Us | Caucho Blog | Wiki | Applica8on Server

You might also like