servlets, jsp and javabeans joshua scotton. getting started servlets jsp javabeans mvc ...

49
Java MVC Servlets, JSP and JavaBeans Joshua Scotton

Upload: fernando-verdier

Post on 01-Apr-2015

253 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

Java MVCServlets, JSP and JavaBeans

Joshua Scotton

Page 2: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

Getting Started Servlets JSP JavaBeans MVC Conclusion

Contents

Page 4: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

ServletsHandling Cl ient

Requests

Page 5: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

Servlets are modules of Java code that run in a server application

Servlets handle client requests Although not exclusively, most servlets are

used to answer HTTP requests and hence extend the javax.servlet.http.HttpServlet class

What is a Servlet?

Page 6: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

1. Server Application loads the Servlet and creates an instance by calling the null constructor.

2. Servlet’s init(ServletConfig config) method is called. HttpServlet’s should call super.init(config) if overriding.

3. Once initialized, service(ServletRequest req, ServletResponse res) is called concurrently for every request.

4. When the servlet is unloaded, the destroy() method is called. This may be run concurrently with service so must be thread-safe.

Servlet Architecture

Page 7: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class HelloWorldServlet extends HttpServlet {

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<HTML><HEAD><TITLE>Hello World!" + "</TITLE></HEAD><BODY>Hello World!" + "</BODY></HTML>"); out.close();

} }

HttpServlet Example

Page 8: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

Request data is sent to the servlet in an HttpServletRequest object

To access a parameter use the getParameter method. For example:

String email = req.getParameter(“email”);

Handling Request Parameters

Page 9: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

