APT_Java - Latvijas universitāte

Download Report

Transcript APT_Java - Latvijas universitāte

Modernās Programmēšanas Tehnoloģijas
(Advanced Programming Technologies)
Edgars Celms, Mārtiņš Opmanis
([email protected])
Latvijas Universitātes
Matemātikas un informātikas institūts
2007, Rīga, Latvija
Serversīklietotņu (servlets) programmēšana

“Java™ How to Program, Sixth Edition”

Chapter 26. Servlets








Servleti un to arhitektūra
Servlet interfeiss un Servletu dzīves cikls
Klase HttpServlet
HttpServletRequest un HttpServletResponse interfeisi
Apache Tomcat serveris
HTTP ...Requests apstrādāšana
Vairāklīmeņu (multitier) lietojumprogrammas
JDBC lietojums servletos
Ievads

Tīklošanās iespējas valodā JAVA

Socket-based un packet-based komunikācija


Remote Method Invocation (RMI)



Package java.rmi
The RMI packages allow Java objects running on separate JVMs (normally on separate
computers) to communicate via remote method calls. Such calls appear to invoke
methods on an object in the same program, but actually have built-in networking (based
on the capabilities of package java.net) that communicates the method calls to another
object on a separate computer.
Common Object Request Broker Architecture (CORBA)



Package java.net
Package org.omg
A key difference between RMI and CORBA is that RMI can only be used between Java
objects, whereas CORBA can be used between any two applications that understand
CORBAincluding applications written in other programming languages.
Remote Method Invocation over the Internet Inter-Orb Protocol (RMI-IIOP)

RMI-IIOP enables the integration of Java with non-Java distributed objects by using
CORBA IIOP
Ievads

Klienta-servera attiecība

Servlets (serversīklietotnes) un JavaServer Pages (JSP)


Pieprasījuma-atbildes modelis (request-response model)
Pakotnes javax.servlet
javax.servlet.http
javax.servlet.jsp
javax.servlet.tagext

Populārākā pieprasījuma-atbildes modeļa implementācija






Ir par pamatu J2EE Web komponentēm
Servleti un “tievais” klients (thin client)


tīmekļa pārlūkprogrammas (web browsers) un tīmekļa serveri (web servers)
Nodrošina prezentācijas līmeni
Neapstrādā datus
Nepieciešami mazāki datora resursi
Apache Jakarta projekti un Tomcat Server
Tomcat


Jakarta projekts
Oficiālo servletu un JSP standartu implementācija
Servleti un to arhitektūra

Servleti


Servlets ir Javas programma, kura atrodas un izpildās serverī un sūta informāciju
klientam
Piemēram, tīmekļa serveris sūta HTML pārlūkprogrammai


JavaServer Pages (JSP)

Servletu tehnoloģijas paplašinājums



Vienkāršo lapu izveidošanas procesu atdalot prezentācijas daļu no satura daļas
Parasti JSP izmanto, ja informācija ko sūta klientam pārsvarā ir statiskas daba un
tikai neliela daļa no šī sūtījuma tiek ģenerēta dinamiski izmantojot Javas kodu
Servletu konteineris (servlet container (engine))


HTML var nākt no reāla faila uz servera vai arī to var sūtīt (izveidot) programma,
piemēram, Javas servlets.
Serveris kurš spēj izpildīt servletus
Tīmekļa serveri un aplikāciju serveri, kuri var darboties kā konteineri
servletiem

Sun Java System Application Server, Microsoft’s Internet Information Server (IIS),
Apache HTTP Server, BEA’s WebLogic Application Server, IBM’s WebSphere
Application Server, World Wide Web Consortium’s Jigsaw Web Server, …
Servleti un to arhitektūra
Servlet interfeiss un servletu dzīves cikls

Servlet interfeiss



Pakotnes kuras tiek izmantotas darbam ar servletiem



Visiem servletiem ir jāimplementē šāds interfeiss
Servlet interfeisa metodes izsauc servlet konteineris
Pakotnē javax.servlet – definēta klase GenericServlet, kura ir
protokolu neatkarīga (protocol-independent).
Pakotnē javax.servlet.http – definēta klase HttpServlet, kura
izmanto HTTP protokolu
Servleta dzīves cikls



