No Slide Title

Download Report

Transcript No Slide Title

Chapter 6
How to structure a web
application
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 1
Objectives
Applied
 Use the MVC pattern to develop your web applications so servlets
control the processing and JSPs do the presentation.
 Provide for server-side data validation in your applications.
 Include files in your JSPs at translation time or request time.
 Use the web.xml file to set initialization parameters and use your
servlets to get the parameters.
 Use the web.xml file to provide servlet mapping and custom error
handling.
Knowledge
 Describe the Model 1 architecture and the applications for which it
is appropriate.
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 2
Objectives (continued)
 Describe the Model-View-Controller pattern, and explain how it
can help you develop web applications that are easier to develop
and maintain.
 Describe the way the controller, view, model, and data store are
used within an application that follows the MVC pattern.
 Distinguish between the use of JavaScript and servlets for data
validation.
 Describe the use of include files.
 Describe the use of the web.xml file.
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 3
The EmailServlet class
package email6;
import
import
import
import
import
java.io.*;
javax.servlet.*;
javax.servlet.http.*;
business.User;
data.UserIO;
public class EmailServlet extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException{
String firstName =request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String emailAddress =
request.getParameter("emailAddress");
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 4
The EmailServlet class (continued)
User user = new User(firstName, lastName,
emailAddress);
UserIO.addRecord(user,
"../webapps/murach/WEB-INF/etc/UserEmail.txt");
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(
"/email6/show_email_entry.jsp");
dispatcher.forward(request, response);
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException{
doGet(request, response);
}
}
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 5
The JSP code for show_email_entry.jsp
<!doctype html public "-//W3C//DTD HTML 4.0
Transitional//EN">
<html>
<head>
<title>Chapter 6 - Email List application</title>
</head>
<body>
<%
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String emailAddress =
request.getParameter("emailAddress");
%>
<h1>Thanks for joining our email list</h1>
<p>Here is the information that you entered:</p>
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 6
The show_email_entry.jsp (continued)
<table cellspacing="5" cellpadding="5" border="1">
<tr>
<td align="right">First name:</td>
<td><%= firstName %></td>
</tr>
<tr>
<td align="right">Last name:</td>
<td><%= lastName %></td>
</tr>
<tr>
<td align="right">Email address:</td>
<td><%= emailAddress %></td>
</tr>
</table>
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 7
The show_email_entry.jsp (continued)
<p>To enter another email address, click on the Back <br>
button in your browser or the Return button shown <br>
below.</p>
<form action="/murach/email6/join_email_list.html"
method="post">
<input type="submit" value="Return">
</form>
</body>
</html>
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 8
The Model 1 architecture
Browser
HTTP request
HTTP response
JSP
show_email_entry.jsp
JavaBean
User.class
Java Servlets and JSPCH06
Data store
© 2003, Mike Murach & Associates, Inc.
Slide 9
An introduction to the Model 1 architecture
 The Model 1 architecture is commonly used for web applications
with limited processing requirements. With this architecture, JSPs
handle both the requests and the responses.
 The business classes in the Model 1 architecture are coded as
JavaBeans. These classes represent the data of the application and
also do the business processing of the application.
 The data store can be a database or one or more disk files. It holds
the business data that is represented by the JavaBeans. This is often
referred to as persistent data storage because it exists after the
application ends.
 Usually, the methods of data classes like the UserIO class are used
to access and store the data of the data store.
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 10
The Model-View-Controller pattern
Browser
HTTP response
HTTP request
Controller
EmailServlet.class
View
show_email_entry.jsp
Model
User.class
Data store
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 11
An introduction to the Model-View-Controller
pattern
 The Model-View-Controller pattern, or MVC pattern, is
commonly used to structure web applications that have significant
processing requirements. That makes them easier to code and
maintain. This pattern is also known as the Model 2 architecture.
 The model in the MVS pattern consists of JavaBeans. The view
consists of HTML documents and JSPs. And the controller
consists of servlets.
 Usually, the methods of data classes like the UserIO class are used
to access and store the data of the data store.
 When you use the MVC pattern, you try to construct each layer so