If you are not going to be sure of which request type you are going to be handling, or if you want to handle both in the same manner. You can forward one to the other as shown below:

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doPost(req,res);}protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { //response code goes here...}

doGet or doPost?

Page 10: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

JSPJ a v a S e r v e r P a g e s

Page 11: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

JSP = JavaServer Pages Puts Java inside a HTML page JSP files are recognised by the

extension .jsp JSP’s are compiled on the first time that

they are loaded Needs a JSP supporting web server like

Tomcat, Glassfish and Blazix etc

JSP

Page 12: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

<HTML><BODY>Hello World! <br />The time is: <%= new java.util.Date() %></BODY></HTML>

JSP - Hello World

Page 13: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

<HTML><BODY> <%//System.out prints to the server logSystem.out.println( “Getting the Date" );     java.util.Date date = new java.util.Date(); %> The time is: <%//The out object prints to the responseout.println(date.toString()); %></BODY></HTML>

Scriplets

Page 14: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

The HttpServletRequest can be accessed by JSP as shown in the following example:

out.println( “Your machine's address is: " );     out.println( request.getRemoteHost());

Getting Request Parameters

Page 15: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

session.setAttribute( “user", username ); <%= session.getAttribute( “user" ) %>

Accessing the Session in JSP

Page 16: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

Page Directive: importing packages<%@ page import="java.util.*" %> <%@ page import="java.util.*,java.text.*" %>

Include Directive: including other JSP’s inline<%@ include file="hello.jsp" %>

JSP Directives

Page 17: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

A JSP is turned into a class definition. To add variables and method declarations to the

class you use a JSP declaration using <%! and %> tags as shown in the following example:

<%! Date theDate = new Date(); Date getDate() { System.out.println(“Returning the Date...”); return theDate; }%>The time is now <%= getDate() %>

JSP Declarations

Page 18: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

${1 > (4/2)} returns false ${3 div 4} or ${3 / 4} return 0.75 ${pageContext.request.contextPath}

returns the context path ${sessionScope.cart.numberOfItems} gets

the property “numberOfItems” from the session scoped bean “cart”

${param['mycom.productId']} returns the mycom.productId parameter from the request

${header["host"]} returns the host value from the page header

JSP 2.0 Expression Language

Page 19: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

pageScope: Maps page-scoped variable names to their values requestScope: Maps request-scoped variable names to their

values sessionScope: Maps session-scoped variable names to their

values applicationScope: Maps application-scoped variable names to

their values pageScope: Maps page-scoped variable names to their values requestScope: Maps request-scoped variable names to their

values sessionScope: Maps session-scoped variable names to their

values applicationScope: Maps application-scoped variable names to

their values

JSP 2.0 Expression Language: Implicit Objects

Page 20: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

JavaBeansBus iness Log ic B locks

Page 21: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

Java Class Implements java.io.Serialiazable interface Has a nullary constructor Provides getter and setter methods for

accessing it’s properties

What are JavaBeans

Page 22: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

package webdev.examples;

public class UserInfo implements java.io.Serializable {private String name;private Integer age;public String getName() { return name; }public void setName(String name) { this.name = name; }public Integer getAge() { return age; }public void setAge(Integer age) { this.age = age; }

}

Simple Example

Page 23: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

<jsp:useBean> <jsp:setProperty> <jsp:getProperty>

Accessing a Bean from JSP

Page 24: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

<jsp:useBean id="object-name" scope="page | request | session | application" type="type-of-object" class="fully-qualified-classname" beanName="fully-qualified-beanName"

/>

Example:<jsp:useBean id="user" class="webdev.examples.UserInfo" scope="session"/>

<jsp:useBean>

Page 25: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

page – Default scope, the JavaBean is created and destroyed every time a page is loaded.

request – The created object is bound to the request object.

session – The bean is bound to the session object, which means that this will be unique to the user.

application – An object bound to the application will stay as long as the application is loaded. Can be used for counting page views.

Object JavaBean Scope

Page 26: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

<jsp:setProperty name="id-of-the-JavaBean" property="name-of-property" param="request-parameter" value="new-value-of-this-property"

/>

Example:<jsp:setProperty name="user" property="password" /><jsp:setProperty name="user" property="password" param="pass" />

<jsp:setProperty name="user" property="password" value="secretPassword" />

<jsp:setProperty>

Page 27: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

<jsp:getProperty name="name-of-the-object" property="name-of-property"

/>

Example:<jsp:getProperty name="user" property="password" />

<jsp:getProperty>

Page 28: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

<form method="post" action="saveDetails.jsp">

Enter your name: <input type="text" name="name" size=50 /><br />

Enter your age: <input type="text" name="age" size=3 /><br />

<input type="submit" />

JSP/JavaBean Example – HTML Form

Page 29: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

<jsp:useBean id="user" class="webdev.examples.UserInfo" scope="session"/>

<jsp:setProperty name="user" property="*"/>

JSP/JavaBean Example – Setting

Page 30: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

<jsp:useBean id="user" class="webdev.examples.UserInfo" scope="session"/>

Hello <%= user.getName() %>, you are <%= user.getAge() %> years old.

JSP/JavaBean Example – Getting

Page 31: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

MVCModel , View, Contro l ler

Page 32: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

Model View Controller

MVC

Page 33: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

The Model represents the business logic of the application

Encapsulating business rules into components:◦ Facilitates testing◦ Improves quality◦ Promotes reuse

The model can be partitioned into State and Action components

The Model

Page 34: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

Define the current set of values in the Model and includes methods to update these values.

Should be protocol independent. JavaBeans are a logical choice for

implementing State Components.

The Model - State Components

Page 35: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

Define allowable changes to the State in response to events

In simpler systems this function may be absorbed into the Controller, however this is not generally recommended.

The Model - Action Components

Page 36: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

Represents the presentation logic of the application.

Retrieves the State from the Model and provides the user interface for the specific protocol.

Separating the View from the Model enables the independent construction of user interfaces with different look and feels.

JSPs are a good choice for implementing the View.

The View

Page 37: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

Provides the glue to MVC In a MVC system the Controller must handle

the following tasks:◦ Security◦ Event Identification◦ Prepare the Model◦ Process the Event◦ Handle Errors◦ Trigger the Response

Servlets are an ideal choice for the Controller

The Controller

Page 38: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

You can use just JSP to create a web application

This makes it hard to separate out the web design and the business code

Using JSP just for the View and Servlets for the Controller can simplify the development process

MVC using Servlets and JSP

Page 39: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

Search Example:ArrayList searchResultsList = // get from the query

RequestDispatcher disp;

disp = getServletContext().getRequestDispatcher("searchresults.jsp");

request.setAttribute("my.search.results", searchResultsList);

disp.forward(request, response); searchResultsList is populated from a query handled by the

servlet searchresults.jsp is selected as the handler for the response We add the search result array to the request so that it is

accessible to the JSP

Servlets and JSP example: Servlet

Page 40: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

The JSP can retrieve the result set using this code:

ArrayList myList = (ArrayList) request.getAttribute("my.search.results");

You can then use a for loop to print the contents of the search request.

Servlets and JSP example: JSP

Page 41: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

Adding JavaBeans Example

http://www.java-samples.com/showtutorial.php?tutorialid=552

Page 42: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

package webdev.examples.address;

public class Person implements java.io.Serializable {private String name;private int age;private Address address;

public Person() { setName("A N Other"); setAge(21); this.address = new Address();}

public void setName(String name) { this.name = name; }public String getName() { return name; }public void setAge(int age) { this.age = age; }public int getAge() { return age; }public void setAddress(Address address) { this.address = address; }public Address getAddress() { return address; }

}

Person Bean

Page 43: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

package webdev.examples.address;import java.util.Collection;public class Address implements java.io.Serializable {private String line1;private String town;private String county;private String postcode;private Collection phoneNumbers;

public Address() { this.line1 = "line1"; this.town = "a town2"; this.county = "a county"; this.postcode = "postcode";}public void setLine1(String line1) { this.line1 = line1; }public String getLine1() { return line1; }

…public Collection getPhoneNumbers() { return phoneNumbers; }public void setPhoneNumbers(Collection phoneNumbers) {

this.phoneNumbers = phoneNumbers; }}

Address Bean

Page 44: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

package webdev.examples.address;

public class PhoneNumber implements java.io.Serializable {

private String std; private String number;

public String getNumber() { return number; } public String getStd() { return std; } public void setNumber(String number) { this.number = number; }public void setStd(String std) {

this.std = std; }}

PhoneNumber Bean

Page 45: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

package webdev.examples.address;import java.io.IOException; import java.util.ArrayList; import javax.servlet.RequestDispatcher;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

public class handlerServlet extends HttpServlet {protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException {

Person p = new Person();p.setName("Sam Dalton");p.setAge(26);Address a = new Address();a.setLine1("221b Baker Street");a.setTown("London");a.setCounty("Greater London");a.setPostcode("NW1 1AA");ArrayList al = new ArrayList();PhoneNumber ph = new PhoneNumber();ph.setStd("01895");ph.setStd("678901");al.add(ph);ph = new PhoneNumber();ph.setStd("0208");ph.setStd("8654789");al.add(ph);a.setPhoneNumbers(al);p.setAddress(a);req.setAttribute("person", p);RequestDispatcher rd = req.getRequestDispatcher(“show.jsp");rd.forward(req, res);

}}

handlerServlet.java

Page 46: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

req.setAttribute("person", p);RequestDispatcher rd = req.getRequestDispatcher(“show.jsp");

rd.forward(req, res);

Setting the Request Variable

Page 47: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

<html><head><title>MVC Example</title></head><body><h2>MVC Example</h2><table border="1"><tr><td>${person.name}</td><td>${person.age}</td><td>${person["address"].line1}</td><td>${person["address"].town}</td><td>${person.address.phoneNumbers[0].std}${person.address.phoneNumbers[0].number}</td><td>${person.address.phoneNumbers[1].std}${person.address.phoneNumbers[1].number}</td></tr></table></body></html>

show.jsp

Page 48: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

Output

Page 49: Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

Questions