+ All Categories
Home > Documents > Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http...

Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http...

Date post: 15-Mar-2018
Category:
Upload: hoangkhuong
View: 236 times
Download: 3 times
Share this document with a friend
34
Servlets and JSP 1 Chapter 13: Servlets And JSP
Transcript
Page 1: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

1

Chapter 13: Servlets And JSP

Page 2: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

2

Contents

Contents ................................................................................................................... 2

Section 1: Servlets........................................................................................................................... 4

Introduction ............................................................................................................. 5

Java Web Support ................................................................................................... 6

Servlet Life Cycle ................................................................................................... 7

Servlet Classes ........................................................................................................ 8

HTML Form ............................................................................................................ 9

doGet Method ........................................................................................................11

HttpServletRequest Class ......................................................................................12

HttpServletRequest Methods ................................................................................13

doPost Method ......................................................................................................14

Status Codes ..........................................................................................................15

init Method ............................................................................................................16

Cookies ..................................................................................................................17

Request Dispatching ..............................................................................................18

Section 2: Java Server Pages ......................................................................................................... 20

Java Server Pages ..................................................................................................21

JSP Statements ......................................................................................................22

Implicit Objects .....................................................................................................23

Directives ..............................................................................................................24

Actions ..................................................................................................................25

Declaration ............................................................................................................26

Expressions............................................................................................................27

Scriptlets ................................................................................................................28

JSP Database Example ..........................................................................................31

Equivalent Servlet Code ........................................................................................32

Summary ...............................................................................................................34

Page 3: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

3

Objectives

After completing this unit you will be able to:

Explain the purpose and use of Servlets and Java Server Pages

Develop Servlets and JSPs

Understand the life cycle of a servlet

Explain the use of the form tag

Explain the use of cookies

Differentiate between JSP tags

Page 4: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

4

Section 1: Servlets

Page 5: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

5

Introduction

Web programming is oriented around a web server and web browsers. The web server provides

HTML pages and other services to the browser. The Common Gateway Interface (CGI) is a

standard used to communicate between the server and browser. CGI programs reside on the

server and provide services to a client browser.

There is not a specific CGI language. Common languages used to support CGI include C/C++,

Java, PHP, ASP and Pearl.

Page 6: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

6

Java Web Support

Java provides web support through several technologies:

Applets

Servlets

Java Server Pages (JSP)

Applets are browser-based programs and provide interactivity on the browser side. Servlets are

Java programs that run on the server side and function as CGI programs.

JSP are Java programs that run on the server side and also function as CGI programs. They are

essentially Servlets. A JSP file consists of HTML code with Java code embedded within it.

Page 7: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

7

Servlet Life Cycle

The life cycleof a servlet conists of three major steps:

The Servlet created and s initialized through the init method

Zero or more requests are handled

The application is terminated and the destroy method is executed

When a request is made by a browser for the services of a Servlet the server will load the Servlet

unless it has already been loaded. The servlet's init method executes allowing initialization of

the Servlet application. This can be used to open files, establish database connections or other

initialization activities. The ServeltContext object is frequently used to store application-wide

information. Initialization properties can be stored in the application’s web.xml file and are

pased to the init method. These can be accessed using the getInitParameter method.

Next, requests are handled typically using either the doGet or doPost methods are executed.

The servlet's service method is actually executed but normally it simply calls either the doGet or

doPost methods. When the Servlet request is completed the Servlet remains in memory. The

servlet is not normally removed until the server stops. When the web application is terminated

the destroy method is executed.

Page 8: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

8

Servlet Classes

The javax.servlet and javax.servlet.http packages contain classes that support the creation of use

of servlets. The Java Servlet Development Kit (JSDK) is available from sun at

http://java.sun.com/products/servlet

The JSDK contains the servlet packages and a server used to test servlets. The three primary

elements of these packages include:

javax.servlet.Servlet interface

javax.servlet.GenericServlet class

javax.servlet.http.HttpServlet class

The Servlet interface is the core of the servlet family. The GenericServlet class is not used as

frequently and does not support any particular protocol. The HttpServlet class is normally

extended to create a Servlet. It is designed to work with the HTTP. Support is provided for

sending and receiving data to and from a browser.

Page 9: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

9

HTML Form

An HTML form is used to obtain information from a user. The form consists of form elements

that look like controls. A name can be provided for each field.

<html>

<head>

<title>Sample Form</title>

</head>

<body>

<form action="http://www.something.com/cgi-bin/query" method="POST">

