SlideShare uma empresa Scribd logo
1 de 15
Baixar para ler offline
© 2010 Marty Hall
S l t B iServlet Basics
Originals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/csajsp2.html
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.2
© 2010 Marty Hall
For live Java EE training, please see training courses
at http://courses.coreservlets.com/.at http://courses.coreservlets.com/.
Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo,
Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT),
Java 5, Java 6, SOAP-based and RESTful Web Services, Spring,g
Hibernate/JPA, and customized combinations of topics.
Taught by the author of Core Servlets and JSP, More
Servlets and JSP and this tutorial Available at public
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Servlets and JSP, and this tutorial. Available at public
venues, or customized versions can be held on-site at your
organization. Contact hall@coreservlets.com for details.
Agenda
‱ The basic structure of servlets
‱ A simple servlet that generates plain text
‱ A servlet that generates HTML
‱ Using helper classes
‱ Giving URLs to servlets
– @WebServlet annotation
– web.xml file
‱ The servlet life cycle‱ The servlet life cycle
‱ Servlet debugging strategies
4
© 2010 Marty Hall
Overview
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.5
A Servlet’s Job
‱ Read explicit data sent by client (form data)
‱ Read implicit data sent by client
(request headers)
G t th lt‱ Generate the results
‱ Send the explicit data back to client (HTML)
S d th i li it d t t li t‱ Send the implicit data to client
(status codes and response headers)
6
© 2010 Marty Hall
Simple Servlets
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.7
A Servlet That Generates Plain
Text (HelloWorld java)Text (HelloWorld.java)
package testPackage; // Always use packages.
import java io *;import java.io. ;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;p j p
@WebServlet("/hello")
public class HelloWorld extends HttpServlet {
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
th S l tE ti IOE ti {throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}}
}
8
URL assumes you have deployed from a project named “test-app”. Code can be downloaded from
Web site. General form is http://hostName/appName/address-from-WebServlet-annotation.
Review previous tutorial section for info on how to deploy the app from Eclipse.
Interpreting HelloWorld Servlet
‱ @WebServlet("/address")
– This is the URL relative to the app name. More later.
‱ doGet
C d f HTTP GET t d P t l– Code for an HTTP GET request. doPost also common.
‱ HttpServletRequest
Contains anything that comes from the browser– Contains anything that comes from the browser
‱ HttpServletResponse
– Used to send stuff to the browser. Most common isUsed to send stuff to the browser. Most common is
getWriter for a PrintWriter that points at browser.
‱ @Override
– General best practice when overriding inherited methods
‱ But, I will omit on many of my PowerPoint slides to
conserve space. Downloadable source has @Override.9
A Servlet That Generates HTML
‱ Tell the browser that you’re sending it HTML
– response.setContentType("text/html");
‱ Modify the println statements to build a
legal Web pagelegal Web page
– Print statements should output HTML tags
‱ Check your HTML with a formal syntax‱ Check your HTML with a formal syntax
validator
– http://validator.w3.org/p g
– http://www.htmlhelp.com/tools/validator/
10
Caveat: As of 2010, it has become moderately conventional to use the HTML 5 DOCTYPE: <!DOCTYPE html>. Even though few browsers have full support for HTML 5, this
declaration is supported in practice by virtually all browsers. So, most validators will give some warnings or errors, and you have to search for the “real” errors in the list, or use a
different declaration. My examples use a mix of this doc type, the formal HTML 4 doc type, and the formal xhtml doc type.
A Servlet That Generates HTML
(Code)(Code)
@WebServlet("/test1")
public class TestServlet extends HttpServlet {public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException IOException {throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.printlnout.println
("<!DOCTYPE html>n" +
"<html>n" +
"<head><title>A Test Servlet</title></head>n" +ead t t e est Se et /t t e / ead 
"<body bgcolor="#fdf5e6">n" +
"<h1>Test</h1>n" +
"<p>Simple servlet for testing.</p>n" +p p g /p 
"</body></html>");
}
}11
A Servlet That Generates HTML
(Result)(Result)
Assumes project is named test-app.
Eclipse users can use the TestServlet code as a basis for their own servlets.
Avoid using “New  Servlet” in Eclipse since it results in ugly code.
12
g p g y
© 2010 Marty Hall
Using Helper Classes
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.13
Idea
‱ All Java code goes in the same place
– In Eclipse, it is src/packageName
‱ It does not matter if code is for a servlet, helper class,
filter, bean, custom tag class, or anything else, , g , y g
‱ Don’t forget OOP principles
– If you find you are doing the same logic multiple times,
put the logic in a helper class and reuse it
‱ Simple example here
Generates HTML B ilding HTML from a helper class is– Generates HTML. Building HTML from a helper class is
probably not really worth it for real projects, but we
haven’t covered logic in servlets yet. But the general
principle still holds: if you are doing the same thing in
several servlets, move the code into shared helper class.
14
A Simple HTML-Building Utility
public class ServletUtilities {
public static String headWithTitle(String title) {public static String headWithTitle(String title) {
return("<!DOCTYPE html>n" +
"<html>n" +
"<head><title>" + title + "</title></head>n");)
}
...
}
‱ Don’t go overboard
– Complete HTML generation packages
usually work poorlyusually work poorly
‱ The JSP framework is a better solution
– More important is to avoid repeating logic.p p g g
ServletUtilities has a few methods for that, as will
be seen later
15
TestServlet2
...
@WebServlet("/test-with-utils")
public class TestServlet2 extends HttpServlet {
public void doGet(HttpServletRequest requestpublic void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Test Servlet with Utilities";
out.println
(ServletUtilities headWithTitle(title) +(ServletUtilities.headWithTitle(title) +
"<body bgcolor="#fdf5e6">n" +
"<h1>" + title + "</h1>n" +
"<p>Simple servlet for testing.</p>n" +
/ /"</body></html>");
}
}
16
TestServlet2: Result
Assumes project is named test-app.
17
© 2010 Marty Hall
Custom URLsCustom URLs
and web.xml
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.18
Tomcat 7 or Other Servlet 3.0
ContainersContainers
‱ Give address with @WebServlet
@WebServlet("/my-address")
public class MyServlet extends HttpServlet { 
 }
– Resulting URL
‱ http://hostName/appName/my-address
‱ Omit web.xml entirely
You are permitted to use web xml even when using– You are permitted to use web.xml even when using
@WebServlet, but the entire file is completely optional.
‱ In earlier versions, you must have a web.xml file even if
th t th th th i t t d d tthere were no tags other than the main start and end tags
(<web-app 
> and </web-app>).
19
Example: URLs with
@WebServlet@WebServlet
package testPackage;



@WebServlet("/test1")
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response getWriter();PrintWriter out = response.getWriter();
out.println
("<!DOCTYPE html>n" +

);
}
}
20
Defining Custom URLs in
web xml (Servlets 2 5 & Earlier)web.xml (Servlets 2.5 & Earlier)
‱ Java code
package myPackage;package myPackage; ...
public class MyServlet extends HttpServlet { ... }
‱ web.xml entry (in <web-app...>...</web-app>)
Gi t l t– Give name to servlet
<servlet>
<servlet-name>MyName</servlet-name>
<servlet class>myPackage MyServlet</servlet class><servlet-class>myPackage.MyServlet</servlet-class>
</servlet>
– Give address (URL mapping) to servlet
<servlet-mapping><servlet-mapping>
<servlet-name>MyName</servlet-name>
<url-pattern>/my-address</url-pattern>
</servlet-mapping>pp g
‱ Resultant URL
– http://hostname/appName/my-address
21
Defining Custom URLs: Example
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2 4"
Don't edit this manually.
Should match version supported
by your server If your server<web app version 2.4
... >
<!-- Use the URL http://hostName/appName/test2 for
by your server. If your server
supports 3.0, can omit web.xml
totally and use annotations.
p pp
testPackage.TestServlet -->
<servlet>
<servlet-name>Test</servlet-name>
Fully qualified classname.
<servlet-class>testPackage.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
< l t >T t</ l t >
Any arbitrary name.
But must be the same both times.
<servlet-name>Test</servlet-name>
<url-pattern>/test2</url-pattern>
</servlet-mapping>
</web-app> The part of the URL that comes after the app (project) name.
</web-app>
22
Should start with a slash.
Defining Custom URLs: Result
‱ Eclipse details
f li j i– Name of Eclipse project is “test-app”
– Servlet is in src/testPackage/TestServlet.java
– Deployed by right-clicking on Tomcat Add and Remove– Deployed by right-clicking on Tomcat, Add and Remove
Projects, Add, choosing test-app project, Finish,
right-clicking again, Start (or Restart)23
© 2010 Marty Hall
Advanced Topics
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.24
The Servlet Life Cycle
‱ init
– Executed once when the servlet is first loaded.
Not called for each request.
‱ service‱ service
– Called in a new thread by server for each request.
Dispatches to doGet, doPost, etc.p
Do not override this method!
‱ doGet, doPost, doBlah
H dl GET POST– Handles GET, POST, etc. requests.
– Override these to provide desired behavior.
‱ destroy‱ destroy
– Called when server deletes servlet instance.
Not called after each request.25
Why You Should
Not Override serviceNot Override service
‱ The service method does other thingsg
besides just calling doGet
– You can add support for other services later by adding
d P t d T tdoPut, doTrace, etc.
– You can add support for modification dates by adding a
getLastModified methodg
– The service method gives you automatic support for:
‱ HEAD requests
‱ OPTIONS requests‱ OPTIONS requests
‱ TRACE requests
‱ Alternative: have doPost call doGet
26
Debugging Servlets
‱ Use print statements; run server on desktop
‱ Use Apache Log4J‱ Use Apache Log4J
‱ Integrated debugger in IDE
– Right-click in left margin in source to set breakpoint (Eclipse)
– R-click Tomcat and use “Debug” instead of “Start”R click Tomcat and use Debug instead of Start
‱ Look at the HTML source
‱ Return error pages to the client
– Plan ahead for missing or malformed datag
‱ Use the log file
– log("message") or log("message", Throwable)
‱ Separate the request and response data.p q p
– Request: see EchoServer at www.coreservlets.com
– Response: see WebClient at www.coreservlets.com
‱ Make sure browser is not caching
– Internet Explorer: use Shift-RELOAD
– Firefox: use Control-RELOAD
‱ Stop and restart the server27
© 2010 Marty Hall
Wrap-Up
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.28
Summary
‱ Main servlet code goes in doGet or doPost:
– The HttpServletRequest contains the incoming
information
– The HttpServletResponse lets you set outgoing– The HttpServletResponse lets you set outgoing
information
‱ Call setContentType to specify MIME type
C ll tW it t bt i W it i ti t li t (b )‱ Call getWriter to obtain a Writer pointing to client (browser)
‱ Make sure output is legal HTML
‱ Give address with @WebServlet or web.xmlGive address with @WebServlet or web.xml
@WebServlet("/some-address")
public class SomeServlet extends HttpServlet { 
 }