it’s as independent as possible. Then, if you need to make changes
to one layer, any changes to the other layers are minimized.
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 12
How to forward the request and response objects
Syntax
RequestDispatcher objectName =
getServletContext().getRequestDispatcher(
"/url");
objectName.forward(request, response);
Examples
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(
"/email6/get_missing_fields.jsp");
dispatcher.forward(request, response);
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(
"/email6/join_email_list.html");
dispatcher.forward(request, response);
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(
"/servlet/email6.ValidateUserServlet");
dispatcher.forward(request, response);
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 13
How to redirect a response from a servlet
Syntax
response.sendRedirect("url");
Examples
response.sendRedirect("http://www.murach.com/index.htm");
response.sendRedirect(
"/murach/email6/show_email_entry.jsp");
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 14
How to forward and redirect requests and
responses
 The forward method of the RequestDispatcher object is typically
used to transfer control to a resource on the same server. Then, all
processing takes place on the server, and the specified resource
has access to the request and response objects.
 To get a RequestDispatcher object, you use the
getRequestDispatcher method of the ServletContext interface.
 To get the ServletContext object, you use the getServletContext
method of the HttpServlet class.
 The sendRedirect method of the response object is typically used
to transfer control to a resource on another server.
 When you use the sendRedirect method, the specified resource
doesn’t have access to the request and response objects and the
processing is split between the server and the browser.
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 15
JavaScript that validates a form
<script language="JavaScript">
<!-- hide this script from older browsers
function validate(form) {
if (form.firstName.value=="") {
alert("Please fill in your first name");
form.firstName.focus();
}
else if (form.lastName.value=="") {
alert("Please fill in your last name");
form.lastName.focus();
}
else if (form.emailAddress.value=="") {
alert("Please fill in your email address");
form.emailAddress.focus();
}
else {
form.submit();
}
}
// end hiding -->
</script>
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 16
JavaScript that validates a form (continued)
<body>
<h1>Join our email list</h1>
<p>To join our email list, enter your name and
email address below. <br>
Then, click on the Submit button.</p>
<form action="../servlet/email6.EmailServlet" method="get">
<table cellspacing="5" border="0">
<tr><td align="right">First name:</td>
<td><input type="text" name="firstName"></td>
</tr>
<tr><td align="right">Last name:</td>
<td><input type="text" name="lastName"></td>
</tr>
<tr><td align="right">Email address:</td>
<td><input type="text" name="emailAddress"></td>
</tr>
<tr><td></td>
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 17
JavaScript that validates a form (continued)
<td><input type="button" value="Submit"
onClick="validate(this.form)"></td>
</tr>
</table>
</form>
</body>
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 18
An introduction to JavaScript
 To validate data on the client side, you can add JavaScript to an
HTML page or a JSP.
 JavaScript improves the performance of an application by
preventing unnecessary requests and responses from being
passed between the server and browser.
 Although JavaScript uses a syntax that’s similar to Java, it is a