<p><input type="text" size="20" name="name">Name </p>

<p><input type="text" size="20" name="id">ID</p>

<p><input type="text" size="20" name="department">Department </p>

<p><input type="submit" name="B1" value="Submit"></p>

</form>

</body>

</html>

When the Submit button is pressed, the contents of these fields are sent to the URL specified by

the action argument of the form.

Page 10: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

10

The GET operation will append the form data to the URL. A ? is used to delimit the data from

the URL. An & is used to separate the form elements from themselves.

http://www.something.com/cgi-bin/query?name=Tom&id=12345&department=101

Page 11: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

11

doGet Method

The doGet method of a servlet will be invoked in response to a get request from a browser. The

method has two arguments:

HttpServletRequest: Represents the information coming from the browser

HttpServletResponse: Represents information sent back to the browser

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class DemoServlet extends HttpServlet {

public void doGet(HttpServletRequest req,

HttpServletResponse res) throws

ServletException, IOException {

res.setContentType("text/html");

PrintWriter out = res.getWriter();

out.println("<HTML>");

out.println("<Head><Title>Demo Servlet Response </Title></Head>");

out.println("<Body><H1>The body of the demo servlet</H1></Body>");

out.println("</HTML>");

}

}

The HttpServletResponse object's setContentType method is to indicate that the output of the

servlet will be an HTML document. It is also used to create a PrintWriter object that is used to

write to the browser.

Page 12: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

12

HttpServletRequest Class

The HttpServletRequest class uses the getParameter method to get access to the form tag fields.

The method has a single String argument that specifies the field of interest and returns a String

that corresponds to that argument.

String name = req.getParameter("Name");

This example redisplays the information from the form.

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class DemoServlet2 extends HttpServlet {

public void doGet(HttpServletRequest req,

HttpServletResponse res) throws

ServletException, IOException {

res.setContentType("text/html");

PrintWriter out = res.getWriter();

out.println("<HTML>");

out.println("<Head><Title>Demo Servlet Response </Title></Head>");

out.println("<Body><H1>Welcome" +

" Name: " + req.getParameter("Name") +

" ID: " + req.getParameter("ID") +

" Department: " + req.getParameter("Department") +

"</H1></Body>");

out.println("</HTML>");

}

}

Page 13: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

13

HttpServletRequest Methods

Other HttpServletRequest methods available include:

getProtocol: Returns the protocol of the request

getServerName: Returns the name of the server

getServerPort: Returns the port number used by the server

getParameterValues: Returns an array of the values associated with a single parameter

(some HTML elements return multiple values)

Page 14: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

14

doPost Method

The doPost method has the same syntax as the doGet method.

public void doPost(HttpServletRequest req,

HttpServletResponse res) throws

ServletException, IOException { … }

As a result the processing of the browser request is placed in either the doGet or doPost methods

and the other method simply calls the other.

public void doGet(HttpServletRequest req,

HttpServletResponse res) throws

ServletException, IOException {

doPost(req, res);

}

Page 15: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

15

Status Codes

With the response object an error code can be sent back to the browser. The sendError method

is used for this purpose. The first argument is the error code number. The second is an optional

string that displays a more customized error message in addition to the default message.

res.sendError(HttpServletResponse.SC_UNAUTHORIZED,

"You are not authorized to access this data");

Constant Value Default Message

SC_OK 200 OK

SC_NO_CONTENT 204 No Content

SC_MOVED_PERMANENTLY 301 Moved Permanently

SC_MOVED_TEMPORARILY 302 Moved Temporarily

SC_UNAUTHORIZED 401 Unauthorized

SC_NOT_FOUND 404 Not Found

SC_INTERNAL_SERVER_ERROR 500 Internal Server Error

SC_NOT_IMPLEMENTED 501 Not Implemented

SC_SERVICE_UNAVAILABLE 503 Service Unavailable

Page 16: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

16

init Method

The init method provides a way for the servlet to perform initialization. A ServletConfig object

is passed to the method.

public void init(ServletConfig conf) throws ServletException { }

The ServletConfig object provides access to initialization parameters that may be passed to the

servlet from the web server .

getInitParameter: Returns a specific parameter

getInitParameterNames: Returns an enumeration of parameters

getServletContext: Returns the ServletContext object

The way that parameters are passed to a servlet is server specific

Page 17: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

17

Cookies

Cookies are files that are stored on a client machine that contain application specific information.

An application may store a cookie to record information about the user’s visit to a web site. The

Cookies class is used to access cookies for a servlet. The request object has a getCookies

