Servlet
Servlet
HTTP Methods
Form Parameters
Requests
Responses
Servlet Life Cycle
Review
• How to connect DB using JDBC API
– Required
• RDBMS: SQL Server
• Driver Connection: sqljdbc4.jar
– Steps
• Load Driver
– using Class.forName method
– Driver string: com.microsoft.sqlserver.jdbc.SQLServerDriver
– Exception: ClassNotFoundException
• Create connection String
– protocol:server://ip:port;databaseName=DB[;instanceName=Instance]
• Open connection
– Connection con = DriverManager.getConnection(url, “user", “pass");
– Exception: SQLException
Review
• How to connect DB using JDBC API
– Implementation
Objectives
• How to build the simple web site combining html
and servlet?
– Http Protocol and Methods
– What is Servlet?
– Parameters vs. Variables
– Servlet Life Cycle
– Break down structure component in building web
application
Objectives
Day 1, 2, 3 – Login
Servlet
Day 4, 5 – Search
Break Down
Day 6, 7 – MVC2
JSP
Web Day 8, 9, 10 – CUD, Shopping Carts
Sessions
Web based
App - PBL Day 11, 12 – Login
Framework
JavaBeans
HTML
Servlet
DB Connection Lib
JDBC Driver
Build The Simple Web
Interactive Server Model
2. Send request
Web/App Servlet
Server
1. Click Login 3. Check Login
5. Response the
result page
DAO
4. Query DB
6. Browser
displays
Welcome page/
invalid page DB
Client Server
Build The Simple Web
Abstraction
Web Server
Container
1. Send request C 2. Call
3. Query
5. Response DAO DB
4. Render/Send
6. Display V
Build The Simple Web
How to Create Web Application Project
• Requirement tools: NetBeans IDE 7.4/8.0.2/8.1
• Create a new Web application project
– Using Tomcat Server
– JavaEE 5
– Uncheck Deploy on Save
HTML Introduction
What is HTML?
• HTML is a presentation language for describing
web pages.
– HTML stands for Hyper Text Markup Language
– HTML is not a programming language, it is a
markup language
– A markup language is a set of markup tags
– HTML uses markup tags to describe web pages
• HTML Documents = Web Pages
– HTML documents describe web pages
– HTML documents contain HTML tags and plain text
– HTML documents are also called web pages
HTML Introduction
HTML Tags
• HTML markup tags are usually called HTML tags
– HTML tags are keywords surrounded by angle brackets, that
begin “<” and finish with “>”, like <html>
– HTML tags normally come in pairs like <b> and </b>
• The first tag in a pair is the start tag, the second tag is the end tag
• Start and end tags are also called opening tags and closing tags.
• Web Browser
– The purpose of a web browser (like Internet Explorer, or Firefox,
etc) is to read HTML documents and display them as web pages.
– The browser does not display the HTML tags, but uses the tags to
interpret the content of the page
HTML Introduction
Example
Form Parameters
HTML Form
• A form is defined on a web page starting with the opening
tag <form> and ending with closing tag </form>
• Syntax: <form action=“target” [method=“HTTP method”]>
– action attribute presents value that contains some target
resource in the web application (e.g. Servlet or JSP)
– method attribute denotes the HTTP method to execute. The
default is to execute HTTP GET when the form is submitted
– Notes: the action parameter obeys the rules
• action=“targetServlet”: the browser will assume that targetServlet resides
in the same place the default page as index.jsp or index.html
• action=“/targetServlet”: the browser will asume the the path at the root
location for specified host (http://host:port).
– Ex: http://localhost:8086/targetServlet
• action=“target?queryString”:the request send the data in queryString to
the URL
Form Parameters
Input Tag
• Is used to input data
• Syntax: <input type=“…” [value=“…” name=“…”] />
– type attribute
• Dedicates to holding a single line of text (text).
– The size attribute specifies the width of text field in characters
– The maxlength attribute controls the maximum number of characters that a user can type
into the text field
• A browser should mask the character typed in by the user (password)
• Being a hidden field – is invisible (hidden)
• Put one or more small boxes that can be clicked to tick or check the
corresponding value denote (checkbox)
– checked=“checked” sets up the checkbox as already selected
• The choice made is mutual exclusive (radio)
– The name attribute is crucial to tying together a group of radio buttons
• Send the form data to the URL designated by the action attribute (submit)
• A request to the client browser to reset all the values within the form
(reset)
• Defining the “custom button” which is connected to some soft of script
(button)
– name attribute supplies the parameter name
Form Parameters
Select & Text Area Tag
• HTML Forms – select tag
– Sets up a list of values to choose (combo box or pop-up menu, or list box)
– Syntax: <select name=“…” [size=“…” multiple] >
<option value=“…” [selected]>…</option>
…
</select>
• option tag
– The user-visible text goes between opening and closing option tag
– The value attribute passes the value in the parameter
• multiple attribute presents the control that can choose more than one
• HTML Forms – textarea tag
– Presents multiple line of text
– Syntax: <textarea name=“…” rows=“…” cols=“…”>
…
</textarea>
• The text value put in opening and closing tag is passed as the parameter value to
server
• rows present the number of visible lines
• cols present the number of characters to displayed across the width of the area
Form Parameters
Examples
Form Parameters
Examples
Build The Simple Web
Views
Build The Simple Web
Interactive Server Model
2. Send request
Web/App Servlet
Server
1. Click Login
3. Check Login
5. Response the
result page
DAO
4. Query DB
6. Browser
displays
Welcome page/
DB
invalid page
Client Server
HTTP Protocols
Overview
1. Convert http://microsoft.com/ to 192.168.54.3:80
Connect
2. Send a request to Web Server (index.html)
4. The result is responsed to Browser
http://microsoft.com/index.html
192.168.54.3:80
5. Web Browser views 3. Web Server
the result which processes a request
contains a markup (connecting DB,
language calculating, call
• Request – Response pairs service …)
• Stateless
• Port 80 is default
HTTP Protocols
HTTP Requests
DB
Client Server
HTTP Protocols
HTTP Responses
Blank line
HTTP Protocols
HTTP Responses
• Indicates status of request process (HTTP version,
response code, status)
• Ex: HTTP/1.1 200 OK
•Server. Ex:
BlankServer:
line JavaWebServer
•Last modified date.
• Ex: Last-modified: Tuesday, 24-Mar-09 8:30:34 GMT
•Content length. Ex: Content-length: 100
•Content type. Ex: Content-type: text/plain
HTTP Protocols
HTTP Responses – Example
HTTP Protocols
HTTP Responses – Example
HTTP Protocols
Some commonly Status codes
Code Associated Message Meaning
… … -…
HTTP Protocols
• GET HTTP Methods – Basic
– Is the method commonly used to request a resource/ get
information (access static resource such as HTML doc and
images or retrieve dynamic information such as query parameters)
from server
– The restricted length of query string, that is introduced by the
question mark “?”
– Is trigger by
• Typing into the address line of the browser and pressing GO
• Clicking on a link in a web page
• Pressing the submit button in an HTML form with GET method
• POST
– Sends data of unlimited length to the web server.
– Is the method commonly used for passing user input/ sending
information to the server (access dynamic resources and enable
secure data in HTTP request because the request parameters are
passed in the body of request)
– No limit and cannot be booked mark or emailed
HTTP Protocols
HTTP Methods – Extends
• HEAD
– Returns the headers identified by the request URL.
– Is identical to the GET method but it doesn’t return a message body
– Is an economical way of checking that a resource is valid and accessible
• OPTIONS
– Returns the HTTP methods the server supports.
• PUT
– Requests the server to store the data enclosed in the HTTP message body at a
location provided in the request URL.
• DELETE
– Requests the server to delete the resource identified by the request URL.
• TRACE
– Is used for debugging and testing the request sent to the server. It is useful
when the request sent to the server reaches through the proxies.
• Idempotency and Safety
– GET, TRACE, OPTIONS, and HEAD
Build The Simple Web
Interactive Server Model
2. Send request
Web/App Servlet
Server
1. Click Login
3. Check Login
5. Response the
result page
DAO
4. Query DB
6. Browser
displays
Welcome page/
invalid page DB
Client Server
The Servlet Model
Common Gateway Interface (CGI)
• A small program (*.exe) is written
in languages such as C/C++, Perl,
... for the gateway programs.
• Used in complex applications, such
as Web pages
• A set of standards followed to
interface applications form client
side to a Web Server
• Enables the Web server to send
information to other files and Web
browsers
• Helps to process the inputs to the
form on the Web page
• Enables to obtain information and
use it on the server machine (server
side)
• When the Browser sends request
to server, CGI instantaties to
receive and process.
The Servlet Model
Common Gateway Interface (CGI)
• Disadvantages
– Reduced efficiency
The Servlet Model
Common Gateway Interface (CGI)
• Disadvantages
– Reduced efficiency
– Reloading Perl interpreter
• The widely accepted platform for writing CGI script is Perl.
Each time the server receives are quest, the Perl interpreter
needs to be reloaded.
– Interactive: not suitable for graphical or highly
interactive programs
– Time consuming and more memory consumed
– Debugging: error detection is difficult
– Not support Session
The Servlet Model
Servlets
• Are Java classes that dynamically process HTTP requests and construct
responses
• Are Java codes that are used to add dynamic content to Web server.
• There is only a single instance of Servlet created on the Web server.
• To service multiple clients’ request, the Web server creates multiple threads
for the same Servlet instance (Overcome CGI’s consumed more memory)
• Gets auto refreshed on receiving a request each time
• A Servlet’s initializing code is used only for initializing in the 1st time
• Merits
– Enhanced efficiency (initializing only once, auto refresh)
– Ease to use (using Java combining HTML)
– Powerful (using Java)
– Portable
– Safe and cheap
• Demerits
– Low-level HTML documentation (Static well-formed-ness is not maintained)
– Unclear-session management (flow of control within the codes is very unclear)
The Servlet Model
Servlets
2. Send Request
3. Dispatch to Application
Figure 4.9: Servlet with Annotations, Web Component Development Using Java, Aptech
World Wide
The Servlet Model
Annotations – Servlets
• WebServlet
– Is used to provide the mapping information of the Servlet.
– Is processed by the servlet container at the time of the deployment.
Attributes Descriptions
name Specifies the Servlet name. This attribute is optional.
An array of url patterns use for accessing the Servlet,
urlPatterns this attribute is required and should register one url
pattern
An array of @WebInitParam, that can be used to pass
initParams servlet configuration parameters. This attribute is
optional.
…
The Servlet Model
Servlets
Servlets
Database
The Servlet Model
Architecture of the Servlet packages
• The javax.servlet package provides interfaces and classes for writing
servlets
• The important interface is javax.servlet.Servlet
• When a servlet accepts a call from a client, it receives two objects:
• ServletRequest, which encapsulates the communication from the client to the
server.
• ServletResponse, which encapsulates the communication from the servlet to the
client.
The Servlet Model
GenericServlet class
• Defines a servlet that is not protocol dependent
• Implements the Servlet, the ServletConfig, and the
java.io.Serializable interfaces
• Retrieves the configuration information by implementing the
ServletObject
• Some methods
Methods Descriptions
- public void init() throws ServletException
init
- Initializes the servlet
Servlet - public abstract void service(ServletRequest req,
Life ServletResponse res) throws ServletException,
service Cycle
IOException
defined - Called by the container to respond to a servlet request
in Generic
destroy - public void destroy(): cleaning the servlet
The Servlet Model
The Servlet Life Cycle
5. first to nth req
Uninstantiated Instantiation Initialization meet request Meet multi request
1. begin to 2. deploying
deploy
success
init() success
service()
4. first req
3. deployed failure
Detroy received request and using
thread
Web/App Servlet
Server
1. Click Login
3. Check Login
5. Response the
result page
DAO
4. Query DB
6. Browser
displays
Welcome page/
invalid page DB
Client Server
Summary
• How to build the simple web site using html
and servlet?
– Http Protocol and Methods
– What is Servlet?
– Parameters vs. Variables
– Servlet Life Cycle
– Break down structure component in
building web application
Q&A
Summary
Web Server
Container
1. Send request C 2. Call
3. Query
5. Response DAO DB
4. Render/Send
6. Display V
Q&A
Exercises
• Do it again all of demos
• Using servlet to write the programs as the following
requirement
– Present the Login form (naming LoginServlet) with title Login,
header h1 – Login, 02 textbox with naming txtUser and
txtPass, and the Login button
• Rewrite above Login application combining with DB
– Writing the ColorServlet that presents “Welcome to Servlet
course” with yellow in background and red in foreground
– Writing the ProductServlet includes a form with a combo box
containing Servlet & JSP, Struts & JSF, EJB, XMJ, Java Web
Services, and the button with value Add to Cart
Next Lecture
• How to deploy the Web Application to Web
Server?
– Web applications Structure
– Request Parameters vs. Context Parameters vs.
Config/Servlet Parameters
– Application Segments vs. Scope
• How to transfer from resources to others
with/without data/objects?
– Attributes vs. Parameters vs. Variables
– Redirect vs. RequestDispatcher
– RequestDispatcher vs. Filter
Next Lecture
Day 1, 2, 3 – Login
Servlet
Day 4, 5 – Search
Break Down
Day 6, 7 – MVC2
JSP
Web Day 8, 9, 10 – CUD, Shopping Carts
Sessions
Web based
App - PBL Day 11, 12 – Login
Framework
JavaBeans
Web Directory
• Caches of server
– WinXP: C:\Documents and Settings\LoggedUser\Application
Data\NetBeans\version\apache-tomcat-
tomcatVersion_base\work\Catalina \localhost\
– Vista or Win7, 8, 10:
C:\Users\LoggedUser\AppData\Roaming\NetBeans\version\apach
e-tomcat-tomcatVersion_base\work\Catalina\localhost\
– Above location should be gone and cleared when the application
cannot be undeployed or the web servers occur the errors
Appendix
Create a Servlet
Fill or choose
package name