1 / 64

Web Engineering

Web Technologies II Lecture X – 9 th December 2008 Federico M. Facca. Web Engineering. Where are we?. Overview. Servlet JSP Java Beans Wrap-up. ServletS. Servlet Overview. Servlet is an extension to the web server that adds additional functionalities and programmability

zola
Télécharger la présentation

Web Engineering

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Web Technologies II Lecture X – 9th December 2008 Federico M. Facca Web Engineering

  2. Where are we?

  3. Overview • Servlet • JSP • Java Beans • Wrap-up

  4. ServletS

  5. Servlet Overview • Servlet is an extension to the web server that adds additional functionalities and programmability • Servlet makes full use of the Java platform • A servlet is basically a Java class. Every servlet extends “javax.servlet.http.HttpServlet” class • Related classes are wrapped in the package of “javax.servlet” and “javax.servlet.http”

  6. Java Servlet Web Application • Servlet development life cycle • Development • Defining servlet classes, methods and properties • Deployment • Servlet mapping to web environment • Deployment on Web Application Server • Execution • Understand its execution life cycle

  7. Basic Servlet Structure public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response ) throws ServletException, java.io.IOException { … } public void doPost(HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { … } }

  8. Constructor and “Main” Method • Servlet instances are created (invoked) by servlet container automatically when requested – not by user classes or methods • No need to define constructor • The entry point is NOT the “main” method, but the two methods • Use “doGet” or “doPost” to perform tasks

  9. Servlet Deployment • Web content root folder (public_html) • The starting point of the whole web application • All files and sub-directories goes here:html, images, documents … • /public_html/WEB-INF/ • This folder contains configuration files and compiled class • Not directly accessible through the web • /public_html/WEB-INF/classes/ • All compiled classes (servlet classes and other classes) are in this folder

  10. Servlet Mapping • Servlet class needs to be mapped to an accessible URI (mainly through HTTP) • For convenience, a servlet can be accessed in a general pattern (invoker servlet) • http://[domain]/[context]/servlet/[ServletClassName] • http://localhost:8988/servletintro/servlet/SimpleServlet • Specific mapping: using the configuration file “web.xml” • A servlet is specifically mapped to a user defined URL

  11. “web.xml” Configuration <servlet> <servlet-name>HelloW</servlet-name> <servlet-class>HelloWorld </servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloW</servlet-name> <url-pattern>hello</url-pattern> </servlet-mapping> • Using the file “web.xml” for more specific mapping • The file is in the“WEB-INF” folder • Example • Servlet class • HelloWorld.class • Application context: • http://localhost:8080/servletintro/ • Invoker class mapping • http://localhost:8080/servletintro/servlet/HelloWorld • Specific mapping • http://localhost:8080/servletintro/hello • For more mapping examples, see example “web.xml”

  12. doPost() service() doGet() Servlet Execution Life Cycle Servlet Class First Request Servlet Instance in Memory init() Subsequent Requests (can be from different users and sessions)

  13. Response and Request Message • Web servers and web clients communicate through HTTP messages (protocols) • Request message: client  server • Response message: server  client • HTTP message consists of header and body • HTTP header: information describing the message and the context of the message • HTTP body: content usually for display

  14. Request Processing • Major request method type • Get • User data is sent as part of the request URL • No request message body • Triggering actions: address bar (in browser), link, form, … • Post • User data is sent in the request message body • Triggering actions: form, …

  15. doGet() Method • Servlet class uses the “doGet()” method to process general (servlet) URL request public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException,IOException { ( generating response message … ) }

  16. Response Processing • Response body • Generating HTML or other content for display • Response header • Manipulating response message header data to affect its behavior

  17. Generating Response Content • Using “response” (javax.servlet.http.HttpServletResponse) and “java.io.PrintWriter” to generate HTML to the output stream java.io.PrintWriter out = response.getWriter(); out.println(“<html>”); … out.println(“</html>”);

  18. Using StringBuffer • When there are frequent changes to a string, using StringBuffer (java.lang.StringBuffer) is more efficient StringBuffer html = new StringBuffer(); html.append(“<html>”); html.append(“<head>"); … … String s= html.toString(); • This is very useful when generating HTML page strings

  19. HTML Paragraph Formatting • Formatting HTML source code, or final display in the browser? • Use escape characters (/n, /t, etc) to format source HTML code • Use HTML tags to format the final output in broswer • <p>, <br>, …

  20. Dynamically Generating HTML • Use Java programming capability to dynamically generate HTML • Dynamic content: date/time, user name, etc. • Dynamic HTML elements (tags) • Dynamic element attributes • … (Be creative!)

  21. Getting User Data • Two ways • URL parameter (Get) • http:// …/somefile?p1=value1&p2=value2 • HTML Form (Get or Post) Servlet User Input URL parameter Get doGet Get HTML Form doPost Post

  22. URL with Parameters • User data can be sent with “get” request • http:// …/somefile?p1=value1&p2=value2 • Applications • Template page for data item details • http://www.newegg.com/Product/Product.asp?Item=N82E16827152058 • http://www2.cis.gsu.edu/cis/people/display.asp?pk=3 • Page content selection • http://forum.java.sun.com/category.jspa?categoryID=20 • http://javaweb.jackzheng.net/cis3270su06/index.jsp?page=schedule • User input • http://www.google.com/search?q=java • Conditions/configuration • http://finance.yahoo.com/q/bc?s=MSFT&t=5d&l=on&z=l&q=l • http://msdn.e-academy.com/elms/Storefront/Home.aspx?campus=gsu_cis • Page display/format, page content, error message, …

  23. Handling “Get” Parameter • In HTTP “get”, user data are sent with URL • http://…/GetData?p1=value1&p2=value2 • Using the request object (given by the doGet method) to retrieve these data • String p1=request.getParameter(“p1”); • String p2=request.getParameter(“p2”); • String p[ ]=request.getParameterValues(“p1”); • Note: parameter names are case sensitive

  24. Number Conversion • All parameter values are String type • String p1=request.getParameter(“p1”); • What if numbers are needed? • Integer.parseInt() • Double.parseDouble() • Conversion exception needs to be handled

  25. Irregular Parameters • Missing value (empty string is returned) • …/GetData?data= • Missing parameter (parameter undefined, null) • …/GetData? // no parameter at all • …/GetData?data // ”data” is still not defined • …/GetData?Data=red // case sensitive • Blanks • …/GetData?data=hello world • Redundant parameter • …/GetData?data=blue&data=red // use getParameterValues()

  26. Java Server Pages

  27. What is JSP • Servlets – HTML in java code • JSP – java code in HTML <HTML> <HEAD> <TITLE>Java Server Pages</TITLE> </HEAD> <BODY> <H1>JSP</H1> <%= “Java Server Pages.” %> <HR> </BODY> </HTML>

  28. JSP Lifecycle JSP to Servlet Translation Servlet Compiled Servlet Loaded jspInit() called _jspService() called

  29. The need for JSP • With servlets • It is hard to write and maintain HTML • Cannot use standard HTML tools • HTML is inaccessible to non-java developers

  30. The benefits of JSP • Easier to write and maintain HTML • Can use standard HTML tools • Can divide up development team

  31. Advantages • The Java advantage • Extensive API • Easy to learn • Big development community • Standardization & server support

  32. Location of JSP pages • Unlike servlets, JSP pages can be located in any of the locations where HTML files can be put.

  33. JSP Scripting Elements • JSP scripting elements enable us to insert java code into JSP files. • There are three types of elements • Expressions <%= Java Expression %> • Scriptlets <% Java Code %> • Declarations <%! Field/Method %>

  34. JSP Expressions • A JSP expression is used to insert java code directly into the output. Syntax <%= Expression %> Eg: Current Time: <%= new java.util.Date() %> Output: Current Time: Tue Aug 22 21:05:47 IST 2006 • The expression is evaluated, converted to string and inserted into the page.

  35. Predefined Variables • To simplify expressions, JSP provides a number of predefined variables (implicit objects). • request – the HttpServletRequest • response – the HttpServletResponse • session – the HttpSession • out – the Writer (buffered version of type JspWriter) • application – the ServletContext • config – the ServletConfig • pageContext – introduced to give single point of access to page attributes • page – synonym for “this”

  36. JSP Scriptlets • To something more than just output the value of a simple expression. • Allows the programmer to insert arbitrary code into the servlets _jspService method. Syntax: <% Java Code %> Eg: <% String str = request.getParameter(“name”); out.print(“Name : ”+str); %>

  37. JSP Declarations • JSP declarations lets the programmer define methods or fields that get inserted into the main body of the generated servlet (outside the _jspService() method) Syntax: <%! Field/Method definition %> Eg: <%! private String getMessage(){ return “This is a simple message!!”; } %> <%= getMessage() %>

  38. XML Syntax • XML like syntax for JSP expression, scriptlet & declaration • <jsp:expression>…</jsp:expression> • <jsp:scriptlet>…</jsp:scriptlet> • <jsp:declaration>…</jsp:declaration> • Supported by JSP versio 1.2 & above • These are case sensitive, should be in lowercase

  39. JSP Directives • A JSP directive affects the overall structure of the servlet that results from the JSP page. • A JSP directive has the form: • <%@ directive attribute=“value” … … %> • There are three types: • page, include & taglib

  40. JSP Page Directive • The page directive controls the structure of the servlet by importing classes, customizing the superclass, changing content type, etc. • The JSP Page directive has the following attributes: • import, contentType, pageEncoding, session, isELIgnored, buffer, autoFlush, info, errorPage, isThreadSafe, language & extends

  41. JSP Page Directive Attributes • import=“java.util.*, java.sql.*” • contentType=“text/html; charset=ISO-8859-1” • pageEncoding=“Shift_JIS” • session=“true/false” • isELIgnored=“false/true” • buffer=“size in kb” • autoFlush=“true/false” • info=“Some info message.” • errorPage=“error.jsp” • isErrorPage=“false/true” • isThreadSafe=“true/false” • language=“java” • extends=“package.class”

  42. Including Files • There are three ways of including external files into a JSP document. • <jsp:include …>… • <%@ include …> • <jsp:plugin …>…

  43. The jsp:include Action • This includes the output of a secondary page at the time the main page is requested. • The output of the sub page must be HTML generated by a servlet or JSP. <jsp:include page=“/inc/header.jsp” flush=“true” /> <jsp:include page=“/inc/header.jsp” flush=“true”> <jsp:param name=“paramName” value=“xyz”> </jsp:include>

  44. The Include Directive • This includes directive is used to include a file in the main JSP at the time of translation into a servlet. • The code of the included file is added to that of the JSP document. <%@ include page=“/inc/header.jsp” %>

  45. Forwarding Requests • This action is used to get the output of a JSP file completely from another JSP or servlet. • The output of the auxiliary JSP or servlet is sent to the client, not that of the current JSP. <jsp:forward page=“xyz.jsp” />

  46. The jsp:plugin Action • Used to embed a java applet into the generated output. • Java applets are rarely used in web pages now a days. <jsp:plugin type=“applet” code=“MyApplet.class” width=“400” height=“300”> </jsp:plugin>

  47. Java BEANS

  48. Java Beans • What Are Beans? • Beans are standard java objects. • Must have a zero-arguments constructor. • Should have no public fields. • Values should be accessed through method calls, getXxx, setXxx & isXxx.

  49. Java Bean (example) public class Person { private int age; private String name; … … … public void setAge(int age){ this.age = age; } public void setName(String name){ this.name = name; } public intgetAge(){ return this.age; } public String getName(){ return this.name; } … … … }

  50. Using Java Beans & JSP • There are three main constructs to use Java Beans in JSP. • <jsp:useBean ……… /> • <jsp:getProperty ……… /> • <jsp:setProperty ……… />

More Related