Servleta konteineris izsauc servleta init metodi
Servleta service metode apstrādā pieprsījumu
Servleta destroy metode atbrīvo servleta resursus, ja konteineris beidz
(terminates) servletu
Servlet interfeiss
Method
Description
void init( ServletConfig config )
The servlet container calls this method once during a servlet’s execution cycle to initialize the
servlet. The ServletConfig argument is supplied by the servlet container that executes the
servlet.
ServletConfig getServletConfig()
This method returns a reference to an object that implements interface ServletConfig. This
object provides access to the servlet’s configuration information, such as its initialization
parameters and ServletContext, which provides the servlet with access to its environment
(i.e., the servlet container in which the servlet executes).
String getServletInfo()
This method is defined by a servlet programmer to return a string containing servlet
information, such as the servlet’s author and version.
void service( ServletRequest request, ServletResponse response )
The servlet container calls this method to respond to a client request to the servlet.
void destroy()
This “cleanup” method is called when a servlet is terminated by its servlet container. Resources
used by the servlet, such as open files or open database connections, should be deallocated here.
Servlet interfeiss un servletu dzīves cikls

Servlet interfeisa implementācija

GenericServlet

Abstrakta klase
Pakotne javax.servlet

Protokola neatkarīgs servlets


HttpServlet




Abstrakta klase
Pakotne javax.servlet.http
Lai apmainītos ar informāciju izmanto HTTP protokolu
Parasti izmanto, lai paplašinātu tīmekļa servera funkcionalitāti
Klase HttpServlet

Klase HttpServlet pārimplementē (overrides) service metodi


Nevajadzētu pārimplementēt service metodi klases HttpServlet
apakšklasēs. Radīs problēmas servletam atšķirt pieprasījuma tipus.
Divi biežāk lietotie HTTP pieprasījuma veidi

get pieprasījums


post pieprasījums




Get/retrieve informāciju no servera
Post/send datus uz servei
Metode doGet reaģē uz get pieprasījumu
Metode doPost reaģē uz post pieprasījumu
Metodes doGet un doPost kā parametrus saņem
HttpServletRequest un HttpServletResponse objektus
Dažas citas HttpServlet klases metodes
Method
Description
doDelete
Called in response to an HTTP delete request. Such a request is normally used to delete a
file from a server. This may not be available on some servers because of its inherent security
risks (e.g., the client could delete a file that is critical to the execution of the server or an
application).
doHead
Called in response to an HTTP head request. Such a request is normally used when the
client wants only the response’s headers, such as its content type and content length. By
overriding this method, the servlet does not compute the response body, thus improving
performance.
Called in response to an HTTP options request. This returns information to the client
indicating the HTTP options supported by the server, such as the HTTP version (1.0 or 1.1)
and the request methods the server supports.
doOptions
doPut
Called in response to an HTTP put request. Such a request is normally used to store a file on
the server. This may not be available on some servers because of its inherent security risks
(e.g., the client could place an executable application on the server, which, if executed, could
damage the server—perhaps by deleting critical files or occupying resources).
doTrace
Called in response to an HTTP trace request. Such a request is normally used for
debugging. The implementation of this method automatically returns an HTML document to
the client containing the request header information (data sent by the browser as part of the
request).
HttpServletRequest interfeiss

Servleta konteineris



izveido HttpServletRequest objektu
nodod to kā parametru servleta service metodei
HttpServletRequest objekts


satur klienta pieprasījumu
nodrošina metodes lai servlets varētu apstrādāt šādu
pieprasījumu
HttpServletRequest metodes
Method
Description
String getParameter( String name )
Obtains the value of a parameter sent to the servlet as part of a get or post request. The
name argument represents the parameter name.
Enumeration getParameterNames()
Returns the names of all the parameters sent to the servlet as part of a post request.
String[] getParameterValues( String name )
For a parameter with multiple values, this method returns an array of strings containing
the values for a specified servlet parameter.
Cookie[] getCookies()
Returns an array of Cookie objects stored on the client by the server. Cookie objects
can be used to uniquely identify clients to the servlet.
HttpSession getSession( boolean create )
Returns an HttpSession object associated with the client’s current browsing session.
This method can create an HttpSession object (true argument) if one does not already
exist for the client. HttpSession objects and Cookies are used in similar ways for
uniquely identifying clients.
String getLocalName()
Gets the host name on which the request was received.
String getLocalAddr()
Gets the Internet Protocol (IP) address on which the request was received.
int getLocalPort()
Gets the Internet Protocol (IP) port number on which the request was received.
HttpServletResponse interfeiss

