SlideShare a Scribd company logo
1 of 22
Download to read offline
© copyright : spiraltrain@gmail.com 1
• What is a servlet?
• Servlet Characteristics
• Possible servlet tasks
• What is a JSP?
• JSP Translation Time
• JSP Request Time
• Form Submissions
• POST and GET Data
• Sessions
• Web Application Structure
• Registering Web Applications
• WAR Files
• Deployment Descriptor
• Defining Custom URL’s
• Preloading pages
• Error pages
• Java Web
Applications
www.spiraltrain.nl
What is a Servlet?
• Java component living inside a Web Server
• Capable of communication through request-response model
• Typically a HTTP servlet generating Dynamic Web Pages
• Compares to other technologies like :
• CGI
• ASP and ASP.NET
• PHP
Java Web Applications 2
Form
HTML
internet
internet
HTML
servlet
1 2 3
6 5 4
www.spiraltrain.nl
Servlet Characteristics
• Possible servlet tasks :
• Read any data sent by the user :
—From HTML form, applet, or custom HTTP client
• Look up HTTP request information like browser capabilities, cookies, etc
• Generate the results from JDBC, RMI, direct computation, legacy app, etc.
• Format the results inside a document in HTML, Excel, etc.
• Set HTTP response parameters :
—MIME type, cookies, compression, etc.
• Send the document to the client
• Servlets handle multiple requests concurrently :
• Typically for each registered servlet only one instance will be loaded in memory
• Container starts a new thread for each request
• Benefits of concurrent access :
• Gives good response times
Java Web Applications 3
www.spiraltrain.nl Java Web Applications 4
Simple Servlet Generating HTML
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
// Use "request" to read incoming HTTP headers and HTML form data
// Use "response" to specify the HTTP response status code and headers
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType = "<!DOCTYPE HTML>n";
// Use "out" to send content to browser
out.println(docType + "<HTML>n" +
"<HEAD><TITLE>Hello Servlets</TITLE></HEAD>n" +
"<BODY BGCOLOR="#FDF5E6">n" +
"<H1>Hello Servlets</H1>n" + "</BODY></HTML>");
}
}
www.spiraltrain.nl Java Web Applications 5
What is a Java Server Page (JSP) ?
• A JSP page uses regular HTML for most of page :
• JSP makes it easier to write, read and maintain HTML
• Dynamic content is marked with special <% and %> tags
• Actually a JSP is a representation of a servlet :
• Entire JSP page gets translated into a servlet (once)
• Servlet is what actually gets invoked (for each request)
<HTML><HEAD><TITLE>JSP declarations</TITLE></HEAD>
<BODY>
<H3>JSP declarations</H3>
<%!
java.util.Date myDate = new java.util.Date();
java.util.Date returnDate() { return myDate; }
%>
<%= returnDate() %>
</BODY>
</HTML>
www.spiraltrain.nl Java Web Applications 6
Benefits of JSP
• JSP supports software reuse through components :
• JavaBeans, Custom tags
• In JSP content and display logic are separated :
• Business logic in Java beans and custom tags
• Presentation logic is captured in the form of a HTML template
• JSP makes it easier to :
• Write, read and maintain the HTML
• JSP supports separation of concerns :
• Designers do the HTML layout
• Developers do the Java programming
• Automatic deployment :
• Recompile automatically when changes are made to JSP pages
• Platform-independent
www.spiraltrain.nl Java Web Applications 7
Translation and Request time
• At page translation time :
• JSP constructs translated into servlet code
• At request time?
• Servlet code gets executed
• No JSP interpretation occurs at request time
• Original JSP page ignored at request time
• Only servlet that resulted from it is used
• When does page translation occur?
• First time JSP page is accessed
• After modification of the JSP
• Does not occur for each request
HTTPRequest
Server
Create Source
Compile
Execute Servlet
JSP File
Changed
?
Y
N
www.spiraltrain.nl Java Web Applications 8
Form Submission
Name
Address
Submit Servlet
Web server
HTTP Request
POST/GET
Form data as name-
value pairs
<form action="http://host/path" method="GET">
• Get request :
• Post request :
<form action="http://host/path" method="POST">
• Pass form data as parameters hidden in request body
http://host/path?name=Bill&address=Seattle
• Pass form data as parameters by appending them in query string :
www.spiraltrain.nl Java Web Applications 9
POST and GET Data
• Sending form data with GET :
<form action="/MyParamsServlet">
Name : <input type = "TEXT" NAME="name"><br>
Address : <input type = "TEXT" NAME="address"><br>
<input type = "SUBMIT">
</form>
• Sending form data with POST :
<form action="/MyParamsServlet" method = "POST">
Name : <input type = "TEXT" NAME="name"><br>
Address : <input type = "TEXT" NAME="address"><br>
<input type ="SUBMIT">
</form>
• A HTML form should use POST, if it has password fields
• Size of parameters is limited to 255 characters using GET
• Parameters are read with request.getParameter("name");
www.spiraltrain.nl Java Web Applications 10
Sessions
• Several mechanisms used to create and track a session id
• Cookies, URL-rewriting, Hidden Form Fields
Session 1
Session 2
Server
Client 1
Client 2
Session ID 1
Session ID 2
www.spiraltrain.nl Java Web Applications 11
Web Applications
• Bundled together in a single directory hierarchy or file
• Servlets, JSP pages, HTML files, utility classes, beans, tag libraries, etc
• Often also packed together in WAR file
• Access to content in the Web app is always through a URL :
• URL has common prefix like http://host/webAppPrefix/blah/blah
• Deployment descriptor web.xml :
• Controls many aspects of Web application behavior
• Files in WEB-INF not directly accessible to clients :
• Server can use RequestDispatcher to forward to pages in WEB-INF
• Portability :
• All compliant servers support Web apps
• Can redeploy on new server by moving a single file
• Each Web application has its own :
• ServletContext, Class loader, Sessions, URL prefix, Directory structure
www.spiraltrain.nl
Web Application Structure
12
web.xml
Servlets and utility classes
.jar files, library classes bundled in jar
.tld files, tag library descriptor files
Directory for creditcard web application
Tomcat root directory for web apps
Servlets and utility classes in com package
Servlets and utility classes in com.company package
MANIFEST.MF and context.xml
html and jsp files,
CSS and image files,
Or in subdirectories
Java Web Applications
www.spiraltrain.nl Java Web Applications 13
Registering Web Applications
• Process is server-specific :
• Portable :
— File structure and deployment descriptor (web.xml).
• Not portable :
— The way to tell a server where a Web app is located
— The way to assign a URL prefix
• Tomcat has configurable autodeploy feature :
• Just drop directory or WAR file in install_dir/webapps
• JRun and others have similar "autodeploy" feature
• Put directory anywhere, add Context entry to install_dir/conf/server.xml
• Use administration console :
• Tomcat, JBoss, WebLogic, WebSphere
www.spiraltrain.nl Java Web Applications 14
WAR Files
• WAR files are simply JAR files with a different file extension :
• And JAR files are simply ZIP files
• All servers are required to support Web apps in WAR files :
• Technically, they are not absolutely required to support unbundled Web apps
• To create a WAR file :
• Change directory to top-level Web app directory
jar cvf webAppName.war *
• Or use Zip utility (or "Create Compressed Folder" on XP)
• Registering is still server-specific :
• On Tomcat just drop WAR file in install_dir/webapps
• webAppName becomes Web application URL prefix
Exercise
Deploy WAR Files
www.spiraltrain.nl Java Web Applications 15
Deployment Descriptor
• Filename : web.xml
• Location :
• Tomcat-specific default for all web applications install_dir/conf/web.xml
• Combined with yourWebApp/WEB-INF/web.xml
• Read : usually only when server starts
• Many servers have "hot deploy" option
• Tomcat monitors web.xml and reloads Web app when web.xml changes
• Basic format :
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=
http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd version="3.1">
<!-- "Real" elements go here. All are optional. -->
</web-app>
www.spiraltrain.nl Java Web Applications 16
Defining Custom URLs
• Java code :
package myPackage; ...
public class MyServlet extends HttpServlet { ... }
• web.xml entry in <web-app...>...</web-app>
• Give name to servlet :
<servlet>
<servlet-name>MyName</servlet-name>
<servlet-class>myPackage.MyServlet</servlet-class>
</servlet>
• Give address, URL mapping, to servlet :
<servlet-mapping>
<servlet-name>MyName</servlet-name>
<url-pattern>/MyAddress</url-pattern>
</servlet-mapping>
• Resultant URL :
• http://hostname/webappName/MyAddress
www.spiraltrain.nl 17
Servlet Initialization
• In init method through ServletConfig.getInitParameter
• init parameters typically set in web.xml
• Common to use init even when you don’t read parameters
• For complex initializations :
• Store the data in a separate file
• Use the init parameters to give the location of that file
• Example entries in web.xml :
<servlet>
<servlet-name>Counter</servlet-name>
<servlet-class>basics.Counter</servlet-class>
<init-param>
<param-name>CountFile</param-name>
<param-value>c:Tomcat 8count.dat</param-value>
</init-param>
</servlet>
Java Web Applications
www.spiraltrain.nl Java Web Applications 18
Application-Wide Initialization Parameters
• web.xml element : context-param
<context-param>
<param-name>support-email</param-name>
<param-value>blackhole@mycompany.com</param-value>
</context-param>
• Read with getInitParameter method of ServletContext
• Problem is who should call getInitParameter :
• load-on-startup gives partial solution
• Listeners give much better answer
www.spiraltrain.nl Java Web Applications 19
Loading Servlets or JSP Pages on Server Start
• What if servlet or JSP page defines data that others use?
<servlet>
<servlet-name>...</servlet-name>
<servlet-class>...</servlet-class>
<!-- Or jsp-file instead of servlet-class -->
<load-on-startup/>
</servlet>
• Specify relative order of multiple preloaded resources with :
<load-on-startup>1</load-on-startup>
<load-on-startup>2</load-on-startup>
www.spiraltrain.nl Java Web Applications 20
Designating Pages to Handle Errors
• Pages to use for specific HTTP status codes :
• Use the error-code element within error-page
• Pages to use when specific uncaught exceptions are thrown :
• Use the exception-type element within error-page
• Page-specific error pages :
• Use <%@ page errorPage="Relative URL" %>
— In individual JSP page, not in web.xml
<web-app...>
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/NotFound.jsp</location>
</error-page>
</web-app>
www.spiraltrain.nl Java Web Applications 21
Other web.xml Capabilities
• You can set Web-app-wide default timeout :
<session-config>
<session-timeout>time in minutes</session-timeout>
</session-config>
• A value of 0 or negative number :
— Indicates that default sessions should never automatically time out
• If no session-config :
• Default session timeout is server-specific
• Allowing execution on multiple systems in cluster :
• Distributable
• More capabilities :
• Designating security settings
• Declaring filters
• Setting up listeners
© copyright : spiraltrain@gmail.com
Summary : Java Web Applications
• Servlet is a Java Component living in a Web Server :
• Capable of communication through request-response model
• Servlets allow concurrent access
• A JSP file consists of markup with embedded Java code :
• Translation time : JSP is translated to Java servlet code and compiled
• Request time : The compiled .class files are executed
• Java Web Applications have a well defined structure :
• WEB-INF directory contains classes subdirectory and deployment descriptor
• Web applications are typically packaged in .war files
• Deployment descriptor web.xml :
• Central configuration file for a web application read when web server starts
• Contains configuration parameters of web application
• Custom URL’s in web.xml define servlet access :
• servlet (servlet-class, servlet-name)
• servlet-mapping (servlet-name, url-pattern)
Java Web Applications 22
Exercise
Deploying Servlets

