Session 9 – Servlet Intro 10/11/2018 1 Internet Programming Robert Kelly, 2018
Session 9
Introduction to Servlets
Robert Kelly, 2018
Lecture Objectives
Understand the foundations for client/server Web interactions Understand the servlet life cycle
2
Session 9 Introduction to Servlets Lecture Objectives Understand - - PDF document
Internet Programming Session 9 Servlet Intro Session 9 Introduction to Servlets Lecture Objectives Understand the foundations for client/server Web interactions Understand the servlet life cycle 2 Robert Kelly, 2018 1
Robert Kelly, 2018
2
Robert Kelly, 2018
Java Servlet
en.wikipedia.org/wiki/Java_servlet
Java Annotation
en.wikipedia.org/wiki/Java_annotation docs.oracle.com/javase/tutorial/java/annotations/
Excellent tutorial, explaining how to set up a servlet in NetBeans
www.studytonight.com/servlet/creating-servlet-in-netbeans.php
Use the on-line Servlet API documentation at:
http://docs.oracle.com/javaee/7/api/
3
Use the J2EE 7 Tutorial as a Reference
Robert Kelly, 2018
4
Java EE now maintained by the Eclipse foundation, and renamed as Jakarta EE
Robert Kelly, 2018 5
Browser
HTML, CSS, MIME Type Display Static Component HTTP interface
Web Container Database
URL / Query string / HTTP data, cookies, etc.
HTML, Images, cookies, etc.
req
res JDBC
Web Server Web container is also referred to as a servlet container
Robert Kelly, 2018
Server responds with a dynamically generated page that includes HTML, CSS, and data (inserted in the page) Data insertion usually performed by a server-side scripting engine
Server responds with data (no HTML and CSS) Data structured based on some coordination between client and server (e.g., JSON, XML, text)
6
Robert Kelly, 2018
Is a Java class that can be loaded dynamically to expand the capability of the Web server Runs inside the Java Virtual Machine on the server (safe and portable) Is able to access all Java APIs supported in the server Does not have a main method
7 Robert Kelly, 2018
8
Developer March 2018 Percent Apache 76M 43.0% nginx 37M 21.0% Google 12M 7.7% Microsoft 12M 6.8%
Robert Kelly, 2018 9
Static Interface
request response
Web Container
HttpServlet subclass Service methods (doGet and doPost) The Web Server static interface primarily serves resources, and passes complex request to the Web Container http method MIME files Frequently both servers are packaged together, but it is good to think of them as separate systems
Robert Kelly, 2018
10
Request data include HTTP version, URL, browser software, client MIME type preferences, data, etc. Response data includes HTTP version, status code, MIME type of data, document size, document
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException protected void doPost( HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException
Robert Kelly, 2018 11
<html> <head> <title>Hello World</title> </head> <body> <p>Hello World</p> </body></html>
Robert Kelly, 2018 12
<!doctype html> <html> <head> <title>Link to Hello World Servlet</title> </head> <body> <p> <a href="http://localhost:8080/CSE336-2017/HelloWorld"> Click here to say hello to the world</a> </p> </body> </html>
The URL in this link maps to the servlet Name of the Web application This is not really a file – it maps to your servlet Verify the port number used by your test server Port 8080 is typical for a test http server
Robert Kelly, 2018 13
protected void processRequest( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType( "text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String docTyp= "<!DOCTYPE html >";
+ "Hello World</title></head>");
Robert Kelly, 2018
package lectures; import java.io.*;import java.net.*;import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }
14
The Web container calls either doGet or doPost, which then calls processRequest processRequest is a method used by convention in NetBeans
Robert Kelly, 2018
web.xml – the deployment descriptor Sub-directories containing classes Meta data for the Web Application
15
Take a look at your Web App in your NetBeans or Eclipse project pane
Robert Kelly, 2018
16
http://localhost:8080/CSE336-2017/HelloWorld
There is no HelloWorld resource
Robert Kelly, 2018
17
http://localhost:8080/CodeCSE336/helloWorld
Context name (Web Application or Project name)
Robert Kelly, 2018
Web.xml (Deployment Descriptor) Annotation
18
Robert Kelly, 2018
You can annotate classes, methods, fields, and local variables
19
@Entity public class Team implements Serializable {
Think of it as a modifier for the declaration
Robert Kelly, 2018
20
@ManyToOne(cascade=CascadeType.PERSIST) public Team getTeam() { … }
Robert Kelly, 2018
21 Robert Kelly, 2018
22
@WebServlet(name = "HelloWorld", urlPatterns = {"/HelloWorld"}) public class HelloWorld extends HttpServlet {
Robert Kelly, 2018
23
Modifier and Type Optional Element and Description
boolean asyncSupported - Declares whether the servlet supports asynchronous operation mode. String description - The description of the servlet String displayName - The display name of the servlet WebInitParam[] initParams The init parameters of the servlet String largeIcon - The large-icon of the servlet int loadOnStartup - The load-on-startup order of the servlet String name - The name of the servlet String smallIcon - The small-icon of the servlet String[] urlPatterns - The URL patterns of the servlet String[] value - The URL patterns of the servlet
Robert Kelly, 2018
24
You can use a URL pattern that is different from the servlet name
Robert Kelly, 2018 25
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <description>A Hello World servlet </description> <servlet-name>HelloWorld</servlet-name> <servlet-class>lectures.HelloWorld</servlet-class> </servlet> ... <servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping> ... <session-config> <session-timeout> 30 </session-timeout> </session-config> </web-ap>
Robert Kelly, 2018
26
This is just to discover anomalies in your lab or personal implementation of your IDE Be sure you have installed the Web components of your IDE
Robert Kelly, 2018
@WebServlet(name = "HelloWorld", urlPatterns = {"/HelloWorld"}) public class HelloWorld extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) {
27 Robert Kelly, 2018
28
method sp URL sp Version cr lf header field name sp value cr lf header field name sp value cr lf header field name sp value cr lf cr lf
request line (like a method call) header lines (like a parameter list
Entity body (like a single object parameter
Robert Kelly, 2018 29
service(req, res) doGet(req, res) doPost(req, res) doOptions()
Etc.
Browser Web Server Includes all name value pairs in the form field plus server data in the URL query strings, header data, and cookies Includes header data and all name value pairs in the request
NetBeans uses a processRequest method (not a standard) processRequest(req, res)
HTTP method becoming much more important with RESTful services
Robert Kelly, 2018
getParameter(String s) getScheme() getProtocol() getRemoteAddress() isSecure() getContentType() getRequestedSessionID()
getRequestURI isRequestedSessionValid() getQueryString() getRemoteUser getMethod() getCookies() getHeader()
30
Robert Kelly, 2018
getWriter - from ServletResponse sendError(int sc) addCookie(Cookie cookie) sendRedirect(String location)
SC_GONE SC_INTERNAL_SERVER_ERROR SC_NOT_FOUND
31 Robert Kelly, 2018
32
Robert Kelly, 2018
33
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); }
Or NetBeans generates a processRequest method
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }
Web services takes a stricter view of the http method used
Robert Kelly, 2018
Information about the transmission to the browser – this is stored in the http header of the response Data (e.g., HTML) that is stored in the http body of the response
34
Servlet buffer
http packet
Robert Kelly, 2018 35
Response header data includes age, cache control, language, message digest, MIME type, expiration date, last modified date, etc. isCommitted method – returns boolean indicating that headers have been sent
setBufferSize flushBuffer
Robert Kelly, 2018
36