Servleta konteineris



izveido HttpServletResponse objektu
nodod to kā parametru servleta service metodei
HttpServletResponse objekts

nodrošina metodes lai servlets varētu noformēt atbildi klientam
HttpServletResponse metodes
Method
Description
void addCookie( Cookie cookie )
Used to add a Cookie to the header of the response to the client. The Cookie’s
maximum age and whether Cookies are enabled on the client determine whether
Cookies are stored on the client.
ServletOutputStream getOutputStream()
Obtains a byte-based output stream for sending binary data to the client.
PrintWriter getWriter()
Obtains a character-based output stream for sending text data (usually HTML formatted
text) to the client.
void setContentType( String type )
Specifies the content type of the response to the browser. The content type helps the
browser determine how to display the data (or possibly what other application to execute
to process the data). The content type is also known as MIME (Multipurpose Internet
Mail Extension) type of the data. For examples, content type "text/html" indicates
that the response is an HTML document, so the browser displays the HTML page;
content type "image/gif" indicates that the response is an image, so the browser
displays the image. For a complete list of content types, visit www.isi.edu/innotes/iana/assignments/media-types/media-types.
String getContentType()
Gets the content type of the response.
Apache Tomcat serveris


Kā strādāt un instalēt Tomcat serveri šajā kursā sīkāk
neapskatīsim.
Informācija tīklā par Tomcat


http://www.apache.org/
http://tomcat.apache.org/
HTTP get pieprasījumu apstrādāšana

HTTP get pieprasījums


Sagaida kā atbildi URL saturu
Piemērs, WelcomeServlet