method that returns an array of cookies .

Cookie[] cookies = req.getCookies();

for (int i=0; i<cookies.length; i++) {

System.out.println("Cookie " + i + ": " + cookies[i].getName());

}

The response object has an addCookie method to add a cookie.

String value = "value to be assigned to key";

Cookie c = new Cookie("key", value);

res.addCookie(c);

Page 18: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

18

Request Dispatching

The RequestDispatcher class is used to forward a request to another servlet or to include the

content generate by another servlet. The ServletContext class uses the getRequestDispatcher

method to return an instance of the RequestDispatcher class. The forward and include methods

of this class performs the desired tasks.

RequestDispatcher rd = getServletContext().getRequestDispatcher("Name of the Servlet");

rd.forward(req, res);

rd.include(req, res);

These methods pass the request and response objects to the other servlet. If forward method is

used, subsequent output generated by the response object is ignored in the servlet.

Page 19: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

19

ServletContext

The ServletContext represents a global region that the application can use to store information.

This information will be available in all servlets that make up the application. Objects are stored

in the ServletCOntext and persist for the life of the application.

Page 20: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

20

Section 2: Java Server Pages

Page 21: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

21

Java Server Pages

JSP is a technique for generating HTML on the server. They are effectively a Servlet. JSPs are

intended to separate the content generation for the content presentation. Servlets are better suited

for handling business logic. JSPs are better for handling presentation logic.

A JSP file consists of HTML code with embedded Java code.

<HTML>

<BODY>

<% out.println("A simple JSP program"); %>

</BODY>

</HTML>

Page 22: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

22

JSP Statements

There are several types of JSP statements:

Directives: Provides global information about the page

Actions: Used primarily with Java Beans

Declarations: Declares Java variables

Expressions: Java expressions

Scriptlets: Code sequences

There are a number of implicit objects available from within a JSP

Page 23: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

23

Implicit Objects

Implicit objects are predefined objects that the JSP programmer can used to complete a task.

out: Represents the output sent to the client

request: Represents the request from the client

response: Represents the response sent back to the client

pageContext: Provides access to the JSP namespaces

session – References the HttpSession object

application – Refers to the ServletContext

config – Refers to the ServletConfig

page – Refers to the current instance of the page being accessed

exception – When the isErrorPage is set true for a page this will reference an uncaught

exception that was thrown

Page 24: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

24

Directives

Directive types include:

Page: Information about the page

Include: Includes the content of another file

Taglib: Used to extend the JSP tags available

The directive syntax uses a <%@ and %> tags

<%@ directive {attribute="value"} %>

Common directives include:

language: The scripting language is specified

extends: Used to support inheritance

errorPage: Used to specify that the current page is an error page

The include directive allows other files to be included

<%@ include file="file location" %>

Page 25: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

25

Actions

Actions are used to create and act on Java Beans. Important actions include:

useBean: Associates a Java Bean with a JSP

setProperty: Sets the property of a Java Bean

getProperty: Retrieves the property of a Java Bean

forward: Dispatches processing to another resource

Page 26: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

26

Declaration

Declarations are used to declare a variable.

<%! declaration %>

Declarations can be made in other locations but this is a convenient place to make them.

<%! int sum;

Account account;

%>

Page 27: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

27

Expressions

Expressions are a convenient way of displaying the result of an expression in an HTML page.

The syntax is:

<%= expression %>

These can be placed within the JSP file at desired locations.

The average salary is <%= result %> excluding contract employees.

Page 28: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

28

Scriptlets

Scriptlets is where most of the Java code is placed.

<% scriptlet code %>

These can be very simple or rather complex.

<%

out.println("<center><b>Report Number " + reports.getReportNumber() + "</b></center>");

%>

The following illustrates how to populate a drop down combo box using the values found n a

Vector. The static getClientList method returns a vector of user names.

<P><FONT SIZE=5><B>Client List: </B></FONT>

<select name="menu" size="1" STYLE="font-family : times; font-size : 14pt">

<%

Vector<String> names = DatabaseAccess.getClientList();

for(String name : names) {

%>

<option style="font:5"

<%

if (name.equals(recipient)) {

out.print(" SELECTED");

}

%>

>

<%

out.print(name);

%>

</option>

<% } %>

</select>

The generated code may appear similar to:

Page 29: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

29

<P><FONT SIZE=5><B>Client List: </B></FONT>

<select name="menu" size="1" STYLE="font-family : times;

font-size : 14pt">

<option style="font=5"

>

Ralph