‱ Resulting URL
– http://hostName/appName/some-address
29
© 2010 Marty Hall
Questions?
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.30

Mais conteĂșdo relacionado

Mais procurados

Java Enterprise Edition
Java Enterprise EditionJava Enterprise Edition
Java Enterprise EditionFrancesco Nolano
 
Ruby On Rails Tutorial
Ruby On Rails TutorialRuby On Rails Tutorial
Ruby On Rails Tutorialsunniboy
 
Java EE 7: Boosting Productivity and Embracing HTML5
Java EE 7: Boosting Productivity and Embracing HTML5Java EE 7: Boosting Productivity and Embracing HTML5
Java EE 7: Boosting Productivity and Embracing HTML5Arun Gupta
 
RSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversRSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversBrian Gesiak
 
Unbreaking Your Django Application
Unbreaking Your Django ApplicationUnbreaking Your Django Application
Unbreaking Your Django ApplicationOSCON Byrum
 
Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3Fabien Potencier
 
Composable and streamable Play apps
Composable and streamable Play appsComposable and streamable Play apps
Composable and streamable Play appsYevgeniy Brikman
 
Best Practices for Front-End Django Developers
Best Practices for Front-End Django DevelopersBest Practices for Front-End Django Developers
Best Practices for Front-End Django DevelopersChristine Cheung
 