different language.
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 19
The dialog box that’s displayed when an entry
isn’t made
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 20
A servlet method that validates data
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException{
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String emailAddress =
request.getParameter("emailAddress");
// if any required fields are missing,
// display a JSP to get the missing fields
if ((firstName.length()==0)||(lastName.length()==0)||
(emailAddress.length()==0)){
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(
"/email6/get_missing_fields.jsp");
dispatcher.forward(request, response);
}
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 21
A servlet method that validates data (continued)
// otherwise, write the data to a file and display entry
User user = new User(firstName, lastName,
emailAddress);
UserIO.addRecord(user,
"../webapps/murach/WEB-INF/etc/UserEmail.txt");
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(
"/email6/show_email_entry.jsp");
dispatcher.forward(request, response);
}
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 22
The JSP that’s displayed when an entry isn’t made
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 23
Some code for the JSP
<%
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String emailAddress =
request.getParameter("emailAddress");
%>
<h1>Join our email list</h1>
<p>To join our email list, enter your name and
email address below. <br>
Then, click on the Submit button.</p>
<p><i>Please fill out all three fields.</i></p>
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 24
Some code for the JSP (continued)
<form action="../servlet/email6.EmailServlet"
method="get">
<table cellspacing="5" border="0">
<tr>
<td align="right">First name:</td>
<td><input type="text" name="firstName"
value="<%= firstName %>"></td>
</tr>
<tr>
<td align="right">Last name:</td>
<td><input type="text" name="lastName"
value="<%= lastName %>"></td>
</tr>
<tr>
<td align="right">Email address:</td>
<td><input type="text" name="emailAddress"
value="<%= emailAddress %>"></td>
</tr>
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 25
A JSP that uses two include files
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 26
The code for the header.htm file
<head>
<title>Chapter 6 - Email List application</title>
</head>
The code for the footer.jsp file
<%@ page import="java.util.Date" %>
<p><i><%= emailAddress %> was added on <%= new Date()
%>.</p>
The code for the show_email_entry.jsp file
<!doctype html public "-//W3C//DTD HTML 4.0
Transitional//EN">
<html>
<jsp:include page="/includes/header.htm" flush="true" />
<body>
// missing code that displays the body of the page
<%@ include file="/includes/footer.jsp" %>
</body>
</html>
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 27
How to include a file in a JSP at translation time
Syntax
<%@ include file="fileLocationAndName" %>
Examples
<%@ include file="/includes/header.htm" %>
<%@ include file="/includes/footer.jsp" %>
How to include a file in a JSP at request time
Syntax
<jsp:include page="fileLocationAndName" flush="true" />
Examples
<jsp:include page="/includes/header.htm" flush="true" />
<jsp:include page="/includes/footer2.jsp" flush="true" />
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 28
How to include a file in a JSP
 To include a file in a JSP at compile-time, or translation time, you
use the include directive.
 When you use the include directive, the code in the included file
becomes part of the generated servlet. As a result, any changes to
the included file don’t appear in the JSP until the JSP is
retranslated and recompiled.
 To include a file in a JSP at runtime, or request time, you use the
include action.
 When you use the include action, the included code is not part of
the generated servlet, and any changes to the included file appear
in the JSP the next time it is requested.
 When you include a file at translation time, the included file has
access to all variables and methods defined in the JSP, including
the request object. When you include a file at request time, the
included file doesn’t have access to these variables.
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 29
A web.xml file
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//
DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<context-param>
<param-name>dbName</param-name>
<param-value>murach</param-value>
</context-param>
<servlet>
<servlet-name>email6.EmailServlet</servlet-name>
<servlet-class>email6.EmailServlet</servlet-class>
<init-param>
<param-name>filename</param-name>
<param-value>
../webapps/murach/WEB-INF/etc/UserEmail.txt
</param-value>
</init-param>
</servlet>
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 30
A web.xml file (continued)
<servlet-mapping>
<servlet-name>email6.EmailServlet</servlet-name>
<url-pattern>/email6/email.jsp</url-pattern>
</servlet-mapping>
<!--To implement error handling, remove the comment-->
<!-<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/email6/error.htm</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/email6/show_error_page.jsp</location>
</error-page>
-->
</web-app>
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 31
An introduction to the web.xml file
 The web.xml file is stored in the WEB-INF directory for an
application. When the servlet engine starts, it reads the web.xml
file.
 You use XML tags to define elements. An element can have several
child elements. Since all elements must be coded within the webapp element, it is the root element.
 You can use comments to document the XML tags and to comment
out certain portions of the web.xml file. The tags for XML
comments are the same as the tags for HTML comments.
 If the elements in the web.xml aren’t in the correct order, Tomcat
will display an error message when it reads the web.xml file.
 After you modify the web.xml file, you must restart Tomcat so the