</option>

<option style="font=5"

>

Ralph

</option>

<option style="font=5"

>

Ralph

</option>

</select>

How to detect whether a submit button has been pressed form JSP code is illustrated here:

// HTML code

<INPUT TYPE=Submit NAME="Logout" VALUE="Logout" STYLE="width: 2.56in;

height: 0.35in">

//Java Code

String logout = request.getParameter("Logout");

if(logout != null) {

// Logout button was selected

}

Page 30: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

30

Standard JSP Tags

Standard JSP tags are similar to HTML tags in that they provide common functionality for JSP

applications.

Standard JSP tags include:

<jsp:useBean> - Provides access to a specific Javabean

<jsp:setProperty> - Sets the property of a bean

<jsp:getProperty> - Returns the property of a bean

<jsp:param> - Specificies for a include, forward or plugin action

<jsp:include> - Includes a page

<jsp:forward> - Forwards the request to a page

<jsp:plugin> -

The ServletContext can be thought of as a global storage area for a Web application. Each Web

application has a ServletContext. Objects stored in the ServletContext persist for the life of the

Web application, unless removed.

Page 31: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

31

JSP Database Example

<HTML>

<HEAD>

<TITLE>JSP JDBC Example</TITLE>

</HEAD>

<BODY>

<%@ page language="java" import="java.sql.*" %>

<%

Connection con = null;

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con = DriverManager.getConnection("jdbc:odbc:Biblio");

Statement statement = con.createStatement();

ResultSet rs = statement.executeQuery("SELECT * FROM Authors");

%>

<TABLE BORDER="1">

<TR>

<TH>Author ID</TH><TH>Author</TH><TH>Year Born</TH>

<%

while ( rs.next() ) {

out.println("<TR>\n<TD>" + rs.getString("AU_ID") + "</TD>");

out.println("<TD>" + rs.getString("Author") + "</TD>");

out.println("<TD>" + rs.getString("Year_Borned") + "</TD></TR>");

}

rs.close();

}

catch (Exception e) {out.println(e.printTraceStack());}

con.close();

%>

</TR>

</TABLE>

</BODY>

</HTML>

Page 32: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

32

Equivalent Servlet Code

http://articles.techrepublic.com.com/5100-10878_11-1050460.html

the generated java code and the class file for this Servlet are stored in a specified location that

defaults to the TOMCAT_HOME/work directory. This directory can be specified in the Context

element for the Web application. In many instances, if a JSP page is not behaving as expected or

if a stack trace with line numbers is displayed, the generated code can be viewed to help

determine the problem.

import javax.servlet.*;

import javax.servlet.http.*;

import java.sql.*;

import java.io.*;

public class DBServlet extends HttpServlet {

public void doGet(HttpServletRequest req,

HttpServletResponse res) throws

ServletException, IOException {

res.setContentType("text/html");

PrintWriter out = res.getWriter();

out.println("<HTML>");

out.println("<Head><Title> JSP JDBC Example</Title></Head>");

out.println("<Body>”);

Connection con = null;

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con = DriverManager.getConnection("jdbc:odbc:Biblio");

Statement statement = con.createStatement();

ResultSet rs = statement.executeQuery("SELECT * FROM Authors");

out.println("<TABLE BORDER=\"1\">”);

out.println("<TR>”);

out.println("<TH>Author ID</TH><TH>Author</TH>” +

“<TH>Year Borned</TH>”);

Page 33: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

33

while ( rs.next() ) {

out.println("<TR>\n<TD>" + rs.getString("AU_ID") + "</TD>");

out.println("<TD>" + rs.getString("Author") + "</TD>");

out.println("<TD>" + rs.getString("Year_Born") +

"</TD></TR>");

}

rs.close();

}

catch (Exception e) {out.println(e.printTraceStack());}

con.close();

out.println("</TR>”);

out.println("</TABLE >”);

out.println("</BODY >”);

out.println("</HTML >”);

}

}

Page 34: Servlets And JSP 451...Servlets and JSP 8 Servlet Classes The javax.servlet and javax.servlet.http packages contain classes that support the creation of use of servlets. The Java Servlet

Servlets and JSP

34

Summary

Servlets and JSPs provide a way of handling CGI request using Java

The request and response objects provide methods to access information sent by the

client and to send data back to the client

The doGet and doPost methods are the primary methods used by a servlet

The content produced by other servlets can be included or control can be passed to other

servlets

JSPs are HTML files within which Java code is embedded

They are compiled to servlets before being executed


Recommended