More Related Content

Similar to Java-Web-Applications.pdf

Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSPGary Yeh
 
Introduction to the Client OM in SharePoint 2010
Introduction to the Client OM in SharePoint 2010Introduction to the Client OM in SharePoint 2010
Introduction to the Client OM in SharePoint 2010Ben Robb
 
Node.js to the rescue
Node.js to the rescueNode.js to the rescue
Node.js to the rescueMarko Heijnen
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.pptWalaSidhom1
 
CNIT 129S - Ch 3: Web Application Technologies
CNIT 129S - Ch 3: Web Application TechnologiesCNIT 129S - Ch 3: Web Application Technologies
CNIT 129S - Ch 3: Web Application TechnologiesSam Bowne
 
Lecture 2: Servlets
Lecture 2:  ServletsLecture 2:  Servlets
Lecture 2: ServletsFahad Golra
 
Jeetrainers.com coursejspservlets00
Jeetrainers.com coursejspservlets00Jeetrainers.com coursejspservlets00
Jeetrainers.com coursejspservlets00Rajesh Moorjani
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to TornadoGavin Roy
 
Introducing asp
Introducing aspIntroducing asp
Introducing aspaspnet123
 
Servlets Java Slides & Presentation
Servlets Java Slides & Presentation Servlets Java Slides & Presentation
Servlets Java Slides & Presentation Anas Sa
 