changes take effect.
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 32
XML tags that set initialization parameters in a
web.xml file
<web-app>
<context-param>
<param-name>dbName</param-name>
<param-value>murach</param-value>
</context-param>
<servlet>
<servlet-name>email6.EmailServlet</servlet-name>
<servlet-class>email6.EmailServlet</servlet-class>
<init-param>
<param-name>filename</param-name>
<param-value>
../webapps/murach/UserEmail.txt
</param-value>
</init-param>
</servlet>
</web-app>
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 33
XML elements for working with initialization
parameters
Element
Description
<web-app>
The root element of web.xml. All other elements
must be coded within this element.
<contextDefines a parameter that’s available to all servlets
param>
within an application.
<servlet>
Identifies a specific servlet within the application.
<servlet-name> Defines the name for the servlet that’s used in the
rest of the web.xml file.
<servletIdentifies the servlet by specifying the servlet’s
class>
package and class name.
<init-param>
Defines a name/value pair for an initialization
parameter for a servlet.
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 34
XML elements (continued)
Element
<param-name>
<param-value>
Java Servlets and JSPCH06
Description
Defines the name of a parameter.
Defines the value of a parameter.
© 2003, Mike Murach & Associates, Inc.
Slide 35
How to set initialization parameters
 To create an initialization parameter that will be available to all
servlets (called a context initialization parameter), you code the
param-name and param-value elements within the context-param
element.
 To create an initialization parameter that will be available to a
specific servlet (called a servlet initialization parameter), you
code the param-name and param-value elements within the initparam element.
 Before you create a servlet initialization parameter, you must
identify the servlet by coding the servlet, servlet-name, and
servlet-class elements.
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 36
Code that gets servlet initialization parameters
public class EmailServlet extends HttpServlet{
private String file;
public void init() throws ServletException{
ServletConfig config = getServletConfig();
file = config.getInitParameter("filename");
}
Code that gets context initialization parameters
public class EmailServlet extends HttpServlet{
private String dbName;
public void init() throws ServletException{
ServletConfig config = getServletConfig();
ServletContext context = config.getServletContext();
dbName = context.getInitParameter("dbName");
}
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 37
XML tags that add servlet mapping to the web.xml
file
<servlet>
<servlet-name>email6.EmailServlet</servlet-name>
<servlet-class>email6.EmailServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>email6.EmailServlet</servlet-name>
<url-pattern>/email6/email.jsp</url-pattern>
</servlet-mapping>
The opening Form tag that requests the servlet
<form action="/murach/email6/email.jsp" method="post">
The URL displayed in the browser
http://localhost:8080/murach/email6/email.jsp
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 38
How servlet mapping works
Client
Server
requests
/email6/email.jsp
Java Servlets and JSPCH06
executes
/servlet/email6.EmailServlet
© 2003, Mike Murach & Associates, Inc.
Slide 39
XML elements for working with servlet mapping
Element
Description
<servlet-mapping> Enables the ability to map URLs to servlets.
<servlet-name>
Specifies the name of the servlet. This must
correspond with the servlet-name element that’s
specified within the servlet element.
<url-pattern>
Specifies the URL or URLs that are to be
redirected to the servlet specified within the
servlet-mapping element. To avoid conflicts, you
should specify a directory or filename that
doesn’t actually exist.
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 40
Some URL patterns
Pattern
email6
email6/show
Java Servlets and JSPCH06
Description
Specifies any file in the email6 directory.
Specifies a file in the email6 directory named
show that has no extension.
© 2003, Mike Murach & Associates, Inc.
Slide 41
XML tags that provide error-handling for specific
exception types
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/email6/error.htm</location>
</error-page>
XML tags that provide error-handling for specific
error codes
<error-page>
<error-code>404</error-code>
<location>/email6/error_404.jsp</location>
</error-page>
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 42
XML elements for working with error handling
Element
Description
<error-page>
Specifies an HTML page or JSP that’s displayed
when the application encounters an uncaught
exception or a certain type of HTTP status code.
<exception-type> Uses the fully qualified class name to specify a
Java exception.
<error-code>
Specifies the number of a valid HTTP status code.
<location>
Specifies the location of the HTML page or JSP
that’s displayed.
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 43
How to implement custom error handling
 In the web.xml file, you can use the error-page element to specify
the error pages that should be displayed when the application
encounters (1) uncaught exceptions or (2) specific HTTP status
codes.
 In the web.xml file, you must place all error-page elements after all
servlet and servlet-mapping elements.
Java Servlets and JSPCH06
© 2003, Mike Murach & Associates, Inc.
Slide 44