Servlets kurš apstrādā HTTP get pieprasījumus
1
2
// Fig. 26.7: WelcomeServlet.java
// A simple servlet to process get requests.
3
4
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
5
6
7
8
9
10
11
12
13
14
import
import
import
import
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
java.io.IOException;
java.io.PrintWriter;
public class WelcomeServlet extends HttpServlet
{
// process "get" requests from clients
protected void doGet( HttpServletRequest request,
HttpServletResponse response )
throws ServletException, IOException
{
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();
// send XHTML page to client
// start XHTML document
out.println( "<?xml version = \"1.0\"?>" );
Import the classes and interfaces in the javax.servlet
and javax.servlet.http packages
Extends HttpServlet to
handle HTTP get requests
and HTTP post requests
Override method doGet to provide
custom get request processing
Uses the response object’s
setContentType method to specify the
content type of the data to be sent as the
response to the client
Uses the response object’s getWriter
method to obtain a reference to the
PrintWriter object that enables the servlet
to send content to the client
out.printf( "%s%s%s", "<!DOCTYPE html PUBLIC",
" \"-//W3C//DTD XHTML 1.0 Strict//EN\"",
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" );
out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
Create the XHTML
document by writing
strings with the out
object’s println method
31
// head section of document
32
out.println( "<head>" );
33
out.println( "<title>A Simple Servlet Example</title>" );
34
out.println( "</head>" );
35
36
// body section of document
37
out.println( "<body>" );
38
out.println( "<h1>Welcome to Servlets!</h1>" );
39
out.println( "</body>" );
40
41
// end XHTML document
42
out.println( "</html>" );
43
out.close();
44
// close stream to complete the page
} // end method doGet
45 } // end class WelcomeServlet
Closes the output stream, flushes
the output buffer and sends the
information to the client
WelcomeServlet.html
1
<?xml version = "1.0"?>
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5
<!-- Fig. 26.7: WelcomeServlet.html -->
6
7
<html xmlns = "http://www.w3.org/1999/xhtml">
8
<head>
9
<title>Handling an HTTP Get Request</title>
10 </head>
11
12 <body>
13
14
17
The form’s method attribute indicates that
the browser sends a get request to the
server, which results a call to the servlet’s
doGet method
<form action = "/jhtp6/welcome1" method = "get">
<p><label>Click the button to invoke the servlet
<input type = "submit" value = "Get HTML Document" />
15
16
The form’s action attribute
(/jhtp6/welcome1) specifies the URL
path that invokes the servlet
</label></p>
</form>
18 </body>
19 </html>
Create a button, when
clicked, the form’s action is
performed
Programmas darbības rezultāts
Web lietojumprogrammu izvietošana serverī

Tīmekļa lietojumprogrammas


JSP, servleti un ar tiem saistītie faili
Tīmekļa lietojumprogrammu izvietošana (deploying)

Folderu struktūra



Context root
Tīmekļa lietojumprogrammu arhīva fails (WAR file)
Izvietošanas deskriptors (deployment descriptor)

web.xml
Web lietojumprogrammu izvietošana serverī

Tīmekļa lietojumprogrammu standarta forlderi
Directory
Description
context root
This is the root directory for the Web application. All the JSPs, HTML
documents, servlets and supporting files such as images and class files reside in
this directory or its subdirectories. The name of this directory is specified by the
Web application creator. To provide structure in a Web application,
subdirectories can be placed in the context root. For example, if your application
uses many images, you might place an images subdirectory in this directory.
The examples of this chapter use jhtp6 as the context root.
WEB-INF
This directory contains the Web application deployment descriptor (web.xml).
WEB-INF/classes
This directory contains the servlet class files and other supporting class files used
in a Web application. If the classes are part of a package, the complete package
directory structure would begin here.
WEB-INF/lib
This directory contains Java archive (JAR) files. The JAR files can contain
servlet class files and other supporting class files used in a Web application.
1
2
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3
4
5
6
7
8
9
10
11
12
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
13
14
15
16
17
18
19
20
<description>
This is the Web application in which we
demonstrate our JSP and Servlet examples.
</description>
21
22
23
24
25
26
27
28
29
30
<!-- General description of your Web application -->
<display-name>
Java How to Program JSP
and Servlet Chapter Examples
</display-name>
Element servlet
describes a servlet.
<!-- Servlet definitions -->
<servlet>
<servlet-name>welcome1</servlet-name>
Element web-app defines the
configuration of each servlet in the
Web application and the servlet
mapping for each servlet.
Element display-name specifies a name
that can be displayed to the administrator
of the server on which the Web
application is installed.
Element description specifies a
description of the Web application that
might be displayed to the administrator of
the server.
Element servlet-name is the
name for the servlet.
<description>
A simple servlet that handles an HTTP get request.
</description>
<servlet-class>
WelcomeServlet
</servlet-class>
</servlet>
Element servlet-class specifies
compiled servlet’s fully
qualified class name.
Element description
specifies a description for this
particular servlet.
Web lietojumprogrammu izvietošana serverī
31
<!-- Servlet mappings -->
32
<servlet-mapping>
33
<servlet-name>welcome1</servlet-name>
34
<url-pattern>/welcome1</url-pattern>
35
</servlet-mapping>
36
37 </web-app>
Element servlet-mapping specifies servletname and url-pattern elements.
Element url-pattern helps the
server determine which
requests are sent to the servlet
Web lietojumprogrammu izvietošana serverī

Invoke WelcomeServlet example

/jhtp6/welcome1



/jhtp6 specifies the context root
/welcome1 specifies the URL pattern
URL pattern formats

Exact match


Path mappings


/jhtp6/example/*
Extension mappings


/jhtp6/welcome1
*.jsp
Default servlet

/
WelcomeServlet Web application directory and file structure
jhtp6
servlets
WelcomeServlet.html
WEB-INF
web.xml
classes
WelcomeServlet.class
Tādu HTTP get pieprasījumu apstrādāšana, kuri satur datus

Pieprasījums serverim var saturēt arī datus.
Dati tiek uzdoti kā parametri.
Parametri ir vārds-vērtība pāris, kurš tiek norādīts aiz URL
beigās aiz jautājuma zīmes
Piemēram: http://localhost?firstname=Jon

Ja ir vairāki parametri – jālieto &.



1
// Fig. 26.12: WelcomeServlet2.java
2
// Processing HTTP get requests containing data.
3
import javax.servlet.ServletException;
4
import javax.servlet.http.HttpServlet;
5
import javax.servlet.http.HttpServletRequest;
6
import javax.servlet.http.HttpServletResponse;
7
import java.io.IOException;
8
import java.io.PrintWriter;
9
10 public class WelcomeServlet2 extends HttpServlet
11 {
12
// process "get" request from client
13
protected void doGet( HttpServletRequest request,
HttpServletResponse response )
14
throws ServletException, IOException
15
16
17
The request object’s
getParameter method receives
the parameter name and returns
the corresponding String value
{
String firstName = request.getParameter( "firstname" );
18
19
response.setContentType( "text/html" );
20
PrintWriter out = response.getWriter();
21
22
// send XHTML document to client
23
24
// start XHTML document
25
out.println( "<?xml version = \"1.0\"?>" );
26
27
out.printf( "%s%s%s", "<!DOCTYPE html PUBLIC",
28
" \"-//W3C//DTD XHTML 1.0 Strict//EN\"",
29
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" );
30
31
out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
32
33
// head section of document
34
out.println( "<head>" );
35
out.println(
36
37
"<title>Processing get requests with data</title>" );
out.println( "</head>" );
38
39
// body section of document
40
out.println( "<body>" );
41
out.println( "<h1>Hello " + firstName + ",<br />" );
42
out.println( "Welcome to Servlets!</h1>" );
43
out.println( "</body>" );
44
45
// end XHTML document
46
out.println( "</html>" );
47
out.close();
48
// close stream to complete the page
} // end method doGet
49 } // end class WelcomeServlet2
Uses the result of line 17 as part
of the response to the client
1
<?xml version = "1.0"?>
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5
<!-- Fig. 26.13: WelcomeServlet2.html -->
6
7
<html xmlns = "http://www.w3.org/1999/xhtml">
8
<head>
9
<title>Processing get requests with data</title>
10 </head>
11
12 <body>
13
14
<form action = "/jhtp6/welcome2" method = "get">
<p><label>
15
Type your first name and press the Submit button
16
<br /><input type = "text" name = "firstname" />
17
<input type = "submit" value = "Submit" />
18
19
</p></label>
</form>
20 </body>
21 </html>
Get the first name
from the user.
form data specified
in URL’s query string
as part of a get
request
Dažas piezīmes I (Software Engineering Observation)



If an error occurs during the servlet invocation, the log files in
the logs directory of the Tomcat installation can help you
determine the error and debug the problem.
A get request is limited to standard characters, which means
that you cannot submit any special characters via a get
request. The length of the URL in a get request is limited. For
example, the maximum URL length in Internet Explorer is
2,083 characters. Some Web servers might restrict this even
more.
A get request should not be used for sending sensitive data
(e.g., a password) because the form data is placed in a query
string that is appended to the request URL as plain text and
can be intercepted.
HTTP post pieprasījuma apstrādāšana

HTTP post pieprasījums


Nosūta (post) datus no HTML formas uz server-side formu
apstrādātāju kurš šos datus apstrādā
Tīmekļa pārlūkprogrammas kešo (cache) apskatītās tīkla lapas


Atbildes uz post pieprasījumiem parasti netiek saglabātas
Servlets WelcomeServlet3


Reaģē uz post pieprasījumu
Piemērs ir ļoti līdzīgs iepriekšējam (doGet() metodes vietā tiek
izmantota metode doPost())

Tā tas ir jo izmantotajās klasēs tiek paslēpta atšķirība starp divu
veidu pieprasījumiem
1
2
// Fig. 26.15: WelcomeServlet3.java
// Processing post requests containing data.
3
4
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
5
6
7
8
9
10
11
12
13
14
import
import
import
import
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
java.io.IOException;
java.io.PrintWriter;
public class WelcomeServlet3 extends HttpServlet
{
// process "post" request from client
protected void doPost( HttpServletRequest request,
HttpServletResponse response )
Declare a doPost method to
responds to post requests
throws ServletException, IOException
{
String firstName = request.getParameter( "firstname" );
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();
// send XHTML page to client
// start XHTML document
out.println( "<?xml version = \"1.0\"?>" );
out.printf( "%s%s%s", "<!DOCTYPE html PUBLIC",
" \"-//W3C//DTD XHTML 1.0 Strict//EN\"",
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" );
The request object’s
getParameter method
receives the parameter
name and returns the
corresponding String value
31
out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
32
33
// head section of document
34
out.println( "<head>" );
35
out.println(
36
37
"<title>Processing post requests with data</title>" );
out.println( "</head>" );
38
39
// body section of document
40
out.println( "<body>" );
41
out.println( "<h1>Hello " + firstName + ",<br />" );
42
out.println( "Welcome to Servlets!</h1>" );
43
out.println( "</body>" );
44
45
// end XHTML document
46
out.println( "</html>" );
47
out.close(); // close stream to complete the page
48
} // end method doPost
49 } // end class WelcomeServlet3
1
<?xml version = "1.0"?>
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5
<!-- Fig. 26.16: WelcomeServlet3.html -->
6
7
<html xmlns = "http://www.w3.org/1999/xhtml">
8
<head>
9
<title>Handling an HTTP Post Request with Data</title>
10 </head>
11
12 <body>
13
14
<form action = "/jhtp6/welcome3" method = "post">
<p><label>
15
Type your first name and press the Submit button
16
<br /><input type = "text" name = "firstname" />
17
<input type = "submit" value = "Submit" />
18
19
</label></p>
</form>
20 </body>
21 </html>
Provide a form in which the user
can input a name in the text
input element firstname, then
click the Submit button to
invoke WelcomeServlet3
Pieprasījumu redirektēšana (redirecting requests)



Dažreiz pieprasījumus ir nepieciešams pārsūtīt tālāk uz citu
vietu. Piemēram, citu serveri vai citu tīmekļa lapu.
To var realizēt lietojot HttpServletResponse objecta
sendRedirect metodi.
Servlets RedirectServlet

Pārsūta pieprasījumu uz citu resursu
1
2
// Fig. 26.18: RedirectServlet.java
// Redirecting a user to a different Web page.
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import
import
import
import
import
import
17
18
19
20
21
22
23
24
25
26
27
28
29
30
javax.servlet.ServletException;
javax.servlet.http.HttpServlet;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
java.io.IOException;
java.io.PrintWriter;
public class RedirectServlet extends HttpServlet
{
// process "get" request from client
protected void doGet( HttpServletRequest request,
HttpServletResponse response )
throws ServletException, IOException
{
Obtains the page parameter
from the request.
Determine if the value is either
“deitel” or “welcome1”
String location = request.getParameter( "page" );
if ( location != null )
{
if ( location.equals( "deitel" ) )
response.sendRedirect( "http://www.deitel.com" );
else if ( location.equals( "welcome1" ) )
response.sendRedirect( "welcome1" );
Redirects the request to
www.deitel.com.
} // end if
// code that executes only if this servlet
// does not redirect the user to another page
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();
Redirects the request to the
servlet WelcomeServlet.
31
32
// start XHTML document
33
out.println( "<?xml version = \"1.0\"?>" );
34
35
out.printf( "%s%s%s", "<!DOCTYPE html PUBLIC",
36
" \"-//W3C//DTD XHTML 1.0 Strict//EN\"",
37
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" );
38
39
40
out.println(
"<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
41
42
// head section of document
43
out.println( "<head>" );
44
out.println( "<title>Invalid page</title>" );
45
out.println( "</head>" );
46
47
// body section of document
48
out.println( "<body>" );
49
out.println( "<h1>Invalid page requested</h1>" );
50
out.println( "<p><a href = " +
51
"\"servlets/RedirectServlet.html\">" );
52
out.println( "Click here to choose again</a></p>" );
53
out.println( "</body>" );
54
55
// end XHTML document
56
out.println( "</html>" );
57
out.close();
58
// close stream to complete the page
} // end method doGet
59 } // end class RedirectServlet
1
<?xml version = "1.0"?>
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5
<!-- Fig. 26.19: RedirectServlet.html -->
6
7
<html xmlns = "http://www.w3.org/1999/xhtml">
8
<head>
9
<title>Redirecting a Request to Another Site</title>
10 </head>
11
12 <body>
13
<p>Click a link to be redirected to the appropriate page</p>
14
<p>
15
<a href = "/jhtp6/redirect?page=deitel">
16
17
18
19
www.deitel.com</a><br />
<a href = "/jhtp6/redirect?page=welcome1">
Welcome servlet</a>
</p>
20 </body>
21 </html>
Provide links that allow the user to
invoke the servlet RedirectServlet
Vairāklīmeņu (multitier) lietojumprogrammas


Programmatūra varētu sastāvēt no GUI interfeisa,
pieprasījumu apsrādes loģikas un pastāvīgas datu
glabātuves (datu bāzes)
Divu līmeņu arhitektūra (two-tier architecture)


GUI un programmas loģika ir vienā līmenī un datu bāze otrā
“Resnais” klients.
Fat client
Client
DB
Vairāklīmeņu (multitier) lietojumprogrammas

Trīs līmeņu arhitektūra (three-tier architecture)


Ja “resno” klientu sadalām divās daļās, tad varam runāt par
programmatūras trīs līmeņu arhitektūru.
“Tievais” klients



Pamatuzdevums ir datu reprezentācija un GUI
Satur ļoti nelielu apstrādes loģikas daļu
Aplikācijas loģikas daļa šādā arhitektūras modelī parasti ir
implementēta servera pusē.
Client
Thin client
Logic
DB
Vairāklīmeņu (multitier) lietojumprogrammas

Trīs līmeņu arhitektūra (three-tier architecture)


Tīmekļa serveri parasti reprezentē vidējo līmeni
Trīs līmeņu arhitektūras piemērs

Tīmekļa lapa, kura sadarbojas ar servletu, kurš savukārt
izmanto JDBC, lai nodrošinātu darbu ar datubāzi.

SurveyServlet
Survey.html

MySQL database

1
// Fig. 26.21: SurveyServlet.java
2
// A Web-based survey that uses JDBC from a servlet.
3
package com.deitel.jhtp6.servlets;
4
5
import java.io.PrintWriter;
6
import java.io.IOException;
7
import java.sql.Connection;
8
import java.sql.DriverManager;
9
import java.sql.Statement;
Import interfaces and classes
for database manipulation
10 import java.sql.ResultSet;
11 import java.sql.SQLException;
12 import javax.servlet.ServletConfig;
13 import javax.servlet.ServletException;
14 import javax.servlet.UnavailableException;
15 import javax.servlet.http.HttpServlet;
16 import javax.servlet.http.HttpServletRequest;
17 import javax.servlet.http.HttpServletResponse;
18
19 public class SurveyServlet extends HttpServlet
20 {
21
private Connection connection;
22
private Statement statement;
Declare a Connection to manage
the database connection
23
Declare a Statement for updating the
vote count, totaling all the votes and
obtaining the complete survey result
24
// set up database connection and create SQL statement
25
public void init( ServletConfig config ) throws ServletException
26
{
27
// attempt database connection and create Statements
28
try
29
{
Loads the database
driver, which is
specified in the
initialization parameter
“databaseDriver”
30
Class.forName( config.getInitParameter( "databaseDriver" ) );
31
connection = DriverManager.getConnection(
32
config.getInitParameter( "databaseName" ) );
33
config.getInitParameter( "username" ),
34
config.getInitParameter( "password" ) );
35
36
// create Statement to query database
37
statement = connection.createStatement();
38
} // end try
39
// for any exception throw an UnavailableException to
40
// indicate that the servlet is not currently available
41
catch ( Exception exception )
42
{
43
exception.printStackTrace();
44
throw new UnavailableException(exception.getMessage());
} // end catch
45
46
47
}
// end method init
Attempt to open a connection
to the animalsurvey database,
the database name, username
and password are specified in
the initialization parameters
Create Statement to
query database.
48
// process survey response
49
protected void doPost( HttpServletRequest request,
HttpServletResponse response )
50
throws ServletException, IOException
51
52
{
53
// set up response to client
54
response.setContentType( "text/html" );
55
PrintWriter out = response.getWriter();
56
57
// start XHTML document
58
out.println( "<?xml version = \"1.0\"?>" );
59
60
out.printf( "%s%s%s", "<!DOCTYPE html PUBLIC",
61
" \"-//W3C//DTD XHTML 1.0 Strict//EN\"",
62
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" );
63
64
65
out.println(
"<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
66
67
// head section of document
68
out.println( "<head>" );
69
70
// read current survey response
71
int value =
72
73
74
Integer.parseInt( request.getParameter( "animal" ) );
String sql;
Obtain the survey
response
75
// attempt to process a vote and display current results
76
try
77
{
78
// update total for current survey response
79
sql = "UPDATE surveyresults SET votes = votes + 1 " +
80
81
"WHERE id = " + value;
statement.executeUpdate( sql );
Create sql to update total
for current survey response
Execute sql statement to update total
for current survey response
82
83
// get total of all survey responses
84
sql = "SELECT sum( votes ) FROM surveyresults";
85
ResultSet totalRS = statement.executeQuery( sql );
86
totalRS.next(); // position to first record
87
int total = totalRS.getInt( 1 );
Create query to get total of
all survey responses
Execute query to get total
of all survey responses
88
89
// get results
90
sql = "SELECT surveyoption, votes, id FROM surveyresults " +
91
"ORDER BY id";
92
ResultSet resultsRS = statement.executeQuery( sql );
93
out.println( "<title>Thank you!</title>" );
94
out.println( "</head>" );
95
96
out.println( "<body>" );
97
out.println( "<p>Thank you for participating." );
98
out.println( "<br />Results:</p><pre>" );
99
Create query to
get survey results
Execute query to get
survey results
100
101
// process results
int votes;
102
103
while ( resultsRS.next() )
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
{
Loop through all records
in resultsRS
out.print( resultsRS.getString( 1 ) );
Obtain the value of the first
out.print( ": " );
column from the current record
votes = resultsRS.getInt( 2 );
out.printf( "%.2f", ( double ) votes / total * 100 );
out.print( "% responses: " );
out.println( votes );
Obtain the value of the second
} // end while
column from the current record
resultsRS.close();
out.print( "Total responses: " );
out.print( total );
// end XHTML document
out.println( "</pre></body></html>" );
out.close();
} // end try
// if database exception occurs, return error page
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
out.println( "<title>Error</title>" );
out.println( "</head>" );
out.println( "<body><p>Database error occurred. " );
out.println( "Try again later.</p></body></html>" );
out.close();
130
} // end catch
131
132
} // end method doPost
133
134
// close SQL statements and database when servlet terminates
135
public void destroy()
136
{
137
// attempt to close statements and database connection
138
try
139
{
140
statement.close();
141
connection.close();
Close Statement and
database connection
142
} // end try
143
// handle database exceptions by returning error to client
144
catch ( SQLException sqlException )
145
{
146
147
148
sqlException.printStackTrace();
} // end catch
} // end method destroy
149 } // end class SurveyServlet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Fig. 26.22: Survey.html -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Survey</title>
</head>
<body>
<form method = "post" action = "/jhtp6/animalsurvey">
<p>What is your favorite pet?</p>
15
<p>
16
<input type = "radio" name = "animal"
17
value = "1" />Dog<br />
18
<input type = "radio" name = "animal"
19
value = "2" />Cat<br />
20
<input type = "radio" name = "animal"
21
value = "3" />Bird<br />
22
<input type = "radio" name = "animal"
23
value = "4" />Snake<br />
24
<input type = "radio" name = "animal"
25
value = "5" checked = "checked" />None
26
</p>
27
<p><input type = "submit" value = "Submit" /></p>
28 </form>
29 </body>
30 </html>
Provide a form in which the user can
select an animal from a list of radio
button, then click the Submit button
to invoke animalsurvey
Deployment descriptors apskatītajam piemēram
Descriptor element
Value
servlet element
servlet-name
description
servlet-class
init-param
animalsurvey
Connecting to a database from a servlet.
com.deitel.jhtp6.servlets.SurveyServlet
param-name
param-value
init-param
param-name
param-value
init-param
param-name
param-value
init-param
param-name
param-value
servlet-mapping element
servlet-name
url-pattern
databaseDriver
com.mysql.jdbc.Driver
databaseName
jdbc:mysql://localhost/animalsurvey
username
jhtp6
password
jhtp6
animalsurvey
/animalsurvey
Jautājumi ?