Ruby On Rails Seminar Basis Softexpo Feb2010
Ruby On Rails Seminar Basis Softexpo Feb2010Ruby On Rails Seminar Basis Softexpo Feb2010
Ruby On Rails Seminar Basis Softexpo Feb2010arif44
 
Django app deployment in Azure By Saurabh Agarwal
Django app deployment in Azure By Saurabh AgarwalDjango app deployment in Azure By Saurabh Agarwal
Django app deployment in Azure By Saurabh Agarwalratneshsinghparihar
 
Ajax Tags Advanced
Ajax Tags AdvancedAjax Tags Advanced
Ajax Tags AdvancedAkramWaseem
 
The JavaFX Ecosystem
The JavaFX EcosystemThe JavaFX Ecosystem
The JavaFX EcosystemAndres Almiray
 
When dynamic becomes static
When dynamic becomes staticWhen dynamic becomes static
When dynamic becomes staticWim Godden
 
Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Yevgeniy Brikman
 

Mais procurados (19)

Java Enterprise Edition
Java Enterprise EditionJava Enterprise Edition
Java Enterprise Edition
 
Ruby On Rails Tutorial
Ruby On Rails TutorialRuby On Rails Tutorial
Ruby On Rails Tutorial
 
Java EE 7: Boosting Productivity and Embracing HTML5
Java EE 7: Boosting Productivity and Embracing HTML5Java EE 7: Boosting Productivity and Embracing HTML5
Java EE 7: Boosting Productivity and Embracing HTML5
 
RSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversRSpec 3.0: Under the Covers
RSpec 3.0: Under the Covers
 
Ant User Guide
Ant User GuideAnt User Guide
Ant User Guide
 
Unbreaking Your Django Application
Unbreaking Your Django ApplicationUnbreaking Your Django Application
Unbreaking Your Django Application
 
Django
DjangoDjango
Django
 
Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3
 
Thinking Beyond ORM in JPA
Thinking Beyond ORM in JPAThinking Beyond ORM in JPA
Thinking Beyond ORM in JPA
 
Composable and streamable Play apps
Composable and streamable Play appsComposable and streamable Play apps
Composable and streamable Play apps
 
Best Practices for Front-End Django Developers
Best Practices for Front-End Django DevelopersBest Practices for Front-End Django Developers
Best Practices for Front-End Django Developers
 
Ruby On Rails Seminar Basis Softexpo Feb2010
Ruby On Rails Seminar Basis Softexpo Feb2010Ruby On Rails Seminar Basis Softexpo Feb2010
Ruby On Rails Seminar Basis Softexpo Feb2010
 
SQLAlchemy Primer
SQLAlchemy PrimerSQLAlchemy Primer
SQLAlchemy Primer
 
Django app deployment in Azure By Saurabh Agarwal
Django app deployment in Azure By Saurabh AgarwalDjango app deployment in Azure By Saurabh Agarwal
Django app deployment in Azure By Saurabh Agarwal
 
Prototype-1
Prototype-1Prototype-1
Prototype-1
 