Similar to Java-Web-Applications.pdf (20)

20jsp
20jsp20jsp
20jsp
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
 
Introduction to the Client OM in SharePoint 2010
Introduction to the Client OM in SharePoint 2010Introduction to the Client OM in SharePoint 2010
Introduction to the Client OM in SharePoint 2010
 
Java part 3
Java part  3Java part  3
Java part 3
 
Node.js to the rescue
Node.js to the rescueNode.js to the rescue
Node.js to the rescue
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
CNIT 129S - Ch 3: Web Application Technologies
CNIT 129S - Ch 3: Web Application TechnologiesCNIT 129S - Ch 3: Web Application Technologies
CNIT 129S - Ch 3: Web Application Technologies
 
Lecture 2: Servlets
Lecture 2:  ServletsLecture 2:  Servlets
Lecture 2: Servlets
 
Jsp
JspJsp
Jsp
 
Jeetrainers.com coursejspservlets00
Jeetrainers.com coursejspservlets00Jeetrainers.com coursejspservlets00
Jeetrainers.com coursejspservlets00
 
Coursejspservlets00
Coursejspservlets00Coursejspservlets00
Coursejspservlets00
 
Servlets
ServletsServlets
Servlets
 
AJppt.pptx
AJppt.pptxAJppt.pptx
AJppt.pptx
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to Tornado
 
