Академический Документы
Профессиональный Документы
Культура Документы
Efficiency
CGI invoking
Servlet
Overhead of starting a new process can dominate the execution time. For N simultaneous request, the same code is loaded into memory N times. When terminated, lose cache computation, DB connection & .. JVM stays running and handles each request using Java thread. Only a single copy is loaded into memory Straightforward to store data between requests
Convinient
CGI invoking
Easy to install and setup
Servlet
Provides an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions and other utilities. No need to learn new programming languages if you are familiar with Java already. Easy to implement DB connection pooling & resourcesharing optimization.
Execution
Destruction
a ServletRequest object is sent with all information about the request a ServletResponse object is used to return the response
Simple Example
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>");out.println("<body>"); out.println("<head>"); out.println("<title>Hello World!</title>"); out.println("</head>");out.println("<body>"); out.println("<h1>Hello World!</h1>"); out.println("</body>");out.println("</html>");}}
Client Interaction
When a servlet accepts a call from a client, it receives two objects:
A ServletRequest, which encapsulates the communication from the client to the server. A ServletResponse, which encapsulates the communication from the servlet back to the client.
Interfaces that extend ServletRequest interface allow the servlet to retrieve more protocol-specific data. For example, the HttpServletRequest interface contains methods for accessing HTTP-specific header information.
Interfaces that extend the ServletResponse interface give the servlet more protocol-specific capabilities.
For example, the HttpServletResponse interface contains methods that allow the servlet to manipulate HTTP-specific header
allows the servlet to set the content length and MIME type of the reply. provides an output stream, ServletOutputStream, and a Writer through which the servlet can send the reply data.
out.println("<h3>Request Information Example</h3>"); out.println("Method: " + request.getMethod()); out.println("Request URI: " + request.getRequestURI()); out.println("Protocol: " +request.getProtocol()); out.println("PathInfo: " + request.getPathInfo()); out.println("Remote Address: " + request.getRemoteAddr()); out.println("</body>");out.println("</html>"); }
/* We are going to perform the same operations for POST requests as for GET methods, so this method just sends the request to the doGet method.*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response);}}
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class RequestHeaderExample extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); Enumeration e = request.getHeaderNames(); while (e.hasMoreElements()) {
Request Parameters
public void doPost(HttpServletRequest request, HttpServletResponse res) throws IOException, ServletException { Enumeration e = request.getParameterNames(); PrintWriter out = res.getWriter (); while (e.hasMoreElements()) { String name = (String)e.nextElement(); String value = request.getParameter(name); out.println(name + " = " + value);}}}
Cookies
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class CookieExample extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); // print out cookies Cookie[] cookies = request.getCookies(); for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i];String name = c.getName(); String value = c.getValue(); out.println(name + " = " + value);}
Servlet References
For an excellent tutorial on java servlets see:
http://www.javasoft.com/docs/books/tutorial/servl ets/index.html
Session Capabilities
Session tracking is a mechanism that servlets use to maintain state about a series of requests from the same user(that is, requests originating from the same browser) across some period of time. session-tracking capabilities. The servlet writer can use these APIs to maintain state between the servlet and the client that persists across multiple connections during some time period.
Sessions
public class SessionExample extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(true); // print session info Date created = new Date( session.getCreationTime()); Date accessed = new
out.println("ID " + session.getId()); out.println("Created: " + created); out.println("Last Accessed: " + accessed); String dataName = request.getParameter("dataName"); if (dataName != null && dataName.length() > 0) {String dataValue = request.getParameter("dataValue"); session.setAttribute(dataName, dataValue);} // print session contents Enumeration e = session.getAttributeNames(); while (e.hasMoreElements()) { String name = String)e.nextElement(); value = session.getAttribute(name).toString(); out.println(name + " = " + value);}}}
What is JSP?
A Java Servlet is a Java program that is run on the server A Java Servlet must return an entire HTML page, so all tuning of the page must be done in a Java program that needs to be re-compiled Java Server Pages (JSP)
use HTML and XML tags to design the page and JSP scriplet tags to generate dynamic content (Easier for separation between designer & developer) use Java Beans and useful built-in objects for more convinience There are Java classes for retrieving HTTP requests and returning HTTP responses
Any change in JSP page automatically repeats the whole life cycle.
A Java Servlet is a Java program that is run on the server A Java Servlet must return an entire HTML page, so all tuning of the page must be done in a Java program that needs to be re-compiled On the other hand Java Server Pages (JSP)
use HTML and XML tags to design the page and JSP scriplet tags to generate dynamic content use Java Beans, which are reusable components that are invoked by scriplets There are Java classes for retrieving HTTP requests and returning HTTP responses
Introduction
Standard Actions
Directives
<%@ include file=Filename %> the static file name to include (included at translation time) <% taglib uri=taglibraryURI prefix=tagPrefix
<%= . . %> can contain any language expression, but without a semicolon, e.g. <%= Math.sqrt(2) %> <%= items[I] %> <%= a + b + c %> <%= new java.util.Date() %> <% . . %> can handle declarations (page scope), expressions, or any other type of code fragment <% for(int I = 0; I < 10; I++) { out.println(<B> Hello World: + I); } %>
Scripting II
Standard Actions
<jsp:useBean> : associates an instance of a java object with a newly declard scripting variable of the same id
<jsp:useBean id=name scope=page|request|session|application class=className />
<jsp:setProperty>
<jsp:getProperty> :action places the value of a Bean instance property, converted to a string, into the implicit out object <jsp:param>
<jsp:getProperty name=beanid property=propertyName />
<jsp:include> :Include static or dynamic (jsp) pages with optional parameters to pass to the included page.
<jsp:include page=filename /> <jsp:include page=urlSpec> <jsp:param name paramname value=value> </jsp:include>
<jsp:forward> : allows the runtime dispatch of the current request to a static resource, jsp pages or java servlet in the same context as the current page.
<jsp:forward page=url /> <jsp:include page=urlSpec> <jsp:param name paramname value=value> </jsp:forward>
Implicit Objects
These objects do not need to be declared or instantiated by the JSP author, but are provided by the container (jsp engine) in the implementation class request Object (javax.servlet.ServletRequest) response Object (javax.servlet.ServletResponse) session Object (javax.servlet.http.HttpSession) application Object out Object config Object page Object pageContext Object (javax.servlet.jsp.PageContext) exception
Hellouser.jsp
<%@ page import=hello.NameHandler %> <jsp:useBean id=mybean scope=page class=hello.NameHandler /> <jsp:setProperty name=myBean property=* /> <html><head><title>hello user</title></head> <body> <h1>My name is Duke. Whats yours?</h1> <form method=get> <input type=text name=username><br> <input type=submit value=submit> </form> <% if ( request.getParameter(username) != null) { %><%@ include file=response.jsp %> <% } %></body>
package hello public class NameHandler { private String username; public NameHandler() { username = null; } public void setUsername ( String name) { username=name; } public String getusername() { return username; } } Note: omit the action attribute for <form> if you want the data processed by the object specified in the <jsp:useBean> tag Response.jsp <h1>hello, <jsp:getProperty name=mybean property=username /></h1>
Namehandler.java
Example Elements
JSP directive passes information to the jsp engine; directives are enclosed in <%@ and %> Fixed template data, typically html or xml, are passed through Jsp actions, or tags, e.g. jsp:useBean tag instantiates the Clock JavaBean on the server Expressions, anything between <%== and %> is evaluated by the jsp engine; e.g. the values of the Day and Year attributes of the Clock bean are returned as strings Scriplet is a small program written in a Java subset; e.g. determining whether it is AM or PM