Bài giảng Web Technologies and e-Services - Bài 7, Phần 1: Web development with Java

Java Persistence Query Language (JPQL) v A query language that looks like SQL, but for accessing objects v Automatically translated to DB-specific SQL statements v select e from Employee e where e.id = :id § From all the Employee objects, find the one whose id matches the given value v Make RDBMS look like ODBMS v Data are accessed as objects, not rows and columns v Simplify many common operations. E.g. System.out.println(e.supervisor.name) v Improve portability § Use an object-oriented query language (OQL) § Separate DB specific SQL statements from application code v Object caching

pdf94 trang | Chia sẻ: hachi492 | Ngày: 06/01/2022 | Lượt xem: 302 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Bài giảng Web Technologies and e-Services - Bài 7, Phần 1: Web development with Java, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
Web development with Java 1 Outline 1. Servlet 2. JSP – Java Server Page 3. Java Beans 4. ORM (Object Relational Mapping) 2 Free Servlet and JSP Engines (Servlet/JSP Containers) v Apache Tomcat § v IDE: NetBeans, Eclipse § https://netbeans.org/ § https://eclipse.org/ v Some Tutorials: § Creating Servlet in Netbeans: § Creating Java Servlets With NetBeans: netbeans/ § Java Servlet Example: § Developing JSPs and Servlets with Netbeans: webapps/ Compiling and Invoking Servlets v Put your servlet classes in proper location § Locations vary from server to server. E.g., • tomcat_install_dir/webapps/ROOT/WEB-INF/classes v Invoke your servlets (HTTP request) § § Custom URL-to-servlet mapping (via web.xml) Java Servlets v 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 v Together with web pages and other components, servlets constitute part of a web application v 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 v Servlets are hosted by a servlet container, such as Apache Tomcat* *Apache Tomcat can be both a web server and a servlet container Server Platform Web Server Servlet Container The servlet container provides a Java Virtual Machine for servlet execution The web server handles the HTTP transaction details Environment For Developing and Testing Servlets v Compile: § Need Servlet.jar. Available in Tomcat package v Setup testing environment § Install and start Tomcat web server § Place compiled servlet at appropriate location Servlet Operation Servlet Methods v 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) Servlet Methods v The default .service() method simply invokes method-specific methods § depending upon the HTTP request method .service() .doGet() .doPost() .doHead() etc. Methods of HttpServlet and HTTP requests All methods take two arguments: an HttpServletRequest object and an HttpServletResponse object. Return a BAD_REQUEST (400) error by default. Methods HTTP Requests Comments doGet GET, HEAD Usually overridden doPost POST Usually overridden doPut PUT Usually not overridden doOptions OPTIONS Almost never overridden doTrace TRACE Almost never overridden HTTP Servlet Servlet Example 1 v 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("" + "Servlet Example Output" + "Hello!" + ""); htmlOut.close(); } } Servlet Example 2 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"); } } • This servlet also will say "Hello World" (not in HTML) Servlet Configuration v The web application configuration file, web.xml, identifies servlets and defines a mapping from requests to servlets HelloServlet servlet.HelloServlet HelloServlet /hello An identifying name for the servlet (appears twice) The servlet's package and class names The pathname used to invoke the servlet (relative to the web application URL) Environment Entries v Servlets can obtain configuration information at run-time from the configuration file (web.xml) § a file name, a database password, etc. v in web.xml: password</env-entry- description> UserId Xy87!fx9* java.lang.String Environment Entries v 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(); } Handling HTML Forms v An HTML form can be sent to a servlet for processing v The action attribute of the form must match the servlet URL mapping HelloServlet /hello User Id: public class HelloServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException { PrintWriter out = res.getWriter(); res.setContentType("text/html"); String userId = req.getParameter("userid"); out.println("Hello" + "Hello, " + userId + "!"); out.close(); } Simple Form Servlet State Management • session: a series of transaction between user and application • session state: the short-term memory that the application needs in order to maintain the session • e.g., shopping cart, user-id • cookie: a small file stored by the client at the instruction of the server Cookies • The Set-Cookie: header in an HTTP response instructs the client to store a cookie Set-Cookie: SESSIONID=B6E98A; Path=/slms; Secure • After a cookie is created, it is returned to the server in subsequent requests as an HTTP request Cookie: header Cookie: SESSIONID=B6E98A Cookie Attributes • Name: the unique name associated with the cookie • Content: value stored in the cookie • Expiration Date: cookie lifetime • Domain: Defines the hosts to which the cookie should be returned • Path: Defines the resource requests with which the cookie should be returned • Secure: if true, cookie is returned only with HTTPS requests Cookie Example • Name: session-id • Content: 104-1898635-929144 • Expiration Date: Monday, June 29, 2009 3:33:30 PM • Domain: .ehsl.org • Path: /slms • Secure: no • This cookie will be returned with all requests matching *.ehsl.org/slms*, through the indicated expiration date Session Management • HTTP is inherently stateless, i.e., there is no memory between transactions • Applications must maintain a session memory if it is required • Cookies are used to identify sessions, by recording a unique session-id State Management Client Cookie [session-id] Server Session Memory session • At the start of a new session, the server sets a new cookie containing the session-id • With each transaction, the client sends the session-id, allowing the server to retrieve the session Session Attributes • The methods session.setAttribute(key, value) session.getAttribute(key) store and retrieve session memory • key is a string; value can be any object • For example, session.setAttribute("userid", userId); String userId = (String)session.getAttribute("userid"); Problem 27 Initial Solution • Develop a number of servlets • Each servlet plays the role of one function (a.k.a business logic) Better Solution: Using MVC • Take business logic out servlets and put them inside Model Example 1: Beer Recommendation JSP page HTML page 31 beer_v1 websrc WEB-INF web.xml result.htmlform.htmlcom BeerExpert .java example web model BeerSelect .java Application Programming Structure Structure of Folder Development WEB-INF beer_v1 classes webapps web.xml result.htmlform.html com BeerExpert .class example web model BeerSelect .class tomcat form.html <form method="POST“ action="SelectBeer.do"> Select beer characteristics Color: light amber brown dark web.xml ServletBeer com.example.web.BeerSelect ServletBeer /SelectBeer.do Servlet BeerSelect – Version 1 public class BeerSelect extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("Beer Selection Advice"); String c = request.getParameter("color"); out.println("Got beer color "+c); } } Application Test Model BeerExpert public class BeerExpert { public List getBrands(String color){ List brands = new ArrayList(); if(color.equals("amber")){ brands.add("Jack Amber"); brands.add("Red Moose"); } else{ brands.add("Jail Pale Ale"); brands.add("Gout Stout"); } return brands; } } 38 Servlet BeerSelect – Version 2 import package com.example.web; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String c = request.getParameter("color"); BeerExpert be = new BeerExpert(); List result = be.getBrands(c); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("Beer Selection Advice"); Iterator it = result.iterator(); while(it.hasNext()){ out.print("try: "+it.next()); } } Application Test 40 Current Architecture of the Application Desired Application Architecture Result.jsp Beer Recommendation <% List styles=(List) request.getAttribute("styles"); Iterator it = styles.iterator(); while(it.hasNext()){ out.print("try: "+it.next()); } %> Servlet BeerSelect – Version 3 import package com.example.web; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String c = request.getParameter("color"); BeerExpert be = new BeerExpert(); List result = be.getBrands(c); request.setAttribute("styles", result); RequestDispatcher view = request.getRequestDispatcher("result.jsp"); view.forward(request, response); } Application Test 45 Outline 1. Servlet 2. JSP – Java Server Page 3. Java Beans 4. ORM (Object Relational Mapping) 46 Introduction and Overview v Server-side java: § Scheme 1: • HTML files placed at location for web pages • Servlets placed at special location for servlets • Call servlets from HTML files § Scheme 2: • JSP: HTML + servlet codes + jsp tags • Placed at location for web pages • Converted to normal servlets when first accessed Scheme 1 Scheme 2 Introduction and Overview v Example: Hello.jsp • • JSP Test • • JSP Test • Time: • • § JSP Test: normal HTML § : special JSP tags § new java.util.Date(): java code § Placed at: tomcat/webapps/ROOT/jsp Introduction and Overview v Ingredients of a JSP § Regular HTML • Simply "passed through" to the client by the servlet created to handle the page. § JSP constructs • Scripting elements let you specify Java code that will become part of the resultant servlet, • Directives let you control the overall structure of the servlet • Actions let you specify existing components that should be used, and control the behavior of the JSP engine • JavaBeans: a type of components frequently used in JSP JSP constructs - Scripting Elements v JSP converted to Servlet at first access v JSP scripting elements let you insert Java codes into the servlet results § Expressions: • Form • Evaluated and inserted into the output § Scriptlets • Form • Inserted into the servlet's service method § Declarations: • Form • Inserted into the body JSP constructs - Scripting Elements v JSP Expressions: § Form: § Example • Time: § Processing • Evaluated, converted to a string, and inserted in the page. • At run-time (when the page is requested) JSP constructs - Scripting Elements v JSP Expressions: § Several variables predefined to simply jsp expressions • request, the HttpServletRequest; • response, the HttpServletResponse; • session, the HttpSession associated with the request (if any); • out, the PrintWriter (a buffered version of type JspWriter) used to send output to the client. § Example: • Your hostname: JSP constructs - Scripting Elements v JSP Scriptlets § Form: § !"#$%&'( • <% String queryData = request.getQueryString(); • out.println("Attached GET data: " + queryData); %> § Inserted into the servlet's service method EXACTLY as written § Can access the same predefined variables as JSP expressions JSP constructs - Scripting Elements v JSP Declarations: § Form: § Example: <%! private int accessCount = 0; %> § Inserted into the main body of the servlet class (outside of the service method processing the request) § Normally used in conjunction with JSP expressions or scriptlets. • • Accesses to page since server reboot: • JSP constructs - JSP Directives v Affect the overall structure of the servlet class. § Form: <%@ directive attribute1="value1" attribute2="value2" ... • AttributeN="valueN" %> v Two commonly used types of directives § Page directives • § Include directives JSP constructs - Directives v Examples of Page directives § § • Same as : § JSP constructs - Directives v Include Directive § lets you include files at the time the JSP page is translated into a servlet (static including). § Form: § !"#$%&')*+,-#,+./)01'2')+,)+*)-*'3-&( • !"#$%&"'()"*(+&%,"-%"*%,+**+#%+.%#"&/%0")$12 • 31")$ • !""#$%&'("'($&)$(*"$'+,-.+(-&'$/+0$-'$+'$123 • 4'%567"$(*"$123$-'$+55$(*"$#+."8 JSP constructs - Actions v JSP actions control the behavior of the servlet engine. Let one § Dynamically insert a file § Forward the user to another page § Reuse JavaBeans components § .. JSP constructs - Actions v The include action § Form: • § Inserts the file at the time the page is requested. • Differs from the include directive, which inserts file at the time the JSP page is translated into a servlet. § Example: IncludeAction.jsp JSP constructs - Actions v The forward action: § Form: " /> § Forward to the page specified. § Example: ForwardAction.jsp v Several actions related to reuse of JavaBeans components § Discuss next JSP JSP ● HTML code in Java ● Not easy to author ● Java-like code in HTML ● Very easy to author ● Code is compiled into a servlet Servlets JSP vs Servlet v Servlets: § Using println() to create HTML pages • àWhenever developers make a change, they have to recompile and redeploy, which is not really convenient v JSP: § correct the problem of Servlet Benefits of using JSP... § Contents and display logic (or presentation logic) are separated. § Web application development can be simplified because business logic is captured in the form of JavaBeans or custom tags while presentation logic is captured in the form of HTML template. § Because the business logic is captured in component forms, they can be reused in other Web applications. § And again for web page authors, dealing with JSP page is a lot easier than writing Java code. § And just like Servlet technology, JSP technology runs over many different platforms. Benefits of Using JSP over Servlet v Exploit both two technologies § The power of Servlet is “controlling and dispatching” § The power of JSP is “displaying” v In practice, both Servlet and JSP are very useful in MVC model § Servlet plays the role of Controller § JSP plays the role of View Outline 1. Servlet 2. JSP – Java Server Page 3. Java Beans 4. ORM (Object Relational Mapping) 66 JavaBeans v Beans § Objects of Java classes that follow a set of simple naming and design conventions • Outlined by the JavaBeans specification § Beans are Java objects • Other classes can access them and their methods • One can access them from jsp using scripting elements. § Beans are special Java objects • Can be accessed using JSP actions. • Can be manipulated in a builder tool • Why interesting? • Programmers provide beans and documentations • Users do not have to know Java well to use the beans. JavaBeans v Naming conventions: § Class name: • Often include the word Bean in class name, such as UserBean § Constructor: • Must implement a constructor that takes no arguments • Note that if no constructor is provided, a default no-argument constructor will be provided. JavaBeans v Naming conventions: Methods § Semantically, a bean consists of a collection of properties (plus some other methods) § The signature for property access (getter and setter) methods • public void setPropertyName(PropertyType value); • public PropertyType getPropertyName() § Example: • Property called rank: public void setRank(String rank); public String getRank(); • Property called age: public void setAge(int age); public int getAge(); JavaBeans v Property name conventions § 4'5+/)0+,1)#)&.0'26#*')&',,'2) § 7%%'26#*'),1')3+2*,)&',,'2).3)'#61)0.289)'"6'%,),1')3+2*,) ./'9)+/),1')%2.%'2,:)/#$';) § !"#$%&'*())firstName, lastName v !"##$%&"'()'*+%$,,$#+-'(+*$,,$#+.$,/"(%0 § setFirstName, setLastName § getFirstName, getLastName § Note the case difference between the property names and their access method JavaBeans v Indexed properties § Properties whose values are sets § Conventions: • public PropertyType[] getProperty() • public PropertyType getProperty(int index) • public void setProperty(int index, PropertyType value) • public void setProperty(PropertyType[]) • public int getPropertySize() JavaBeans v Bean with indexed properties import java.util.*; public class StatBean { private double[] numbers; public StatBean() {numbers = new double[0]; } public double getAverage() {..} public double getSum() { .. } public double[] getNumbers() { return numbers; } public double getNumbers(int index) { return numbers[index]; } public void setNumbers(double[] numbers) { this.numbers = numbers; } public void setNumbers(int index, double value) { numbers[index] = value; } public int getNumbersSize() { return numbers.length; } } JavaBeans v Boolean Properties § Properties that are either true or false § Setter/getter methods conventions • public boolean isProperty(); • public void setProperty(boolean b); • public boolean isEnabled(); • public void setEnabled(boolean b); • public boolean isAuthorized(); • public void setAuthorized(boolean b); Using Beans in JSP v JSP actions for using beans: § <*%(-*'4'#/ • Find or instantiate a JavaBean. § <*%(*',=2.%'2,: • Set the property of a JavaBean. • Call a setter method § <*%(5',=2.%'2,: • Get the property of a JavaBean into the output. • Call a getter method Using Beans in JSP v Example: The bean • package jspBean201; public class SimpleBean { private String message = "No message specified"; public String getMessage() { return(message); } public void setMessage(String message) { this.message = message; } } v Compile with javac and place in regular classpath § In Tomcat, same location as servlets. (can be different on other web servers) Using Beans in JSP v Use SimpleBean in jsp: ReuseBean.jsp § >+/8)#/8)+/*,#/,+#,')?'#/ § @',)%2.%'2,: <jsp:setProperty name="test" property="message" value="Hello WWW“/> § A',)%2.%'2,:()6#&&),1')5',B'**#5')$',1.8)#/8)+/*'2,) 01#,)+,)2',-2/*),.)0'?)%#5' CDEFB'**#5'()CGF CHGFCHDEF) Using Beans in JSP v The jsp:useBean action: § Format • Simple format: <jsp:useBean id="test" class=“jspBean201.SimpleBean" /> • Container format: body portion executed only when bean first instantiated • Body Using Beans in JSP v The jsp:useBean action: § Attributes: • Scope: Indicates the context in which the bean should be made available • page (default): available only in current page • request, available only to current request • session, available only during the life of the current HttpSession • Application, available to all pages that share the same ServletContext • id: Gives a name to the variable that will reference the bean • New bean not instantiated if previous bean with same id and scope exists. • class: Designates the full package name of the bean. • type and beanName: can be used to replace the class attribute Using Beans in JSP v The jsp:setProperty action: § Forms: § 4.%*5$%'"67$%"**-(,7*$%(1%71$8 • String values are automatically converted to numbers, boolean, Boolean, byte, Byte, char, and Character § 4.%*5$%0"-"#%"**-(,7*$%(1%71$8 • 9&$%&',"08-&' Outline 1. Servlet 2. JSP – Java Server Page 3. Java Beans 4. ORM (Object Relational Mapping) 80 The Object-Oriented Paradigm v The world consists of objects v So we use object-oriented languages to write applications vWe want to store some of the application objects (a.k.a. persistent objects) v So we use a Object Database? The Reality of DBMS v Relational DBMS are still predominant § Best performance § Most reliable § Widest support v Bridge between OO applications and relational databases § CLI and embedded SQL (JDBC) § Object-Relational Mapping (ORM) tools Object-Relational Mapping v It is a programming technique for converting object-type data of an object oriented programming language into database tables. v Hibernate is used convert object data in JAVA to relational database tables. What is Hibernate? v It is an object-relational mapping (ORM) solution that allows for persisting Java objects in a relational database v Open source v Development started late 2001 The ORM Approach customer employee account Application Persistent Data Store ORM tool Oracle, MySQL, SQL Server Flat files, XML O/R Mapping Annotations v Describe how Java classes are mapped to relational tables @Entity Persistent Java Class @Id Id field @Basic (can be omitted) Fields of simple types @ManyToOne @OneToMany @ManyToMany @OneToOne Fields of class types Basic Object-Relational Mapping v Class-level annotations § @Entity and @Table v Id field § @Id and @GeneratedValue v Fields of simple types § @Basic (can be omitted) and @Column v Fields of class types § @ManyToOne and @OneToOne persistence.xml v § name v § Database information § Provider-specific properties v No need to specify persistent classes Access Persistent Objects v EntityManagerFactory v EntityManager v Query and TypedQuery v Transaction § A transaction is required for updates Some EntityManager Methods v find( entityClass, primaryKey ) v createQuery( query ) v createQuery( query, resultClass ) v persist( entity ) vmerge( entity ) v getTransaction() Persist() vs. Merge() Scenario Persist Merge Object passed was never persisted 1. Object added to persistence context as new entity 2. New entity inserted into database at flush/commit 1. State copied to new entity. 2. New entity added to persistence context 3. New entity inserted into database at flush/commit 4. New entity returned Object was previously persisted, but not loaded in this persistence context 1. EntityExistsException thrown (or a PersistenceException at flush/commit) 1. Existing entity loaded. 2. State copied from object to loaded entity 3. Loaded entity updated in database at flush/commit 4. Loaded entity returned Object was previously persisted and already loaded in this persistence context 1. EntityExistsException thrown (or a PersistenceException at flush or commit time) 1. State from object copied to loaded entity 2. Loaded entity updated in database at flush/commit 3. Loaded entity returned Java Persistence Query Language (JPQL) v A query language that looks like SQL, but for accessing objects v Automatically translated to DB-specific SQL statements v select e from Employee e where e.id = :id § From all the Employee objects, find the one whose id matches the given value See Chapter 4 of Java Persistence API, Version 2.0 Advantages of ORM vMake RDBMS look like ODBMS v Data are accessed as objects, not rows and columns v Simplify many common operations. E.g. System.out.println(e.supervisor.name) v Improve portability § Use an object-oriented query language (OQL) § Separate DB specific SQL statements from application code v Object caching Q&A Thank you for your attentions! 94

Các file đính kèm theo tài liệu này:

  • pdfbai_giang_web_technologies_and_e_services_bai_7_phan_1_web_d.pdf