Ajax Tags Advanced
Ajax Tags AdvancedAjax Tags Advanced
Ajax Tags Advanced
 
The JavaFX Ecosystem
The JavaFX EcosystemThe JavaFX Ecosystem
The JavaFX Ecosystem
 
When dynamic becomes static
When dynamic becomes staticWhen dynamic becomes static
When dynamic becomes static
 
Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)
 

Destaque

11 page-directive
11 page-directive11 page-directive
11 page-directivesnopteck
 
10 jdbc
10 jdbc10 jdbc
10 jdbcsnopteck
 
Digital Engagement for CSPs
Digital Engagement for CSPsDigital Engagement for CSPs
Digital Engagement for CSPsKind of Digital
 
03 form-data
03 form-data03 form-data
03 form-datasnopteck
 
07 cookies
07 cookies07 cookies
07 cookiessnopteck
 
13 java beans
13 java beans13 java beans
13 java beanssnopteck
 
04 request-headers
04 request-headers04 request-headers
04 request-headerssnopteck
 

Destaque (7)

11 page-directive
11 page-directive11 page-directive
11 page-directive
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
 
Digital Engagement for CSPs
Digital Engagement for CSPsDigital Engagement for CSPs
Digital Engagement for CSPs
 
03 form-data
03 form-data03 form-data
03 form-data
 
07 cookies
07 cookies07 cookies
07 cookies
 
13 java beans
13 java beans13 java beans
13 java beans
 
04 request-headers
04 request-headers04 request-headers
04 request-headers
 

Semelhante a 02 servlet-basics

01 overview-and-setup
01 overview-and-setup01 overview-and-setup
01 overview-and-setupsnopteck
 
15 expression-language
15 expression-language15 expression-language
15 expression-languagesnopteck
 
JavaScript-Core
JavaScript-CoreJavaScript-Core
JavaScript-Coretutorialsruby
 
JavaScript-Core
JavaScript-CoreJavaScript-Core
JavaScript-Coretutorialsruby
 
05 status-codes
05 status-codes05 status-codes
05 status-codessnopteck
 
Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Ramamohan Chokkam
 
Jsf2 overview
Jsf2 overviewJsf2 overview
Jsf2 overviewmusaibasrar
 
14 mvc
14 mvc14 mvc
14 mvcsnopteck
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-trackingsnopteck
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-trackingsnopteck
 
Struts2-Spring=Hibernate
Struts2-Spring=HibernateStruts2-Spring=Hibernate
Struts2-Spring=HibernateJay Shah
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2divzi1913
 
Struts 2 Overview
Struts 2 OverviewStruts 2 Overview
Struts 2 Overviewskill-guru
 
Dave Orchard - Offline Web Apps with HTML5
Dave Orchard - Offline Web Apps with HTML5Dave Orchard - Offline Web Apps with HTML5
Dave Orchard - Offline Web Apps with HTML5Web Directions
 

Semelhante a 02 servlet-basics (20)

01 overview-and-setup
01 overview-and-setup01 overview-and-setup
01 overview-and-setup
 
15 expression-language
15 expression-language15 expression-language
15 expression-language
 
Ajax basics
Ajax basicsAjax basics
Ajax basics
 
JavaScript-Core
JavaScript-CoreJavaScript-Core
JavaScript-Core
 
JavaScript-Core
JavaScript-CoreJavaScript-Core
JavaScript-Core
 
10 jsp-scripting-elements
10 jsp-scripting-elements10 jsp-scripting-elements
10 jsp-scripting-elements
 
05 status-codes
05 status-codes05 status-codes
05 status-codes
 
Prototype-1
Prototype-1Prototype-1
Prototype-1
 
Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268
 
Jsf2 overview
Jsf2 overviewJsf2 overview
Jsf2 overview
 
14 mvc
14 mvc14 mvc
14 mvc
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-tracking
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-tracking
 
Android networking-2
Android networking-2Android networking-2
Android networking-2
 
