Java Servlet File - e

Download Report

Transcript Java Servlet File - e

JAVA SERVLET
Dr Mohd Soperi Mohd Zahid
Semester 2 2015/16
Overview
• Servlet
• Java Web Application Components
• Web Containers and Application Server
• Servlet examples
• Sessions and Cookies
Java Servlets
• A servlet is a Java program that is invoked by a web
server in response to a request
Client
Server Platform
Web
Server
Web Application
Servlet
Java Servlets
• Together with web pages and other components,
servlets constitute part of a web application
• Servlets can
• create dynamic (HTML) content in response to a
request
• handle user input, such as from HTML forms
• access databases, files, and other system resources
• perform any computation required by an application
Java Servlets
• Servlets are hosted by a web/servlet container, such as
Apache Tomcat*
The web server
handles the HTTP
transaction details
Server Platform
Web
Server
Servlet
Container
The servlet container
provides a Java
Virtual Machine
for servlet execution
*Apache Tomcat can be both a web server and a servlet container
Java Web Application Components
• Your code and the third-party libraries it depends on
• Deployment descriptor (instructions for deploying and
starting your application)
• ClassLoaders to isolate your application from other web
applications on the same server
• WAR and EAR files to package your application
Web Container
• Managing the life cycle of Servlets
• Mapping request URLs to Servlet code
• Accepting and responding to HTTP requests
• We may use a variety of web containers for our
application: Apache Tomcat for local testing on
developers’ machines, GlassFish for production
environment
Apache Tomcat
• Lacks the sophisticated web management interface
• Provides only a simple interface for basic tasks such as
•
•
•
•
deploying and undeploying applications
Administrators must manipulate a collection of XML and
Java properties files to make further configurations
Lacks many Java EE components suchs Java
Persistence API, etc.
Using Tomcat for complex enterprise applications are
challenging and sometimes impossible
Options: Apache TomEE, Geronimo
GlassFish
• Open source and Commercial (Oracle Corporation) full
Java EE application server implementation
• Provides a graphical web user interface, a command-line
interface, and configuration files to configure the server
• Go to GlassFish web site to know more about GlassFish
or download it
JBoss and WildFly
• Red Hat’s JavaBeans Open Source Software Application
•
•
•
•
Server (JBoss AS)
JBoss AS was renamed to WildFly in early 2014 to avoid
confusion with other JBoss projects
WildFly 8.0 is a full Java EE 7 application server
Other web containers: Jetty and Tiny
Other full Java EE application server: JOnAS, Caucho,
and Enhydra (Open source); Oracle WebLogic and IBM
WebSphere (Commercial)
Servlet Operation
Servlet Methods
• Servlets have three principal methods
.init()
invoked once, when the servlet is loaded by the servlet container
(upon the first client request)
.service(HttpServletRequest req, HttpServletResponse res)
invoked for each HTTP request
parameters encapsulate the HTTP request and response
.destroy()
invoked when the servlet is unloaded
(when the servlet container is shut down)
init() and destroy() methods
• When a web container first starts a Servlet, it calls that
•
•
•
•
Servlet’s init() method
Later when the web container shuts down the Servlet, it
calls the Servlet’s destroy() method
Not the same as Java constructor and finalizer, and they
are not called at the same time as the constructor and
finalizer
Normally do nothing but can be overridden to perform
some actions
init() method may be used to read a properties file or
connect to a database using JDBC, while destroy() may
be used to clean up resources (disconnect database, etc)
Servlet Methods
• The default .service() method simply invokes
method-specific methods
• depending upon the HTTP request method
.service()
.doGet()
.doPost()
.doHead()
… etc.
HTTP method Types
• Any HTTP Servlet methods that are not overridden will be
responded to with an HTTP status 405 (Method Not
Allowed error)
Activity 1 (Installing Tomcat)
• Go to Tomcat Downloads page
•
•
•
•
http://tomcat.apache.org/download-80.cgi, and scroll
down to the “Binary Distributions” section
Choose the one under the “Core” heading
For this class, do not install Tomcat as a Window service
Avoid the option 32-bit/64-bit Windows Service
Installer (pgp, md5, sha1)
Open the file conf/tomcat-users.xml and add the following
between <tomcat-users> and </tomcat-users> tags:
<user username=“admin” password=“admin” roles=“manager-gui, admin-gui” />
Cont.
• Open the conf/web.xml and search for the text:
org.apache.servlet.JspServlet. There are two <init-param>
tags below the tag that contains the text. Add the following
parameters below the existing init parameters:
<init-param>
<param-name>CompilerSourceVM</param-name>
<param-value>1.8</param-value>
</init-param>
<init-param>
<param-name>compilerTargetVM</param-name>
<param-value>1.8</param-value>
• The init parameters instruct Tomcat to compile JSP files
with Java SE 8 language features
Activity 2 (Starting Tomcat)
• Go to Tomcat home directory
• Type echo %JAVA_HOME% to check the JAVA_HOME
•
•
•
•
environment variable is properly set to your Java
Development Kit (JDK)
Type the command bin\startup.bat in command window
Wait until the Java console window shows the message
“INFO [main] org.apache.catalina.startup.Catalina.start
Server startup in … ms”
Open your browser and navigate to http://localhost:8080/
To stop Tomcat, type bin\shutdown.bat in command
window
Deploying application in Tomcat
• Can be done by manually placing the application in the
webapps directory, or using the Tomcat manager
application
• Activity 1: Place sample-deployment.war file from
Chapter2 directory, copy it into the webapps directory, and
start Tomcat
• Navigate to http://localhost:8080/sample-deployment/
• To undeploy the application, just delete the sampledeployment.war file and wait for Tomcat to automatically
delete the unpacked directory
Using Tomcat Manager to deploy app
• Navigate to http://localhost:8080/manager/html
• Enter your username and password (e.g. admin)
• Find the “WAR file to deploy” form, choose sample-
deployment.war file and then click the Deploy button
Setting Up Tomcat in Eclipse
• In eclipse, go to Windows > Preferences
• In dialog box, expand Server, and click Runtime
•
•
•
•
Environments
Click Add button to open the New Server Runtime
Environment dialog
Expand the Apache folder and select Apache Tomcat
v8.0, making sure the “Create a new local server” check
box is selected, and click Next button
Click Browse button and browse to Tomcat 8.0 home
directory, then click OK
In the JRE drop-down, select your local Java SE 8 JRE
installation. Give a name you want to the server
Using Tomcat Server in a Project
• After a Project is opened or created in Eclipse, go to
•
•
•
•
Project > Properties and click the Server menu item on
the left side of the project Properties dialog box
By default, the selected server is “<None>”, change it to
“Tomcat v8.0 Server at localhost”
Click Apply
Change the application context URL that the application
deploys to in Tomcat. In the Project Properties dialog,
click the Web Project Settings menu item and update the
“Context root” field to change the setting
Click Apply
Activity 2 (Starting an Application)
• Open the Sample-Debug-Eclipse project: File > Import >
General > Existing Projects into Workspace; Click Next;
Browse to locate and select the root directory eclipse
project to be imported
• Set server with configuration to use your local Tomcat 8.0
application server (Project > Properties, Click Server
menu item on the left side)
• Click the Debug icon in the toolbar to compile and start
your application in debug mode.
Activity 3 (Install Eclipse)
• Install the EE version
Servlets
• The core classes in any web application
• A small Java program that runs within a Web server
• Receive and respond to requests from Web clients usually
•
•
•
•
via HTTP protocol
Two (2) types: Built-in Servlets and Custom Servlets
Every Servlet implements the javax.servlet.Servlet
interface which contains methods for initializing and
destroying the Servlet, and servicing requests
Every Servlet extends javax.servlet.http.HttpServlet
allowing the use of HTTP method types listed in next slide
Maven dependency (in pom.xml)
Deploying a Servlet
• Adding the servlet to the deployment descriptor file
(web.xml) in WEB-INF directory
• Mapping the Servlet to a URL
• Run and Debug the Servlet
Hello World Servlet
package com.wrox;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.getWriter().println("Hello, World!");
}
@Override
public void init() throws ServletException {
System.out.println("Servlet " + this.getServletName() + " has started.");
}
@Override
public void destroy() {
System.out.println("Servlet " + this.getServletName() + " has stopped.");
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>Hello World Application</display-name>
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>com.wrox.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/greeting</url-pattern>
</servlet-mapping>
</web-app>
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Hello, World Application Index File</title>
</head>
<body>
<a href="greeting">Go to greeting</a>.
</body>
</html>
Servlet Example
• This servlet will say "Hello!" (in HTML)
package servlet;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
public void service(HttpServletRequest req,
HttpServletResponse res) throws IOException {
PrintWriter htmlOut = res.getWriter();
res.setContentType("text/html");
htmlOut.println("<html><head><title>" +
"Servlet Example Output</title></head><body>" +
"<p>Hello!</p>" + "</body></html>");
htmlOut.close();
}
}
Servlet Configuration
• The web application configuration file, web.xml, identifies
servlets and defines a mapping from requests to servlets
An identifying name for the servlet (appears twice)
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>servlet.HelloServlet</servlet-class>
</servlet>
The servlet's package
<servlet-mapping>
and class names
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
The pathname used to invoke the servlet
(relative to the web application URL)
Environment Entries
• Servlets can obtain configuration information at
run-time from the configuration file (web.xml)
• a file name, a database password, etc.
• in web.xml:
<env-entry-description>password</env-entry-description>
<env-entry>
<env-entry-name>UserId</env-entry-name>
<env-entry-value>Xy87!fx9*</env-entry-value>
<env-entry-type>java.lang.String</env-entry-type>
</env-entry>
Environment Entries
• in the init() method of the servlet:
try {
Context envCtx = (Context)
(new InitialContext()).lookup("java:comp/env");
password = (String) envCtx.lookup("password");
} catch (NamingException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
HttpServletRequest & HttpServletResponse
• Are parameters available in the various methods defined
by HttpServlet class
• Enable us to read parameters passed from the client,
accept files uploaded from a posted form, read the raw
data contained in the request body (e.g. PUT requests or
JSON request bodies), read request headers and
manipulate response headers, and write response content
back to the client
Request Parameters passed by client
• Via query parameters (i.e. URI parameters) or an
application/x-www-form-urlencoded or multipart/form-data
encoded request body (i.e. post variables or form
variables)
• Query parameters are in the first line of data in an HTTP
request such as:
GET /index.jsp?productId=9781118656464&category=Books HTTP/1.1
• There are two (2) query parameters in the above HTTP
request: productId and category
Cont.
• productId and category via request body (post variables)
included in POST requests:
Query parameters
Post variables
• To access the request parameters, use relevant methods
on a request object in your code: e.g. getParameter,
getParameterValues, getParameterMap
Writing to response body
• Most common thing we do with a response object
• Examples: HTML document displayed in a browser, an
•
•
•
•
•
image the browser is retrieving, or content of a file the
client is downloading (plaint text or binary data – few
bytes or gigabytes long)
getOutputputStream method returns a
javax.servlet.ServletOutputStream
getWriter method returns a java.io.PrintWriter
To return HTML to the client, use PrintWriter
To send binary data to client, use ServletOutputStream
Cannot use both methods in the same response object
A Dynamic “Hello World” Servlet
package com.wrox;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;import java.io.PrintWriter;
@WebServlet(
name = "helloServlet", urlPatterns = {"/greeting", "/salutation", "/wazzup"}, loadOnStartup = 1
)
public class HelloServlet extends HttpServlet{
private static final String DEFAULT_USER = "Guest";
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user = request.getParameter("user");
if(user == null)
user = HelloServlet.DEFAULT_USER;
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
writer.append("<!DOCTYPE html>\r\n") .append("<html>\r\n") .append("<head>\r\n") .append("<title>Hello User
Application</title>\r\n")
.append("</head>\r\n") .append("<body>\r\n") .append("Hello, ").append(user).append("!<br/><br/>\r\n")
.append("<form action=\"greeting\" method=\"POST\">\r\n")
.append("Enter your name:<br/>\r\n") .append("<input type=\"text\"
name=\"user\"/><br/>\r\n") .append("<input type=\"submit\" value=\"Submit\"/>\r\n") .append("</form>\r\n") .append("</body>\r\n")
.append("</html>\r\n");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
@Override public void init() throws ServletException { System.out.println("Servlet " + this.getServletName() + " has started."); }
@Override public void destroy() { System.out.println("Servlet " + this.getServletName() + " has stopped."); }
}
web.xml
Servlet API version number
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>Hello World Application</display-name>
<context-param>
<param-name>settingOne</param-name> Application name – will appear in list of installed
<param-value>foo</param-value>
application displayed by Tomcat manager
</context-param>
screen
<context-param>
<param-name>settingTwo</param-name>
<param-value>bar</param-value>
</context-param>
Tell web container to create an instance
<servlet>
<servlet-name>helloServlet</servlet-name>
of the HelloServlet Servlet and call
<servlet-class>com.wrox.HelloServlet</servlet-class>
(name) it helloServlet. Possible to have
<init-param>
<param-name>database</param-name>
several of instances of the same Servlet
<param-value>CustomerSupport</param-value>
with different names. To retrieve the
</init-param>
<init-param>
name, make a call to
<param-name>server</param-name>
this.getServletName() in your Servlet
<param-value>10.0.12.5</param-value>
code
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
To run, navigate to http://localhost:8080/Hello<url-pattern>/greeting</url-pattern>
World/greeting
</servlet-mapping>
</web-app
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Hello, User Application Index File</title>
</head>
<body>
<a href="greeting">Go to greeting</a>.
</body>
</html>
• doGet method is called when user name is passed
through query parameter (url, not via form)
• goPost method is called when user name is passed
through post variable (form submission)
Context init parameters
• A way to configure an application
• Defined at startup and cannot change without restarting
the application
• Require entries in deployment descriptor (web.xml)
<context-param>
<param-name>settingOne</param-name>
<param-value>foo</param-value>
</context-param>
<param-name>settingTwo</param-name>
<param-value>bar</param-value>
</context-param>
Shared by
every
Servlets
• Use getServletContext and getInitParameter methods on
ServletContext object to obtain the parameter values
Servlet init parameters
• A way to configure Servlet
• Setting can be done in deployment descriptor or
annotating the class with @WebServlet
• If annotations is used, servlet has to be recompiled every
time changes to settings are made
• Setting applies only to a single Servlet
• Use getServletConfig and getInitParameter methods on
ServletConfig object to obtain the parameter values
Cont. (deployment descriptor)
<servlet>
<servlet-name>servletParameterServlet</servlet-name>
<servlet-class>com.wrox.servletParameterServlet</servlet-class>
<init-param>
<param-name>database</param-name>
<param-value>CustomerSupport</param-value>
</init-param>
<init-param>
<param-name>server</param-name>
<param-value>10.0.12.5</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>servletParameterServlet</servlet-name>
<url-pattern>/servletParameters</url-pattern>
<servlet-mapping>
Cont. (@WebServlet annotation)
@WebServlet {
name = “servletParameterServlet”,
urlPatterns = {“/servletParameters”},
initParams = {
@WebInitParam(name = “database”, value = “CustomerSupport”),
@WebInitParam(name = “server”, value = “10.0.12.5”)
}
public class ServletParameterServlet extends HttpServlet {
……..
}
File Uploading from Form
• Use multipart configuration options and, getPart and
getParts methods in HttpServletRequest
@WebServlet {
name = “ticketServlet”,
urlPatterns = {“/tickets”},
loadOnStartup = 1
}
@MultipartConfig {
fileSizeThreshold = 5_242_880, // 5 MB
maxFileSize = 20_971_520L, // 20 MB
maxRequestSize = 41_943_040L // 40 MB
}
public class TicketServlet extends HttpServlet {
private volatile int TICKET_ID_SEQUENCE = 1;
priivate Map<Integer, Ticket> ticketDatabase = new LinkedHashMap<>();
……. }
Handling multithreading
• Most of the time web applications are multithreaded
•
•
•
•
•
applications
Many people may be using a web application
simultaneously at any given time
In Java EE, a web container has some type of thread pool
If request arrives but no thread available and thread pool
has reached maximum value, the request enters a FIFO
queue and wait for available thread
Tomcat has acceptCount setting which defines the
maximum number of connections that can be queued
before the container starts rejecting connections
Default pool size in Tomcat is 200 threads
Cont.
• One way to prevent exceptional behavior when multiple
•
•
•
•
threads are executing the same instance of code
simultaneously is to protect accesses to shared resources
Synchronize the accesses to static and instance variables
by multiple threads
Techniques: volatile variable and synchronized block
Volatile variable prevents a thread to read changes made
by other thread to the variable
Code in a synchronized block gives a thread exclusive
privilege of execution until its completion
Cont.
private volatile int TICKET_ID_SEQUENCE = 1;
synchronized(this) {
id = this.TICKET_ID_SEQUENCE++;
this.ticketDatabase.put(id, ticket);
}
Sessions
• Multiple requests coming from the same client and the
•
•
•
•
states between the requests
HTTP is stateless
An HTTP request begins with a client opens a socket to
connect with the server
An HTTP request ends when the server sends the last
packet to the client and closes the connection
No link between the user and server anymore and HTTP
is not able to tie between the request just ended and the
next request
Example (Browsing a Store)
• Find a product you like and add it to your shopping cart
• Find another product and add it to your shopping cart
• View your shopping cart and figure out that both products
are in your shopping cart
• Somehow, the website knew those requests were coming
from the same browser on the same computer and
associated them with your shopping cart
• Nobody else can see your shopping cart and the items in
it
• Mechanisms to maintain the states in a session are
needed
Maintaining states
• A session is some file, memory segment, object, or
container managed by the server or application
• A session contains various data elements such as
username, shopping cart, etc.
• A session is assigned a randomly generated string called
the session ID
• Passing session ID from server to browser can be done
via session cookies or URL rewriting
Cookies
• Cookies are essentially a mechanism where arbitrary
data can be passed from the server to the browser via
the Set-Cookie response header field of an HTTP
• The data can be stored locally on the user’s computer,
and then transmitted back to the server via the Cookie
request header
• Cookies can have various attributes such as a domain
name, a path, an expiration date or maximum age, a
secure flag, and HTTP-only flag.
• In Java EE application servers, the name of a session
cookie is JSESSIONID by default
Cookies
Tomcat sends
session ID as value
of cookie named
JSESSIONID
Jackson, Web Technologies: A Computer Science
Perspective, © 2007 Prentice-Hall, Inc. All rights reserved.
0-13-185603-0
Cookies
Cookie-enabled
browser returns
session ID as value
of cookie named
JSESSIONID
Jackson, Web Technologies: A Computer Science
Perspective, © 2007 Prentice-Hall, Inc. All rights reserved.
0-13-185603-0
Tracing HTTP requests & responses
URL Rewriting
• Server looks for a particular pattern containing the
session ID in the URL
• In Java EE applications, the session ID is placed in a
matrix parameter in the last path segment (or directory) in
the URL, for example:
• The session ID must be embedded in every URL that the
application sends back in every response
• The browser never actually “remember” the session ID
like it is with session cookie
Tracing HTTP requests & responses
Embedding session ID in URL
• Use two methods defined in HttpServletResponse
•
•
•
•
interface or use <c:url> tag
encodeURL and encodeRedirectURL
Pass the URL (link, form action, etc) to the encodeURL
method, which will return an appropriately “encoded”
version of the URL
aAny URL passes to the sendRedirect response method
can be passed to the encodeRedirectURL method, which
also return an “encoded” version of the URL
“encoded” means JSESSIONID matrix parameter is
embedded in the last path segment of the URL
Configuring Sessions in web.xml
• Available options:
<session-config>
<session-timeout>30</session-timeout>
<cookie-config>
<name>JSESSIONID</name>
<domain>example.org</domain>
<path>/shop</path>
<comment><!CDATA [Keeps you logged in. See our privacy policy for
more information.]]></comment>
<http-only>true</http-only>
<secure>false</secure>
<max-age>1800</max-age>
</cookie-config>
<tracking-mode>COOKIE</tracking-mode>
<tracking-mode>URL</tracking-mode>
<tracking-mode>SSL</tracking-mode>
</session-config>
Example
• Session will last in 30 minutes (time to remain inactive)
• maxage specifies when cookie will expire (by default
cookie has no expiration date)
• Use only cookies for session tracking
<session-config>
<session-timeout>30</session-timeout>
<cookie-config>
<http-only>true</http-only>
</cookie-config>
<tracking-mode>COOKIE</tracking-mode>
</session-config>
Creating a session in Servlet
HttpSession session = request.getSession();
if (session.getAttribute(“cart”) == null)
session.setAttribute(“cart”, new Hashtable<Integer, Integer>());
@SuppressWarning(“unchecked”)
Map<Integer, Integer> cart =
(Map<Integer, Integer>) session.getAttribute(“cart”);
if (!cart.containsKey(productId))
cart.put(productId, 0);
cart.put(productId, cart.get(productId) + 1);
response.sendRedirect(“shop?action=viewCart”);
• getSession() or getSessions(boolean)
• getAttribute method returns an object stored in the
session, setAttribute creates an object in the session