Java MVC - JoshuaScotton.com

advertisement
Servlets, JSP and JavaBeans
Joshua Scotton






Getting Started
Servlets
JSP
JavaBeans
MVC
Conclusion

Install JDK 5.0
◦ http://www.oracle.com/techn
etwork/java/javase/downloads/index-jdk5-jsp142662.html

Install Tomcat 6.0
◦ http://tomcat.apache.org/download-60.cgi

Install Eclipse EE IDE
◦ http://www.eclipse.org/downloads/packages/eclip
se-ide-java-ee-developers/heliossr1
Handling Client Requests



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
1.
2.
3.
4.
Server Application loads the Servlet and creates
an instance by calling the null constructor.
Servlet’s init(ServletConfig config) method is
called. HttpServlet’s should call
super.init(config) if overriding.
Once initialized, service(ServletRequest req,
ServletResponse res) is called concurrently for
every request.
When the servlet is unloaded, the destroy()
method is called. This may be run concurrently
with service so must be thread-safe.
import
import
import
public
java.io.*;
javax.servlet.*;
javax.servlet.http.*;
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();
}
}


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”);
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...
}

JavaServer
Pages





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
<HTML>
<BODY>
Hello World! <br />
The time is: <%= new java.util.Date() %>
</BODY>
</HTML>
<HTML>
<BODY>
<%
//System.out prints to the server log
System.out.println( “Getting the Date" );
java.util.Date date = new java.util.Date();
%>
The time is: <%
//The out object prints to the response
out.println(date.toString());
%>
</BODY>
</HTML>

The HttpServletRequest can be accessed by
JSP as shown in the following example:
out.println( “Your machine's address is: " );
out.println( request.getRemoteHost());


session.setAttribute( “user", username );
<%= session.getAttribute( “user" ) %>

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" %>


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() %>






${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








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
Business Logic Blocks




Java Class
Implements java.io.Serialiazable interface
Has a nullary constructor
Provides getter and setter methods for
accessing it’s properties
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; }
}



<jsp:useBean>
<jsp:setProperty>
<jsp:getProperty>
<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"/>

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.
<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:getProperty
name="name-of-the-object"
property="name-of-property"
/>
Example:
<jsp:getProperty name="user"
property="password" />
<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:useBean id="user"
class="webdev.examples.UserInfo"
scope="session"/>
<jsp:setProperty name="user"
property="*"/>
<jsp:useBean id="user"
class="webdev.examples.UserInfo"
scope="session"/>
Hello <%= user.getName() %>, you are
<%= user.getAge() %> years old.
Model, View, Controller
Model
 View
 Controller



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



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.


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.




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.


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



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

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

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.
http://www.java-samples.com/showtutorial.php?tutorialid=552
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; }
}
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;
}
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; }
}
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);
}
}
req.setAttribute("person", p);
RequestDispatcher rd =
req.getRequestDispatcher(“show.jsp");
rd.forward(req, res);
<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>
Download