Struts2-Spring=Hibernate
Struts2-Spring=HibernateStruts2-Spring=Hibernate
Struts2-Spring=Hibernate
 
Jsp and jstl
Jsp and jstlJsp and jstl
Jsp and jstl
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2
 
Struts 2 Overview
Struts 2 OverviewStruts 2 Overview
Struts 2 Overview
 
Json generation
Json generationJson generation
Json generation
 
Dave Orchard - Offline Web Apps with HTML5
Dave Orchard - Offline Web Apps with HTML5Dave Orchard - Offline Web Apps with HTML5
Dave Orchard - Offline Web Apps with HTML5
 

Último

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 

Último (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

02 servlet-basics

  • 1. © 2010 Marty Hall S l t B iServlet Basics Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/csajsp2.html Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.2 © 2010 Marty Hall For live Java EE training, please see training courses at http://courses.coreservlets.com/.at http://courses.coreservlets.com/. Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo, Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT), Java 5, Java 6, SOAP-based and RESTful Web Services, Spring,g Hibernate/JPA, and customized combinations of topics. Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial Available at public Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at your organization. Contact hall@coreservlets.com for details.
  • 2. Agenda ‱ The basic structure of servlets ‱ A simple servlet that generates plain text ‱ A servlet that generates HTML ‱ Using helper classes ‱ Giving URLs to servlets – @WebServlet annotation – web.xml file ‱ The servlet life cycle‱ The servlet life cycle ‱ Servlet debugging strategies 4 © 2010 Marty Hall Overview Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.5
  • 3. A Servlet’s Job ‱ Read explicit data sent by client (form data) ‱ Read implicit data sent by client (request headers) G t th lt‱ Generate the results ‱ Send the explicit data back to client (HTML) S d th i li it d t t li t‱ Send the implicit data to client (status codes and response headers) 6 © 2010 Marty Hall Simple Servlets Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.7
  • 4. A Servlet That Generates Plain Text (HelloWorld java)Text (HelloWorld.java) package testPackage; // Always use packages. import java io *;import java.io. ; import javax.servlet.*; import javax.servlet.annotation.*; import javax.servlet.http.*;p j p @WebServlet("/hello") public class HelloWorld extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) th S l tE ti IOE ti {throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("Hello World"); }} } 8 URL assumes you have deployed from a project named “test-app”. Code can be downloaded from Web site. General form is http://hostName/appName/address-from-WebServlet-annotation. Review previous tutorial section for info on how to deploy the app from Eclipse. Interpreting HelloWorld Servlet ‱ @WebServlet("/address") – This is the URL relative to the app name. More later. ‱ doGet C d f HTTP GET t d P t l– Code for an HTTP GET request. doPost also common. ‱ HttpServletRequest Contains anything that comes from the browser– Contains anything that comes from the browser ‱ HttpServletResponse – Used to send stuff to the browser. Most common isUsed to send stuff to the browser. Most common is getWriter for a PrintWriter that points at browser. ‱ @Override – General best practice when overriding inherited methods ‱ But, I will omit on many of my PowerPoint slides to conserve space. Downloadable source has @Override.9
  • 5. A Servlet That Generates HTML ‱ Tell the browser that you’re sending it HTML – response.setContentType("text/html"); ‱ Modify the println statements to build a legal Web pagelegal Web page – Print statements should output HTML tags ‱ Check your HTML with a formal syntax‱ Check your HTML with a formal syntax validator – http://validator.w3.org/p g – http://www.htmlhelp.com/tools/validator/ 10 Caveat: As of 2010, it has become moderately conventional to use the HTML 5 DOCTYPE: <!DOCTYPE html>. Even though few browsers have full support for HTML 5, this declaration is supported in practice by virtually all browsers. So, most validators will give some warnings or errors, and you have to search for the “real” errors in the list, or use a different declaration. My examples use a mix of this doc type, the formal HTML 4 doc type, and the formal xhtml doc type. A Servlet That Generates HTML (Code)(Code) @WebServlet("/test1") public class TestServlet extends HttpServlet {public class TestServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException IOException {throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.printlnout.println ("<!DOCTYPE html>n" + "<html>n" + "<head><title>A Test Servlet</title></head>n" +ead t t e est Se et /t t e / ead "<body bgcolor="#fdf5e6">n" + "<h1>Test</h1>n" + "<p>Simple servlet for testing.</p>n" +p p g /p "</body></html>"); } }11
  • 6. A Servlet That Generates HTML (Result)(Result) Assumes project is named test-app. Eclipse users can use the TestServlet code as a basis for their own servlets. Avoid using “New  Servlet” in Eclipse since it results in ugly code. 12 g p g y © 2010 Marty Hall Using Helper Classes Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.13
  • 7. Idea ‱ All Java code goes in the same place – In Eclipse, it is src/packageName ‱ It does not matter if code is for a servlet, helper class, filter, bean, custom tag class, or anything else, , g , y g ‱ Don’t forget OOP principles – If you find you are doing the same logic multiple times, put the logic in a helper class and reuse it ‱ Simple example here Generates HTML B ilding HTML from a helper class is– Generates HTML. Building HTML from a helper class is probably not really worth it for real projects, but we haven’t covered logic in servlets yet. But the general principle still holds: if you are doing the same thing in several servlets, move the code into shared helper class. 14 A Simple HTML-Building Utility public class ServletUtilities { public static String headWithTitle(String title) {public static String headWithTitle(String title) { return("<!DOCTYPE html>n" + "<html>n" + "<head><title>" + title + "</title></head>n");) } ... } ‱ Don’t go overboard – Complete HTML generation packages usually work poorlyusually work poorly ‱ The JSP framework is a better solution – More important is to avoid repeating logic.p p g g ServletUtilities has a few methods for that, as will be seen later 15
  • 8. TestServlet2 ... @WebServlet("/test-with-utils") public class TestServlet2 extends HttpServlet { public void doGet(HttpServletRequest requestpublic void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Test Servlet with Utilities"; out.println (ServletUtilities headWithTitle(title) +(ServletUtilities.headWithTitle(title) + "<body bgcolor="#fdf5e6">n" + "<h1>" + title + "</h1>n" + "<p>Simple servlet for testing.</p>n" + / /"</body></html>"); } } 16 TestServlet2: Result Assumes project is named test-app. 17
  • 9. © 2010 Marty Hall Custom URLsCustom URLs and web.xml Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.18 Tomcat 7 or Other Servlet 3.0 ContainersContainers ‱ Give address with @WebServlet @WebServlet("/my-address") public class MyServlet extends HttpServlet { 
 } – Resulting URL ‱ http://hostName/appName/my-address ‱ Omit web.xml entirely You are permitted to use web xml even when using– You are permitted to use web.xml even when using @WebServlet, but the entire file is completely optional. ‱ In earlier versions, you must have a web.xml file even if th t th th th i t t d d tthere were no tags other than the main start and end tags (<web-app 
> and </web-app>). 19
  • 10. Example: URLs with @WebServlet@WebServlet package testPackage; 

 @WebServlet("/test1") public class TestServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response getWriter();PrintWriter out = response.getWriter(); out.println ("<!DOCTYPE html>n" + 
); } } 20 Defining Custom URLs in web xml (Servlets 2 5 & Earlier)web.xml (Servlets 2.5 & Earlier) ‱ Java code package myPackage;package myPackage; ... public class MyServlet extends HttpServlet { ... } ‱ web.xml entry (in <web-app...>...</web-app>) Gi t l t– Give name to servlet <servlet> <servlet-name>MyName</servlet-name> <servlet class>myPackage MyServlet</servlet class><servlet-class>myPackage.MyServlet</servlet-class> </servlet> – Give address (URL mapping) to servlet <servlet-mapping><servlet-mapping> <servlet-name>MyName</servlet-name> <url-pattern>/my-address</url-pattern> </servlet-mapping>pp g ‱ Resultant URL – http://hostname/appName/my-address 21
  • 11. Defining Custom URLs: Example <?xml version="1.0" encoding="UTF-8"?> <web-app version="2 4" Don't edit this manually. Should match version supported by your server If your server<web app version 2.4 ... > <!-- Use the URL http://hostName/appName/test2 for by your server. If your server supports 3.0, can omit web.xml totally and use annotations. p pp testPackage.TestServlet --> <servlet> <servlet-name>Test</servlet-name> Fully qualified classname. <servlet-class>testPackage.TestServlet</servlet-class> </servlet> <servlet-mapping> < l t >T t</ l t > Any arbitrary name. But must be the same both times. <servlet-name>Test</servlet-name> <url-pattern>/test2</url-pattern> </servlet-mapping> </web-app> The part of the URL that comes after the app (project) name. </web-app> 22 Should start with a slash. Defining Custom URLs: Result ‱ Eclipse details f li j i– Name of Eclipse project is “test-app” – Servlet is in src/testPackage/TestServlet.java – Deployed by right-clicking on Tomcat Add and Remove– Deployed by right-clicking on Tomcat, Add and Remove Projects, Add, choosing test-app project, Finish, right-clicking again, Start (or Restart)23
  • 12. © 2010 Marty Hall Advanced Topics Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.24 The Servlet Life Cycle ‱ init – Executed once when the servlet is first loaded. Not called for each request. ‱ service‱ service – Called in a new thread by server for each request. Dispatches to doGet, doPost, etc.p Do not override this method! ‱ doGet, doPost, doBlah H dl GET POST– Handles GET, POST, etc. requests. – Override these to provide desired behavior. ‱ destroy‱ destroy – Called when server deletes servlet instance. Not called after each request.25
  • 13. Why You Should Not Override serviceNot Override service ‱ The service method does other thingsg besides just calling doGet – You can add support for other services later by adding d P t d T tdoPut, doTrace, etc. – You can add support for modification dates by adding a getLastModified methodg – The service method gives you automatic support for: ‱ HEAD requests ‱ OPTIONS requests‱ OPTIONS requests ‱ TRACE requests ‱ Alternative: have doPost call doGet 26 Debugging Servlets ‱ Use print statements; run server on desktop ‱ Use Apache Log4J‱ Use Apache Log4J ‱ Integrated debugger in IDE – Right-click in left margin in source to set breakpoint (Eclipse) – R-click Tomcat and use “Debug” instead of “Start”R click Tomcat and use Debug instead of Start ‱ Look at the HTML source ‱ Return error pages to the client – Plan ahead for missing or malformed datag ‱ Use the log file – log("message") or log("message", Throwable) ‱ Separate the request and response data.p q p – Request: see EchoServer at www.coreservlets.com – Response: see WebClient at www.coreservlets.com ‱ Make sure browser is not caching – Internet Explorer: use Shift-RELOAD – Firefox: use Control-RELOAD ‱ Stop and restart the server27
  • 14. © 2010 Marty Hall Wrap-Up Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.28 Summary ‱ Main servlet code goes in doGet or doPost: – The HttpServletRequest contains the incoming information – The HttpServletResponse lets you set outgoing– The HttpServletResponse lets you set outgoing information ‱ Call setContentType to specify MIME type C ll tW it t bt i W it i ti t li t (b )‱ Call getWriter to obtain a Writer pointing to client (browser) ‱ Make sure output is legal HTML ‱ Give address with @WebServlet or web.xmlGive address with @WebServlet or web.xml @WebServlet("/some-address") public class SomeServlet extends HttpServlet { 
 } ‱ Resulting URL – http://hostName/appName/some-address 29
  • 15. © 2010 Marty Hall Questions? Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.30