Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Introduction to Server-Side Web Development with Servlets and JSP; basic concepts and syntax 18th February 2005 Bogdan L. Vrusias [email protected] Introduction to Server-Side Web Development Introduction • Most web sites want to display dynamic content based on user’s requests and expectations. • Most contents, such as images, text, and banner ads, are easiest to build with HTML editors. • We need to mix the "static" content of HTML files with "directives" for accessing or generating dynamic content. • Introducing: 18th February 2005 Bogdan L. Vrusias © 2005 2 Introduction to Server-Side Web Development Contents • History of JavaServer Pages (JSP) • Fundamentals of server-side programming. • Comparison to other server-side languages • Fundamentals of JavaServer Pages / Servlets. • Servlets • JavaServer Pages • Tomcat 18th February 2005 Bogdan L. Vrusias © 2005 3 Introduction to Server-Side Web Development History: The Beginning • 1991… beginning of WWW… beginning of HTML • No dynamic pages… the Webmaster • Too many static HTML pages had to be created for each website. • Need for change 18th February 2005 Bogdan L. Vrusias © 2005 4 Introduction to Server-Side Web Development History: First approach - CGI • Solution… Common Gateway Interface (CGI) technology created. • Dynamic pages…using Perl and C • Problem… these languages are not the simplest • Need for change • Java had the answer… Servlets 18th February 2005 Bogdan L. Vrusias © 2005 5 Introduction to Server-Side Web Development History: Servlets and JSP • Servlets are pure Java objects that generate HTML by writing it to a stream. • The files do not contain any HTML tags; they simply contain Java code which write out HTML (as strings) to produce the page that is sent to the user's browser. • …but it was quite painful to develop any large scale application with a bunch of servlets running around doing println() statements. • This is why Sun invented JSPs in the first place: to compete with the ease-of-development of Microsoft's ASP files, which could combine HTML tags and code in a single file. 18th February 2005 Bogdan L. Vrusias © 2005 6 Introduction to Server-Side Web Development Definition • JSP provide server-side scripting support for generating web pages with combined static and dynamic content. • JSP is a fast way to serve web pages that display dynamically generated content. 18th February 2005 Bogdan L. Vrusias © 2005 7 Introduction to Server-Side Web Development A dynamic Web Page • Static web page is a page whose content consists of some HTML that was predetermined and was typed directly into a text editor and saved as ".htm" or ".html" file. • Dynamic web page is a page whose content is generated at runtime dynamically. 1. Author writes instructions 5. HTML stream returned to browser 6. Browser processes HTML and displays page. 3. Web server locates instructions file 4. Web server processes instructions to create HTML 18th February 2005 2. Client request web page Bogdan L. Vrusias © 2005 8 Introduction to Server-Side Web Development Requests and Responses 18th February 2005 Bogdan L. Vrusias © 2005 9 Introduction to Server-Side Web Development Other Server-Side programming languages • CGI – Perl, C, C++ • ColdFusion – Tags with encapsulated functionality • ASP (Active Server Pages) and ASP .NET – VBasic, JavaScript, C# – ADO • PHP (Personal Home Pages) – Syntax similar to C and Perl – Open-source, cross-platform 18th February 2005 Bogdan L. Vrusias © 2005 10 Introduction to Server-Side Web Development JSP vs .NET and ASP • Similarities – Create interactive pages with web-based applications – Separates programming logic from page design through the use of component technology – Faster and Easier alternative to older, more cryptic technologies such as CGI • Differences (?) – JSP: Platform and server Independent • JSP can run on any web server • Supported by large number of tools – ASP: Relies on Microsoft platforms and servers • Restricted to MS Windows based platforms because of ActiveX Controls (that is to change now?) • Can be ported to different platforms using third party products, but ActiveX must be present on the platform. 18th February 2005 Bogdan L. Vrusias © 2005 11 Introduction to Server-Side Web Development Why Use JSPs? • Write once, run anywhere (JAVA). – JSPs are entirely platform independent, both in dynamic Web pages and underlying server components. • Emphasize components. – JSPs encourage the use of reusable, cross-platform server components called JavaBeans. Therefore saves development time, while giving you the power and flexibility of the Java programming language. • Provide a front door to the Enterprise’s Java platform. – JSPs are an integral part of the Java Platform for the Enterprise, which brings Java technology to enterprise computing. You can develop enterprise-wide or middle-tier server applications, using a JSP web site as a front end. 18th February 2005 Bogdan L. Vrusias © 2005 12 Introduction to Server-Side Web Development Advantages of Java • According to java.sun.com: – More mature, powerful, and scalable than Basic-based scripting languages – Java helps developers protect against system crashes, ASP and NT systems are susceptible to crashing – Java helps with memory management by providing protection against memory leaks • Well supported, large collection of APIs 18th February 2005 Bogdan L. Vrusias © 2005 13 Introduction to Server-Side Web Development JSP Model Architectures BROWSER BROWSER request response request response JSP / Servlet Container JSP / Servlet Container JSP PAGE JSP (VIEW) SERVLET (CONTROLLER) JAVABEAN JAVABEAN Data Tier Data Tier DATA DATA DATA Model 1 18th February 2005 DATA Model 2 Bogdan L. Vrusias © 2005 14 Introduction to Server-Side Web Development JSP Model Architectures • Model 1 – – – – Simple and fast Maintainability problems Reusability Problems Security Problems • Model 2 (also called Model-View-Controller) – – – – Requires more initial effort and technical knowledge Maintainability solutions vs. Model 1 Security solutions vs. Model 1 Reusability and extensibility solutions vs. Model 1 18th February 2005 Bogdan L. Vrusias © 2005 15 Introduction to Server-Side Web Development What are Servlets? • Servlets are objects that reside on a Java enabled web server, that work on the request-response principle. • Servlets are to the server-side what applets are to the client side • Servlets do not have a GUI associated with them • Servlets are faster and cleaner than CGI scripts • Servlets use a standard API • Servlets provide all the advantages of Java 18th February 2005 Bogdan L. Vrusias © 2005 16 Introduction to Server-Side Web Development Servlets Characteristics • Security – Servlets are called within the server context so they have all the security of the server itself. – They’re hidden from view and transmission. • Robustness – Rich application programming interfaces, APIs, are available making it easier to build sophisticated applications (JDBC, EJB, etc.). • Performance – Servlets run in the same context as the application server and can be preloaded or loaded on demand. – They’re multi-threaded to scale with multiprocessors and heterogeneous systems • Portability – Write-once, run-anywhere capability – They are able to exploit re-useable Java components called JavaBeans. 18th February 2005 Bogdan L. Vrusias © 2005 17 Introduction to Server-Side Web Development Servlet Code Sample import javax.servlet.*; import java.io.*; import java.util.*; public class SimpleServlet extends GenericServlet { public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); printWriter pw = response.getWriter(); pw.println("<html>\n<body>"); for(int counter = 1; counter <= 10; counter++) { pw.println(counter + " Mississippi,<br>"); } pw.println("<b>Ready or not, here I come!</b>"); pw.println("</body>\n<html>"); pw.close(); } } 18th February 2005 Bogdan L. Vrusias © 2005 18 Introduction to Server-Side Web Development Servlet Lifecycle 1. When a server loads a servlet, it runs the servlet's init() method. Even though most servlets are run in multi-threaded servers, there are no concurrency issues during servlet initialization. 2. After the server loads and initializes the servlet, the servlet is able to handle client requests. It processes them in its service() method. 3. Servlets run until they are removed from the service, by calling the servlet's destroy() method. • NOTE: Servlets can run multiple service methods at a time. It is important, therefore, that service methods be written in a thread-safe manner. If, for some reason, a server should not run multiple service methods concurrently, the servlet should implement the SingleThreadModel interface. 18th February 2005 Bogdan L. Vrusias © 2005 19 Introduction to Server-Side Web Development Servlet Lifecycle Diagram Uninstantiated Instantiated init() Initialised Servicing Requests service() doGet() Process Requests 18th February 2005 destroy() Garbage Collection doPost() Process Requests Bogdan L. Vrusias © 2005 20 Introduction to Server-Side Web Development Servlet Architecture Overview • The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet. • When a servlet accepts a call from a client, it receives two objects: one is a ServletRequest and the other is a ServletResponse. – The ServletRequest class encapsulates the communication from the client to the server – The ServletResponse class encapsulates the communication from the servlet back to the client. 18th February 2005 Bogdan L. Vrusias © 2005 21 Introduction to Server-Side Web Development ServletRequest • The ServletRequest interface allows the servlet access to information such as: – the names of the parameters passed in by the client – the protocol (scheme) being used by the client – the names of the remote host that made the request and the server that received it. • It also provides the servlet with access to the input stream, ServletInputStream, through which the servlet gets data from clients that are using application protocols such as the http POST method. CLIENT 18th February 2005 SERVER Bogdan L. Vrusias © 2005 22 Introduction to Server-Side Web Development ServletResponse • The ServletResponse interface gives the servlet methods for replying to the client. It 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. • Subclasses of ServletResponse give the servlet more protocolspecific capabilities. For example, HttpServletResponse contains methods that allow the servlet to manipulate HTTP-specific header information. CLIENT 18th February 2005 SERVER Bogdan L. Vrusias © 2005 23 Introduction to Server-Side Web Development Interacting with Clients I • Servlet writers who are developing HTTP servlets that specialize the HttpServlet class should override the method or methods designed to handle the HTTP interactions that their servlet will handle. • The candidate methods include: – – – – doGet, for handling GET, conditional GET and HEAD requests doPost, for handling POST requests doPut, for handling PUT requests doDelete, for handling DELETE requests 18th February 2005 Bogdan L. Vrusias © 2005 24 Introduction to Server-Side Web Development Interacting with Clients II • An HttpServletRequest object provides access to HTTP header data, such as any cookies found in the request and the HTTP method with which the request was made. It allows the you to obtain the arguments that the client sent as part of the request: – For any HTTP method, you can use the getParameter() or getParameterValues() method, which will return the value(s) of a named parameter. The method getParameterNames() provides the names of the parameters. • For responding to the client, an HttpServletResponse object provides ways of returning the response data to the user. You can use the writer returned by the getWriter() method to return text data to the user. 18th February 2005 Bogdan L. Vrusias © 2005 25 Introduction to Server-Side Web Development Reading Form Data Example - GET <form action="/servlet/aservlet" method="GET"> <input type="HIDDEN" name="key1" value="abc"/> <input type="HIDDEN" name="key2" value="def"/> <input type="SUBMIT" value="Go...."/> </form> When submitted, the browser would execute the following URL: http://www.somewhere.com/servlet/aservlet?key1=x& key2=y Alternatively <a href="/servlet/aservlet?key1=x&key2=y"> LINK</a> 18th February 2005 Bogdan L. Vrusias © 2005 26 Introduction to Server-Side Web Development Reading Form Data Example - POST The HTML <form action="/servlet/MyNameServlet" method="POST"> Please Enter your name <input type="TEXT" NAME="yourname"/> <input type="SUBMIT" VALUE="Submit"/> </form> 18th February 2005 Bogdan L. Vrusias © 2005 27 Introduction to Server-Side Web Development Reading Form Data Example - POST The Servlet ... public class AServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String name=req.getParameter("yourname"); String reply="<HTML>\n"+ "<HEAD><TITLE>My Name Servlet Response</TITLE></HEAD>\n"+ "<BODY>\n<CENTER><BR><B>\n"+ "Hello "+name+"\n"+ "</B></CENTER>\n</BODY>\n</HTML>"; res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println(reply); out.close(); } } 18th February 2005 Bogdan L. Vrusias © 2005 28 Introduction to Server-Side Web Development Demo • Some examples will now be demonstrated using the Tomcat server… http://host/servlet/ServletName http://host/servlet/PackageName.ServletName 18th February 2005 Bogdan L. Vrusias © 2005 29 Introduction to Server-Side Web Development How Servlets relate to JSPs • JSPs and servlets are two different ways to accomplish the same goal: generating dynamic HTML pages using Java code. One puts Java code in your HTML, and one puts HTML in your Java code. • Functionally, they are equivalent. In fact, under the covers, the web server takes a JSP and converts it to the corresponding servlet and dynamically compiles it. • BUT servlets have the following deficiencies: – It is hard to write and maintain the HTML – You cannot use standard HTML tools – The HTML is inaccessible to non-Java developers 18th February 2005 Bogdan L. Vrusias © 2005 30 Introduction to Server-Side Web Development JSP Code Sample <%@ page language="java" %> <html> <body> <% for (int counter = 1; counter <= 10; counter++) {%> <%= counter %> Mississippi,<BR> <% }%> <b>Ready or not, here I come!</b> </body> </html> 18th February 2005 Bogdan L. Vrusias © 2005 31 Introduction to Server-Side Web Development JSP Syntax • Scriptlets • Expressions • Declarations • Comments • Directives 18th February 2005 Bogdan L. Vrusias © 2005 32 Introduction to Server-Side Web Development Scriptlets <% // Java Code %> e.g. <% for (int i = 1; i <= 10; i++) {%> <%= i %> Mississippi,<BR> <% }%> 18th February 2005 Bogdan L. Vrusias © 2005 33 Introduction to Server-Side Web Development Expressions An expression prints out a string value on the page's buffer output: <%= counter %> <%= new java.util.Date() %> Using scriplets this would look like: <% out.print(counter) %> 18th February 2005 Bogdan L. Vrusias © 2005 34 Introduction to Server-Side Web Development Declarations <%! // this integer can be used anywhere in this JSP page private int myVariable = -1; // this function can be called from anywhere in this JSP page public boolean isPositive() { return ( myVariable > 0 ); } %> 18th February 2005 Bogdan L. Vrusias © 2005 35 Introduction to Server-Side Web Development Comments The comments are not printed on page's buffer, therefore are not viewed by the client. <%-comments over many lines of code --%> 18th February 2005 Bogdan L. Vrusias © 2005 36 Introduction to Server-Side Web Development Directives • Here is what directives look like in a general form: <%@ directive attribute="someValue" attribute="anotherValue" ... %> • There are three directives: <%@ page ... %> specifies information that affects the page e.g. <%@ page import="java.util.Date, java.text.*" %> <%@ include ... %> includes a file at the location of the include directive (parsed) e.g. <%@ include file="/copyright.html" %> <%@ taglib ... %> allows the use of custom tags in the page e.g. <%@ taglib uri="/WEB-INF/tlds/myTagLib.tld" prefix="myPrefix" %> <myPrefix:displayImage file="logo.jpg" /> 18th February 2005 Bogdan L. Vrusias © 2005 37 Introduction to Server-Side Web Development Page Directive • <%@ page import="package.class" %> • <%@ page errorPage="Relative URL" %> • <%@ page isErrorPage="true" %> • <%@ page contentType="application/vnd.ms-excel" %> 18th February 2005 Bogdan L. Vrusias © 2005 38 Introduction to Server-Side Web Development Include Directive • Use the include directive to include a file in the main JSP document at the time the document is translated into a servlet. • What is included is the actual content of the respective file. <%@ include file="header.jsp" %> 18th February 2005 Bogdan L. Vrusias © 2005 39 Introduction to Server-Side Web Development JSP Action Elements • There are three different types of action elements: – Standard • • • • • <jsp:include> <jsp:forward> <jsp:useBean> <jsp:plugin> <jsp:getProperty> and <jsp:setProperty> – JSTL (JavaServer Pages Standard Tag Library) • It provides tag libraries in the subject of Internationalization and formatting, XML, SQL, and the core tags. – Custom • Tags constructed by the developer. 18th February 2005 Bogdan L. Vrusias © 2005 40 Introduction to Server-Side Web Development Include Action Element • The jsp:include action lets you include the output (not the not the actual code) of a page at request time: <jsp:include page="header.jsp" /> <jsp:include page="header.jsp" %> <jsp:param name="title" value="Welcome"/> </jsp:include> NOTE: Is it similar to <%@ include file="header.jsp"%> ??? 18th February 2005 Bogdan L. Vrusias © 2005 41 Introduction to Server-Side Web Development Forward Action Element • The jsp:forward action lets you forward the output to another page: <jsp:forward page="main.jsp" /> NOTE: Not recommended… !!! Better use the forward method of the RequestDispatcher object. 18th February 2005 Bogdan L. Vrusias © 2005 42 Introduction to Server-Side Web Development Implicit Objects and the JSP Environment • The scriptlets and expressions written in a JSP page do not stand alone as a complete program – they need an environment in which to operate. • The JSP container provides this environment and makes it accessible to the page author through what are called implicit objects: – – – – – – – – – request (HttpServletRequest) response (HttpServletResponce) application (ServletContext) session (HttpSession) out (JspWriter) pageContext config page exception 18th February 2005 Bogdan L. Vrusias © 2005 43 Introduction to Server-Side Web Development Basic request Methods • String getParameter(String name) • Enumeration getParameterNames() • String getMethod() (e.g "POST", "GET") • Cookie[] getCookies() • String getHeader(String name) • Enumeration getHeaderNames() • HttpSession getSession(boolean create) • ... 18th February 2005 Bogdan L. Vrusias © 2005 44 Introduction to Server-Side Web Development Basic response Methods • void sendRedirect() • void addCookie(Cookie cookie) • void setHeader(String name) • void addHeader(String name) • void sendError(int sc [, String msg]) 18th February 2005 Bogdan L. Vrusias © 2005 45 Introduction to Server-Side Web Development Basic session Methods • Object getAttribute(String name) • void setAttribute(String name, Object value) • Enumeration getAttributeNames() • int setMaxInactiveInterval() • int getMaxInactiveInterval() • void invalidate() • void isNew() • void logout() • String getId() 18th February 2005 Bogdan L. Vrusias © 2005 46 Introduction to Server-Side Web Development Basic application Methods • String getRealPath(String path) • Object getAttribute(String name) • void setAttribute(String name , Object value) • void removeAttribute(String name) • Enumeration getAttributeNames() • void log(String msg) • URL getResource(String path) 18th February 2005 Bogdan L. Vrusias © 2005 47 Introduction to Server-Side Web Development Basic out Methods • void print(String value) • void println(String value) • void newLine() • void clear() 18th February 2005 Bogdan L. Vrusias © 2005 48 Introduction to Server-Side Web Development Tomcat • Tomcat is the official JavaServer Pages Web server. • Tomcat is the official reference implementation of the Java Servlet and JavaServer Pages technologies. Developed under the Apache license in an open and participatory environment. • Other popular Web servers are: – – – – – Apache Macromedia JRun Jetty Internet Information Server (IIS) Jigsaw http://jakarta.apache.org/tomcat/ 18th February 2005 Bogdan L. Vrusias © 2005 49 Introduction to Server-Side Web Development Exploring Tomcat • Please follow the demonstration on exploring Apache Tomcat. 18th February 2005 Bogdan L. Vrusias © 2005 50 Introduction to Server-Side Web Development Closing • Questions??? • Remarks??? • Comments!!! • Evaluation! 18th February 2005 Bogdan L. Vrusias © 2005 51