Download Java Servlets

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

URL redirection wikipedia , lookup

Transcript
Java Web Applications
WAR
• Web Archive
• Introduced with servlet 2.2 specification
• Portable deployment mechanism for web
applications
• Defines directory structure
– Jar’d into a .war file for deployment
• Uses XML deployment descriptor
Directory Structure
find ./webbasics -print
./webbasics
./webbasics/WEB-INF
./webbasics/WEB-INF/classes
./webbasics/WEB-INF/classes/ejava
./webbasics/WEB-INF/classes/ejava/servlets
./webbasics/WEB-INF/classes/ejava/servlets/webbasics
./webbasics/WEB-INF/classes/ejava/servlets/webbasics/BonusServlet.class
./webbasics/WEB-INF/classes/ejava/servlets/webbasics/PurchaseServlet.class
./webbasics/WEB-INF/web.xml
./webbasics/WEB-INF/weblogic.xml
./webbasics/FormExample.html
./webbasics/MenuExample.html
Directory Structure (Cont)
• WEB-INF
–
–
–
–
–
Contains web.xml deployment descriptor
Contains class files for web app (classes)
Contains .jar files for web app (lib)
Contains Tag Library Descriptors (tlds)
Cannot be served to client
• Other directories store web content i.e. jsp/html
files, images, sound, etc.
Deployment Descriptor (web.xml)
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 1.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<display-name>HTML Basics</display-name>
<context-param>
<param-name>weblogic.httpd.servlet.reloadCheckSecs</param-name>
<param-value>1</param-value>
</context-param>
<servlet>
<servlet-name>PurchaseServlet</servlet-name>
<servlet-class>ejava.servlets.webbasics.PurchaseServlet</servlet-class>
<init-param>
<param-name>param1</param-name>
<param-value>value1</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>BonusServlet</servlet-name>
<servlet-class>ejava.servlets.webbasics.BonusServlet</servlet-class>
</servlet>
...
Mapping Servlets to URLs
(web.xml)
…
<servlet-mapping>
<servlet-name>PurchaseServlet</servlet-name>
<url-pattern>PurchaseAlias</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>BonusServlet</servlet-name>
<url-pattern>BonusAlias</url-pattern>
</servlet-mapping>
...
Declaring Default Pages (web.xml)
…
<welcome-file-list>
<welcome-file>/welcome.html</welcome-file>
</welcome-file-list>
...
Creating the .war file
%cd c:\\weblogic/myserver/public_html/webbasics; \
%//c/jdk1.3/bin/jar cvf /webbasics.war *
added manifest
adding: FormExample.html(in = 467) (out= 257)(deflated 44%)
adding: MenuExample.html(in = 486) (out= 274)(deflated 43%)
adding: WEB-INF/(in = 0) (out= 0)(stored 0%)
adding: WEB-INF/classes/(in = 0) (out= 0)(stored 0%)
adding: WEB-INF/classes/ejava/(in = 0) (out= 0)(stored 0%)
adding: WEB-INF/classes/ejava/servlets/(in = 0) (out= 0)(stored 0%)
adding: WEB-INF/classes/ejava/servlets/webbasics/(in = 0) (out= 0)(stored 0%)
adding: WEB-INF/classes/ejava/servlets/webbasics/BonusServlet.class(in = 2403) (
out= 1260)(deflated 47%)
adding: WEB-INF/classes/ejava/servlets/webbasics/PurchaseServlet.class(in = 2585
) (out= 1449)(deflated 43%)
adding: WEB-INF/web.xml(in = 1843) (out= 587)(deflated 68%)
adding: WEB-INF/weblogic.xml(in = 412) (out= 227)(deflated 44%)
adding: WEB-INF/web.xml~(in = 1071) (out= 366)(deflated 65%)
adding: welcome.html(in = 183) (out= 103)(deflated 43%)
Summary
• The web application format should be used
for all web deployments
• Standardized mechanism for web tier
deployments
Java Servlets
Servlet Definition
• “Web component, managed by a container, that
generates dynamic content”
• Request-Response mechanism modeled after
HTTP
• Required by J2EE v1.2 specification
• Web Server configured to invoke servlets when
specified URLs are accessed (servlet mapping)
– HTML Forms
– Java programs
Architecture
Get/Post Request
Web
Browser
HTML Page
Request
Web
Server
Reply
Servlet Container
Servlet
Servlet Benefits
• Efficiency
– run as threads vs. CGI processes
• Written in Java
– can use any Java API such as JDBC, EJB, RMI, etc.
• Portability
– supported by many web/application servers
• Simplicity
– Provides support for common operations including
session management
Servlet Container
• Provides the execution environment for a servlet
• Must support HTTP as the request/response
protocol
– HTTP 1.1 support strongly recommended by spec
– May support HTTPS (HTTP over SSL)
• Can be installed directly in a web server or as an
add-on using web server extension mechanisms
• May impose security constraints on servlet
My First Servlet
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
{
PrintWriter out = response.getWriter();
out.println(“Hello World”);
}
}
Notes
• Default return mime type is text/plain
• Can also implement doPost
– Same arguments
– What if you want to answer to both?
• Running the servlet
– Compile
• You will need the java 2 enterprise edition jar in your classpath
– Put class into WEB-INF/classes
– Put in servlet mapping and class info in
WEB-INF/web.xml
– Invoke  http://host/context/servletmapping
Key Servlet Classes
<<Interface>>
Servlet
ServletConfig
void destroy()
getServletConfig() : ServletConfig
getServletInfo() : String
init(ServletConfig config)
service(ServletRequest req, ServletResponse resp)
getInitParameter(String name) : String
getInitParameterNames() : Enumeration
getServletContext() : ServletContext
HttpServlet
GenericServlet
doDelete(ServletRequest req, ServletResponse res)
doGet(ServletRequest req, ServletResponse res)
doOptions(ServletRequest req, ServletResponse res)
doPost(ServletRequest req, ServletResponse res)
doPut(ServletRequest req, ServletResponse res)
doTrace(ServletRequest req, ServletResponse res)
Another Example
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
{
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
out.println(“<HTML>\n” +
“<HEAD><title>Hello WWW</title></HEAD>\n” +
“<body>\n” +
“<h1>Hello World!</h1>\n” +
“</body></html>”);
}
}
Requests and Responses
ServletRequest
ServletResponse
getContentLength() : int
getContentType() : String
getInputStream() : ServletInputStream
getParameter(String name) : String
getReader() : BufferedReader
getOutputStream() : ServletOutputStream
getWriter() : PrintWriter
setContentLength(int len)
setContentType(String type)
HttpServletRequest
HttpServletResponse
getAuthType() : String
getCookies() : Cookie[]
getHeader(String name) : String
getSession() : HttpSession
addCookie(Cookie c)
setHeader(String name, String value)
setStatus(int sc)
The HttpServletRequest Object
• Form parameters
–
–
–
–
String choice=request.getParameter(“Product”);
String getParameter(String key)
String[] getParameterValues(String key)
Enumeration getParameterNames()
• Cookies
– Cookie[] = request.getCookies()
– getName(), getValue()
• Binary Data
– InputStream is = request.getInputStream()
• Character Data
– Reader r = request.getReader()
The HttpServletResponse Object
•
•
•
•
void setContentType(String type)
void setContentLength(int len)
PrintWriter getWriter()
ServletOutputStream getOutputStream()
– Used to send binary data back to client
• void setHeader(String name, String value)
• Other methods as well
Servlet Implementation
package ejava.servlets.webbasics;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PurchaseServlet extends HttpServlet
{
public void init(ServletConfig config) throws ServletException
{
super.init(config);
log("BonusServlet:init(config)");
}
Servlet (Cont)
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, java.io.IOException
{
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter();
out.println("<html><head><title>");
out.println("Purchase Servlet");
out.println("</title></head><body>");
if (request.getParameter("BUYCMD") != null)
{
String product = request.getParameter("Product");
out.println("<p><b>purchased product:</b>"+product);
}
out.println("</body></html>");
out.close();
}
Performance Issues
• Strings are immutable
– New string object is created for each string
– Also for each concatenation of 2 strings
–  a lot of object creation and cleanup
• Use a single StringBuffer object
– Use append() method to add text to it
• Use flush method to push output to client
Organizational Issues
• WEB-INF/classes can get crowded
• Use java packages to clean things up
–
–
–
–
package mypackage; //place at top of file
Put classes in WEB-INF/classes/mypackage
Set up servlet mapping in WEB-INF/web.xml
Invoke http://host/context/servletmapping
Headers and CGI variables
• Request object has methods to access
– String value getHeader(String name)
– Others
• PrintEnv code
– http://localhost:8080/ServletsAndJSP/TestGetP
ostServlet.html
Cookies
• Use the Cookie class
• Constructor
– Cookie(String name, String value)
• Cookie Methods
–
–
–
–
–
–
String getDomain() or void setDomain(String dom)
String getName() or void setName(String name)
String getValue() or void setValue(String value)
String getPath() or void setPath(String path)
boolean getSecure() or void setSecure(boolean flag)
int getMaxAge() or void setMaxAge(int seconds)
Cookies
• Create a cookie
– Construct it
– Set values
• Add the cookie to the response before content type
– response.addCookie(Cookie theCookie)
• Get Cookies from request
– Cookie[] cookies = request.getCookies()
Sessions
• High level API
– HttpSession object
• Built on top of cookies or URL-rewriting
– You don’t have to worry which one
• Convenient place to store information
– Arbitrary objects
– Associated with each session
The Session API
• Get the HttpSession object
– HttpSession session = request.getSession(true);
– true automatically creates one if one doesn’t exist
• Get and Set information using HttpSession methods
–
–
–
–
–
–
–
–
–
Object getAttribute(String name)
void setAttribute(String name, Object value)
void removeAttribute(String name)
String[] getAttributeNames()
String getID()
boolean getId()
long getCreationTime() and long getLastAccessedTime()
int getMaxInactiveInterval() and void setMaxInactiveInterval(int sec)
void invalidate()
Example: Toy Shop
• http://localhost:8080/ServletsAndJSP/ToyS
hop.html
The Servlet Life Cycle
• Initialization
– void init() or
– void init(ServletConfig config)
• Be sure to call super.init(config) on first line
• doXxx methods are called (doGet, doPut, etc.)
– Consider if you need single thread
• public class YourServlet extends HttpServlet
implements SingleThreadModel
• Destruction
– void destroy()
• don’t rely on this. The server could crash
Servlet Context
• Servlet may wish to interact with the host
server
• GenericServlet::getServletContext()
–
–
–
–
getMimeType( String file )
getServlet(String name) : Servlet
log(Exception, String)
log(String)
Redirection
• Web Browser redirection
– resp.sendRedirect(String url)
– resp.sendError(int code, String message)
• Server-Side
– RequestDispatcher rd =
getServletContext().getRequestDispatcher(urlString);
– rd.forward();
Request Dispatcher
Resources
• Main Servlets Page
– http://java.sun.com/products/servlet/
• Java Servlet Specification v2.2
– http://java.sun.com/products/servlet/2.2/index.html
• Marty Hall’s servlet tutorial
– http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/