Introducing asp
Introducing aspIntroducing asp
Introducing asp
 
Lect06 tomcat1
Lect06 tomcat1Lect06 tomcat1
Lect06 tomcat1
 
Tomcat server
 Tomcat server Tomcat server
Tomcat server
 
Servlets
ServletsServlets
Servlets
 
Servlets Java Slides & Presentation
Servlets Java Slides & Presentation Servlets Java Slides & Presentation
Servlets Java Slides & Presentation
 
Webapplication ppt prepared by krishna ballabh gupta
Webapplication ppt prepared by krishna ballabh guptaWebapplication ppt prepared by krishna ballabh gupta
Webapplication ppt prepared by krishna ballabh gupta
 

Recently uploaded

Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 

Recently uploaded (20)

Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 

Java-Web-Applications.pdf

  • 1. © copyright : spiraltrain@gmail.com 1 • What is a servlet? • Servlet Characteristics • Possible servlet tasks • What is a JSP? • JSP Translation Time • JSP Request Time • Form Submissions • POST and GET Data • Sessions • Web Application Structure • Registering Web Applications • WAR Files • Deployment Descriptor • Defining Custom URL’s • Preloading pages • Error pages • Java Web Applications
  • 2. www.spiraltrain.nl What is a Servlet? • Java component living inside a Web Server • Capable of communication through request-response model • Typically a HTTP servlet generating Dynamic Web Pages • Compares to other technologies like : • CGI • ASP and ASP.NET • PHP Java Web Applications 2 Form HTML internet internet HTML servlet 1 2 3 6 5 4
  • 3. www.spiraltrain.nl Servlet Characteristics • Possible servlet tasks : • Read any data sent by the user : —From HTML form, applet, or custom HTTP client • Look up HTTP request information like browser capabilities, cookies, etc • Generate the results from JDBC, RMI, direct computation, legacy app, etc. • Format the results inside a document in HTML, Excel, etc. • Set HTTP response parameters : —MIME type, cookies, compression, etc. • Send the document to the client • Servlets handle multiple requests concurrently : • Typically for each registered servlet only one instance will be loaded in memory • Container starts a new thread for each request • Benefits of concurrent access : • Gives good response times Java Web Applications 3
  • 4. www.spiraltrain.nl Java Web Applications 4 Simple Servlet Generating HTML import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { // Use "request" to read incoming HTTP headers and HTML form data // Use "response" to specify the HTTP response status code and headers response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = "<!DOCTYPE HTML>n"; // Use "out" to send content to browser out.println(docType + "<HTML>n" + "<HEAD><TITLE>Hello Servlets</TITLE></HEAD>n" + "<BODY BGCOLOR="#FDF5E6">n" + "<H1>Hello Servlets</H1>n" + "</BODY></HTML>"); } }
  • 5. www.spiraltrain.nl Java Web Applications 5 What is a Java Server Page (JSP) ? • A JSP page uses regular HTML for most of page : • JSP makes it easier to write, read and maintain HTML • Dynamic content is marked with special <% and %> tags • Actually a JSP is a representation of a servlet : • Entire JSP page gets translated into a servlet (once) • Servlet is what actually gets invoked (for each request) <HTML><HEAD><TITLE>JSP declarations</TITLE></HEAD> <BODY> <H3>JSP declarations</H3> <%! java.util.Date myDate = new java.util.Date(); java.util.Date returnDate() { return myDate; } %> <%= returnDate() %> </BODY> </HTML>
  • 6. www.spiraltrain.nl Java Web Applications 6 Benefits of JSP • JSP supports software reuse through components : • JavaBeans, Custom tags • In JSP content and display logic are separated : • Business logic in Java beans and custom tags • Presentation logic is captured in the form of a HTML template • JSP makes it easier to : • Write, read and maintain the HTML • JSP supports separation of concerns : • Designers do the HTML layout • Developers do the Java programming • Automatic deployment : • Recompile automatically when changes are made to JSP pages • Platform-independent
  • 7. www.spiraltrain.nl Java Web Applications 7 Translation and Request time • At page translation time : • JSP constructs translated into servlet code • At request time? • Servlet code gets executed • No JSP interpretation occurs at request time • Original JSP page ignored at request time • Only servlet that resulted from it is used • When does page translation occur? • First time JSP page is accessed • After modification of the JSP • Does not occur for each request HTTPRequest Server Create Source Compile Execute Servlet JSP File Changed ? Y N
  • 8. www.spiraltrain.nl Java Web Applications 8 Form Submission Name Address Submit Servlet Web server HTTP Request POST/GET Form data as name- value pairs <form action="http://host/path" method="GET"> • Get request : • Post request : <form action="http://host/path" method="POST"> • Pass form data as parameters hidden in request body http://host/path?name=Bill&address=Seattle • Pass form data as parameters by appending them in query string :
  • 9. www.spiraltrain.nl Java Web Applications 9 POST and GET Data • Sending form data with GET : <form action="/MyParamsServlet"> Name : <input type = "TEXT" NAME="name"><br> Address : <input type = "TEXT" NAME="address"><br> <input type = "SUBMIT"> </form> • Sending form data with POST : <form action="/MyParamsServlet" method = "POST"> Name : <input type = "TEXT" NAME="name"><br> Address : <input type = "TEXT" NAME="address"><br> <input type ="SUBMIT"> </form> • A HTML form should use POST, if it has password fields • Size of parameters is limited to 255 characters using GET • Parameters are read with request.getParameter("name");
  • 10. www.spiraltrain.nl Java Web Applications 10 Sessions • Several mechanisms used to create and track a session id • Cookies, URL-rewriting, Hidden Form Fields Session 1 Session 2 Server Client 1 Client 2 Session ID 1 Session ID 2
  • 11. www.spiraltrain.nl Java Web Applications 11 Web Applications • Bundled together in a single directory hierarchy or file • Servlets, JSP pages, HTML files, utility classes, beans, tag libraries, etc • Often also packed together in WAR file • Access to content in the Web app is always through a URL : • URL has common prefix like http://host/webAppPrefix/blah/blah • Deployment descriptor web.xml : • Controls many aspects of Web application behavior • Files in WEB-INF not directly accessible to clients : • Server can use RequestDispatcher to forward to pages in WEB-INF • Portability : • All compliant servers support Web apps • Can redeploy on new server by moving a single file • Each Web application has its own : • ServletContext, Class loader, Sessions, URL prefix, Directory structure
  • 12. www.spiraltrain.nl Web Application Structure 12 web.xml Servlets and utility classes .jar files, library classes bundled in jar .tld files, tag library descriptor files Directory for creditcard web application Tomcat root directory for web apps Servlets and utility classes in com package Servlets and utility classes in com.company package MANIFEST.MF and context.xml html and jsp files, CSS and image files, Or in subdirectories Java Web Applications
  • 13. www.spiraltrain.nl Java Web Applications 13 Registering Web Applications • Process is server-specific : • Portable : — File structure and deployment descriptor (web.xml). • Not portable : — The way to tell a server where a Web app is located — The way to assign a URL prefix • Tomcat has configurable autodeploy feature : • Just drop directory or WAR file in install_dir/webapps • JRun and others have similar "autodeploy" feature • Put directory anywhere, add Context entry to install_dir/conf/server.xml • Use administration console : • Tomcat, JBoss, WebLogic, WebSphere
  • 14. www.spiraltrain.nl Java Web Applications 14 WAR Files • WAR files are simply JAR files with a different file extension : • And JAR files are simply ZIP files • All servers are required to support Web apps in WAR files : • Technically, they are not absolutely required to support unbundled Web apps • To create a WAR file : • Change directory to top-level Web app directory jar cvf webAppName.war * • Or use Zip utility (or "Create Compressed Folder" on XP) • Registering is still server-specific : • On Tomcat just drop WAR file in install_dir/webapps • webAppName becomes Web application URL prefix Exercise Deploy WAR Files
  • 15. www.spiraltrain.nl Java Web Applications 15 Deployment Descriptor • Filename : web.xml • Location : • Tomcat-specific default for all web applications install_dir/conf/web.xml • Combined with yourWebApp/WEB-INF/web.xml • Read : usually only when server starts • Many servers have "hot deploy" option • Tomcat monitors web.xml and reloads Web app when web.xml changes • Basic format : <?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd version="3.1"> <!-- "Real" elements go here. All are optional. --> </web-app>
  • 16. www.spiraltrain.nl Java Web Applications 16 Defining Custom URLs • Java code : package myPackage; ... public class MyServlet extends HttpServlet { ... } • web.xml entry in <web-app...>...</web-app> • Give name to servlet : <servlet> <servlet-name>MyName</servlet-name> <servlet-class>myPackage.MyServlet</servlet-class> </servlet> • Give address, URL mapping, to servlet : <servlet-mapping> <servlet-name>MyName</servlet-name> <url-pattern>/MyAddress</url-pattern> </servlet-mapping> • Resultant URL : • http://hostname/webappName/MyAddress
  • 17. www.spiraltrain.nl 17 Servlet Initialization • In init method through ServletConfig.getInitParameter • init parameters typically set in web.xml • Common to use init even when you don’t read parameters • For complex initializations : • Store the data in a separate file • Use the init parameters to give the location of that file • Example entries in web.xml : <servlet> <servlet-name>Counter</servlet-name> <servlet-class>basics.Counter</servlet-class> <init-param> <param-name>CountFile</param-name> <param-value>c:Tomcat 8count.dat</param-value> </init-param> </servlet> Java Web Applications
  • 18. www.spiraltrain.nl Java Web Applications 18 Application-Wide Initialization Parameters • web.xml element : context-param <context-param> <param-name>support-email</param-name> <param-value>blackhole@mycompany.com</param-value> </context-param> • Read with getInitParameter method of ServletContext • Problem is who should call getInitParameter : • load-on-startup gives partial solution • Listeners give much better answer
  • 19. www.spiraltrain.nl Java Web Applications 19 Loading Servlets or JSP Pages on Server Start • What if servlet or JSP page defines data that others use? <servlet> <servlet-name>...</servlet-name> <servlet-class>...</servlet-class> <!-- Or jsp-file instead of servlet-class --> <load-on-startup/> </servlet> • Specify relative order of multiple preloaded resources with : <load-on-startup>1</load-on-startup> <load-on-startup>2</load-on-startup>
  • 20. www.spiraltrain.nl Java Web Applications 20 Designating Pages to Handle Errors • Pages to use for specific HTTP status codes : • Use the error-code element within error-page • Pages to use when specific uncaught exceptions are thrown : • Use the exception-type element within error-page • Page-specific error pages : • Use <%@ page errorPage="Relative URL" %> — In individual JSP page, not in web.xml <web-app...> <error-page> <error-code>404</error-code> <location>/WEB-INF/NotFound.jsp</location> </error-page> </web-app>
  • 21. www.spiraltrain.nl Java Web Applications 21 Other web.xml Capabilities • You can set Web-app-wide default timeout : <session-config> <session-timeout>time in minutes</session-timeout> </session-config> • A value of 0 or negative number : — Indicates that default sessions should never automatically time out • If no session-config : • Default session timeout is server-specific • Allowing execution on multiple systems in cluster : • Distributable • More capabilities : • Designating security settings • Declaring filters • Setting up listeners
  • 22. © copyright : spiraltrain@gmail.com Summary : Java Web Applications • Servlet is a Java Component living in a Web Server : • Capable of communication through request-response model • Servlets allow concurrent access • A JSP file consists of markup with embedded Java code : • Translation time : JSP is translated to Java servlet code and compiled • Request time : The compiled .class files are executed • Java Web Applications have a well defined structure : • WEB-INF directory contains classes subdirectory and deployment descriptor • Web applications are typically packaged in .war files • Deployment descriptor web.xml : • Central configuration file for a web application read when web server starts • Contains configuration parameters of web application • Custom URL’s in web.xml define servlet access : • servlet (servlet-class, servlet-name) • servlet-mapping (servlet-name, url-pattern) Java Web Applications 22 Exercise Deploying Servlets