Lập trình hướng đối tượng JSP/Servlet

Lập trình hướng đối tượng JSP/Servlet

Author: Vinh Thanh Nguyen


3 Resource Creation

 
    A resource is a program object that provides(cung cấp) connections to systems, such as database servers and messaging systems. (A Java Database Connectivity(Kết nối cơ sở dữ liệu) resource is sometimes referred to as a data source.) Each resource object is identified(xác định) by a unique, people-friendly name, called the JNDI name. For example, the JNDI name of the preconfigured(cấu hình sẵn) JDBC resource for the Java DB database that is shipped(vận chuyển) with GlassFish Server is java:comp/DefaultDataSource.

3.1 Resources and JNDI Naming

    In a distributed application (ứng dụng phân tán), components need to access other components and resources, such as databases. For example, a servlet might invoke (có thể gọi) remote methods (phương thức từ xa) on an enterprise bean that retrieves (để lấy) information from a database. In the Java EE platform, the Java Naming and Directory Interface (JNDI) naming service enables(cho phép) components to locate(xác định vị trí) other components and resources.

    A resource is a program object that provides(cung cấp) connections(các kết nối) to systems, such as database servers and messaging systems. (A Java Database Connectivity resource is sometimes referred to as a data source (đôi khi được gọi là nguồn dữ liệu).) Each resource object is identified (được xác định) by a unique (duy nhất), people-friendly name (có tên dễ hiểu), called the JNDI name. For example, the JNDI name of the preconfigured(cấu hình sẵn) JDBC resource for the Java DB database that is shipped(được vận chuyển) with GlassFish Server is java:comp/DefaultDataSource.

    An administrator creates resources(tài nguyên) in a JNDI namespace. In GlassFish Server, you can use either(hoặc) the Administration Console or the asadmin command to create resources. Applications then use annotations(chú thích) to inject(chích(tiêm)) the resources. If an application uses resource injection, GlassFish Server invokes(cầu khẩn/nhờ) the JNDI API, and the application is not required to do so(không bắt buộc phải làm vậy). However, it is also possible(cũng có thể) for an application to locate(định vị) resources by making direct calls to the JNDI API. (nó cũng có thể cho một ứng dụng để xác định vị trí các nguồn lực bằng cách thực hiện cuộc gọi trực tiếp đến JNDI API).

A resource object and its JNDI name are bound together(ràng buộc với nhau) by the naming and directory service. To create a new resource, a new name/object binding(ràng buộc đối tượng) is entered(nhập vào) into the JNDI namespace. You inject(tiêm) resources by using the @Resource annotation in an application.

You can use a deployment descriptor(script deploy) to override the resource mapping that you specify(chỉ định) in an annotation. Using a deployment descriptor allows you to change an application by repackaging it rather than (thay vì) by both recompiling the source files and repackaging. However, for most applications a deployment descriptor is not necessary(không cần thiết).

3.2 DataSource Objects and Connection Pools

   To store(lưu), organize(tổ chức), and retrieve(truy xuất) data, most applications use a relational database (CSDL quan hệ). Java EE 7 components may access relational databases through the JDBC API. For information on this API, see http://docs.oracle.com/javase/7/docs/technotes/guides/jdbc/.

    In the JDBC API, databases are accessed by using DataSource objects. A DataSource has a set of properties that identify and describe (xác định và mô tả) the real-world data source that it represents(đại diện). These properties include such information as the location of the database server, the name of the database, the network protocol to use to communicate with the server, and so on. In GlassFish Server, a data source is called a JDBC resource.

    Applications access a data source by using a connection, and a DataSource object can be thought of as (có thể được coi là) a factory(nhà máy) for connections to the particular(cụ thể) data source that the DataSource instance represents(đại diện). In a basic DataSource implementation(thực hiện), a call to the getConnection method returns a connection object that is a physical connection to the data source.

    A DataSource object may be registered(đã đăng ký) with a JNDI naming service. If so (nếu có), an application can use the JNDI API to access that DataSource object, which can then be used to connect to the data source it represents(đại diện).

    DataSource objects that implement(thực hiện) connection pooling(tổng hợp) also(cũng) produce(tạo ra) a connection to the particular(cụ thể) data source that the DataSource class represents. The connection object that the getConnection method returns is a handle(xử lý) to a PooledConnection object rather than (hơn là) a physical connection. An application uses the connection object in the same way that it uses a connection. Connection pooling has no effect (không ảnh hưởng) on application code except(ngoại trừ) that a pooled connection, like all connections, should always be explicitly closed (đóng lại một cách rõ ràng). When an application closes a connection that is pooled(tập hợp lại), the connection is returned to a pool of reusable connections (kết nối được trả lại cho một nhóm các kết nối tái sử dụng được). The next time getConnection is called, a handle(xử lý) to one of these pooled connections will be returned if one is available. Because connection pooling avoids(tránh) creating a new physical connection every time one is requested, applications can run significantly faster (nhanh hơn đáng kể).

    A JDBC connection pool is a group of reusable(tái sử dụng) connections for a particular(cụ thể) database. Because creating each new physical connection is time consuming (mất thời gian), the server maintains(duy trì) a pool of available connections to increase(tăng) performance. When it requests a connection, an application obtains(kiếm được) one from the pool. When an application closes a connection, the connection is returned to the pool.

    Applications that use the Persistence API specify(xác định) the DataSource object they are using in the jta-data-source element of the persistence.xml file:

<jta-data-source>jdbc/MyOrderDB</jta-data-source>
    This is typically(thường) the only reference to a JDBC object for a persistence unit. The application code does not refer(đề cập) to any JDBC objects.

3.3 Creating Resources Administratively
    Before you deploy or run many applications, you may need to create resources for them. An application can include a glassfish-resources.xml file that can be used to define resources for that application and others. You can then use the asadmin command, specifying(chỉ rõ) as the argument a file named glassfish-resources.xml, to create the resources administratively(hành chính), as shown.

 asadmin add-resources glassfish-resources.xml

The glassfish-resources.xml file can be created in any project using NetBeans IDE or by hand. Some of the JMS examples use this approach(tiếp cận) to resource creation. A file for creating the resources needed(cần thiết) for the JMS simple producer(nhà sản xuất) example can be found in the jms/simple/producer/src/main/setup directory.

    You could also use the asadmin create-jms-resource command to create the resources for this example. When you are done using the resources, you would(sẻ) use the asadmin list-jms-resources command to display their names, and the asadmin delete-jms-resource command to remove them, regardless(bất kể) of the way you created the resources.

4 Injection (chích)

This chapter provides(cung cấp) an overview(tổng quan) of injection in Java EE and describes(mô tả) the two injection mechanisms provided (các cơ chế cung cấp) by the platform: resource injection and dependency(phụ thuộc) injection.

Java EE provides injection mechanisms(cơ chế) that enable your objects to obtain (đạt được) references to resources and other dependencies (phụ thuộc khác) without having to instantiate them directly. You declare(khai báo) the required(bắt buộc) resources and other dependencies in your classes by decorating(trang trí) fields or methods with one of the annotations that mark(đánh dấu) the field as an injection point. The container then provides the required instances at runtime. Injection simplifies(đơn giản hóa) your code and decouples(tách) it from the implementations(việc thực hiện) of its dependencies(phụ thuộc).

4.1 Resource Injection


Resource injection enables(cho phép) you to inject any resource available in the JNDI namespace into any container-managed(quản lý) object, such as a servlet, an enterprise bean, or a managed bean. For example, you can use resource injection to inject data sources, connectors, or custom resources available in the JNDI namespace.

The type you use for the reference to the injected instance is usually(thường là) an interface, which decouples(tách) your code from the implementation of the resource.

For example, the following code injects a data source object that provides connections to the default Java DB database shipped with GlassFish Server:
public class MyServlet extends HttpServlet {
    @Resource(name="java:comp/DefaultDataSource")
    private javax.sql.DataSource dsc;
    ...
}
In addition(ngoài việc) to field-based injection as in the preceding(trước) example, you can inject resources using method-based injection:
public class MyServlet extends HttpServlet {
    private javax.sql.DataSource dsc;
    ...
    @Resource(name="java:comp/DefaultDataSource")
    public void setDsc(java.sql.DataSource ds) {
        dsc = ds;
    }
}
To use method-based injection, the setter method must follow the JavaBeans conventions(quy ước) for property names: The method name must begin with set, have a void return type, and have only one parameter.
The @Resource annotation is in the javax.annotation package and is defined in JSR 250 (Common Annotations for the Java Platform). Resource injection resolves(giải quyết) by name, so it is not typesafe: the type of the resource object is not known at compile time, so you can get runtime errors if the types of the object and its reference do not match(không khớp).

4.2 Dependency Injection

Dependency injection enables you to turn(chuyển) regular Java classes (các lớp java thông thường) into managed objects (các đối tượng được quản lý) and to inject them into any other managed object. Using dependency injection, your code can declare dependencies (khai báo phụ thuộc) on any managed object. The container (vùng lưu trữ) automatically provides instances of these dependencies at the injection points at runtime, and it also manages the lifecycle(vòng đời) of these instances for you.

Dependency injection in Java EE defines scopes (định nghĩa phạm vi), which determine the lifecycle (xác định vòng đời) of the objects that the container instantiates(khởi tạo) and injects(tiêm vào). For example, a managed object that is only needed to respond to a single client request (such as a currency converter) has a different scope (phạm vi khác) than a managed object that is needed to process multiple client requests within a session (such as a shopping cart).

You can define managed objects (also called managed beans) that you can later(sau đó) inject by assigning a scope (gán một phạm vi) to a regular class (cho một lớp thông thường):

@javax.enterprise.context.RequestScoped
public class CurrencyConverter { ... }

Use the javax.inject.Inject annotation to inject managed beans; for example:

public class MyServlet extends HttpServlet {
    @Inject CurrencyConverter cc;
    ...
}

As opposed to (khác với) resource injection, dependency injection is typesafe because it resolves by type (giải quyết theo loại). To decouple(tách) your code from the implementation(thực hiện) of the managed bean, you can reference the injected instances using an interface type and have your managed bean implement that interface.

For more information about dependency injection, see Chapter 23, "Introduction to Contexts and Dependency Injection for Java EE"and JSR 299 (Contexts and Dependency Injection for the Java EE Platform).

4.3 The Main Differences between Resource Injection and Dependency Injection

Table 4-1 lists the main differences between resource injection and dependency injection.

Table 4-1 Differences between Resource Injection and Dependency Injection
Injection MechanismCan Inject JNDI Resources DirectlyCan Inject Regular(thường xuyên) Classes DirectlyResolves ByTypesafe
Resource InjectionYesNoResource nameNo
Dependency InjectionNoYesTypeYes




5 Packaging

This chapter describes(mô tả) packaging. A Java EE application is packaged(đóng gói) into one or more standard units (nhiều đơn vị tiêu chuẩn) for deployment to any Java EE platform–compliant system (hệ thống tương thích). Each unit contains a functional(chức năng) component(thành phần) or components, such as an enterprise bean, web page, servlet, or applet, and an optional deployment descriptor(bộ mô tả) that describes its content.

5.1 Packaging Applications

A Java EE application is delivered(đã giao) in a Java Archive (JAR) file, a Web Archive (WAR) file, or an Enterprise Archive (EAR) file. A WAR or EAR file is a standard JAR (.jar) file with a .war or .ear extension(phần mở rộng). Using JAR, WAR, and EAR files and modules makes it possible(có thể) to assemble(thu thập) a number of different Java EE applications using some of the same components. No extra coding is needed (không cần code thêm); it is only a matter(vấn đề) of assembling(lắp ráp) (or packaging(đóng gói)) various(nhiều) Java EE modules into Java EE JAR, WAR, or EAR files.

An EAR file (see Figure 5-1) contains(chứa) Java EE modules and, optionally(tùy chọn), deployment descriptors (bộ mô tả triển khai). A deployment descriptor, an XML document with an .xml extension, describes the deployment settings of an application, a module, or a component. Because deployment descriptor information is declarative(khai báo), it can be changed without the need to modify the source code (nó có thể được thay đổi mà không cần sửa đổi mã nguồn.). At runtime, the Java EE server reads the deployment descriptor and acts upon the application (hoạt động theo ứng dụng), module, or component accordingly(tương ứng).

Deployment information is most commonly specified (thường được chỉ định) in the source code by annotations. Deployment descriptors, if present (nếu có), override what is specified (những gì được xác định) in the source code.


Figure 5-1 EAR File Structure
Description of Figure 5-1 follows
Description of "Figure 5-1 EAR File Structure"

The two types of deployment descriptors are Java EE and runtime. A Java EE deployment descriptor is defined(xác định) by a Java EE specification(đặc tả) and can be used to configure deployment settings on any Java EE-compliant(tuân thủ) implementation(triển khai). A runtime deployment descriptor is used to configure Java EE implementation-specific(cụ thể) parameters. For example, the GlassFish Server runtime deployment descriptor contains such information as the context root of a web application as well as (cũng như) GlassFish Server implementation-specific parameters, such as (chẳng hạn) caching directives (chỉ thị bộ nhớ đệm). The GlassFish Server runtime deployment descriptors are named glassfish-moduleType.xml and are located(đặt) in the same META-INF directory as the Java EE deployment descriptor.

A Java EE module consists(bao gồm) of one or more Java EE components for the same container type and, optionally, one component deployment descriptor of that type. An enterprise bean module deployment descriptor, for example, declares transaction attributes (khai báo thuộc tính transaction) and security authorizations (ủy quyền bảo mật) for an enterprise bean. A Java EE module can be deployed as a stand-alone(độc lập) module.

Java EE modules are of the following types:


  • EJB modules, which contain class files for enterprise beans and, optionally, an EJB deployment descriptor. EJB modules are packaged as JAR files with a .jar extension.
  • Web modules, which contain servlet class files, web files, supporting class files, GIF and HTML files, and, optionally, a web application deployment descriptor. Web modules are packaged as JAR files with a .war (web archive) extension.
  • Application client modules, which contain class files and, optionally, an application client deployment descriptor. Application client modules are packaged as JAR files with a .jar extension.
  • Resource adapter modules, which contain all Java interfaces, classes, native libraries, and, optionally, a resource adapter deployment descriptor. Together, these implement the Connector architecture (see Java EE Connector Architecture) for a particular EIS. Resource adapter modules are packaged as JAR files with an .rar (resource adapter archive) extension.


5.3 Packaging Web Archives

In the Java EE architecture(kiến trúc), a web module is the smallest(nhỏ nhất) deployable and usable unit (đơn vị sử dụng) of web resources. A web module contains web components and static(tĩnh) web content files, such as images, which are called web resources. A Java EE web module corresponds(tương ứng) to a web application as defined in the Java Servlet specification (đặc tả).

In addition to web components and web resources, a web module can contain other files (Ngoài các thành phần web và tài nguyên web, một mô-đun web có thể chứa các tệp khác):


  • Server-side utility(tiện ích) classes, such as shopping carts

  • Client-side classes, such as utility classes


A web module has a specific structure (cấu trúc cụ thể). The top-level directory of a web module is the document root of the application. The document root is where XHTML pages, client-side classes and archives, and static web resources, such as images, are stored.

The document root contains a subdirectory named WEB-INF, which can contain the following files and directories:


  • classes, a directory that contains server-side classes: servlets, enterprise bean class files, utility classes, and JavaBeans components
  • lib, a directory that contains JAR files that contain enterprise beans, and JAR archives of libraries called (được gọi) by server-side classes
  • Deployment descriptors, such as web.xml (the web application deployment descriptor) and ejb-jar.xml (an EJB deployment descriptor)
A web module needs a web.xml file if it uses JavaServer Faces technology, if it must specify certain kinds of security information (nếu nó phải xác định một số loại thông tin bảo mật), or if you want to override information specified(được chỉ định) by web component annotations.

You can also create application-specific(cụ thể) subdirectories (that is, package directories) in either the document root or the WEB-INF/classes/ directory.

A web module can be deployed as an unpacked file structure or can be packaged in a JAR file known as a Web Archive (WAR) file. Because the contents and use of WAR files differ(khác nhau) from those of JAR files, WAR file names use a .war extension. The web module just(được) described(mô tả) is portable(bỏ túi); you can deploy it into any web container that conforms(phù hợp) to the Java Servlet specification(đặc điểm kỹ thuật).

You can provide(cung cấp) a runtime deployment descriptor (DD) when you deploy a WAR on GlassFish Server, but it is not required under most circumstances (nó không phải là yêu cầu trong hầu hết các trường hợp). The runtime DD is an XML file that may contain such information as the context(ngữ cảnh) root of the web application, the mapping of the portable names of an application's resources to GlassFish Server resources, and the mapping of an application's security roles to users, groups, and principals(giám đốc) defined(đã định nghĩa) in GlassFish Server. The GlassFish Server web application runtime DD, if used, is named (được đặt tên là) glassfish-web.xml and is located(định vị trí) in the WEB-INF directory. The structure of a web module that can be deployed on GlassFish Server is shown in Figure 5-3

Figure 5-3 Web Module Structure
Description of Figure 5-3 follows
Description of "Figure 5-3 Web Module Structure"




6 Getting Started with Web Applications



This chapter introduces(giới thiệu) web applications, which typically(thường) use JavaServer Faces technology and/or Java Servlet technology. A web application is a dynamic extension(mở) of a web or application server. Web applications are of the following types:

Presentation-oriented(định hướng Trình bày): A presentation-oriented web application generates(tạo ra) interactive(tương tác) web pages containing various types (nhiều loại khác nhau) of markup language (HTML, XHTML, XML, and so on) and dynamic content in response to requests (đáp lại yêu cầu). Development of presentation-oriented web applications is covered in Chapter 7, "JavaServer Faces Technology," through Chapter 17, "Java Servlet Technology."
Service-oriented(Định hướng dịch vụ): A service-oriented web application implements the endpoint(điểm cuối) of a web service. Presentation-oriented applications are often clients (thường là các client) of service-oriented web applications. Development of service-oriented web applications is covered in Chapter 28, "Building Web Services with JAX-WS," and Chapter 29, "Building RESTful Web Services with JAX-RS," in Part VI, "Web Services."

6.1 Web Applications

In the Java EE platform, web components provide the dynamic extension capabilities (khả năng mở rộng) for a web server. Web components can be Java servlets, web pages implemented(đã thực hiện) with JavaServer Faces technology, web service endpoints, or JSP pages. Figure 6-1 illustrates(minh họa) the interaction (sự tương tác) between a web client and a web application that uses a servlet. The client sends an HTTP request to the web server. A web server that implements Java Servlet and JavaServer Pages technology converts the request into an HTTPServletRequest object. This object is delivered(được giao) to a web component, which can interact (có thể tương tác) with JavaBeans components or a database to generate dynamic content. The web component can then generate an HTTPServletResponse or can pass the request to another web component. A web component eventually (cuối cùng) generates a HTTPServletResponse object. The web server converts this object to an HTTP response and returns it to the client.

Figure 6-1 Java Web Application Request Handling










 Description of "Figure 6-1 Java Web Application Request Handling"



    The JavaServer Pages Standard Tag Library (JSTL) encapsulates core functionality common to many JSP applications. Instead of mixing tags from numerous vendors in your JSP applications, you use a single, standard set of tags. This standardization allows you to deploy your applications on any JSP container that supports JSTL and makes it more likely that the implementation of the tags is optimized.

    Servlets are Java programming language classes that dynamically(năng động) process(xử lý) requests and construct(xây dựng) responses. Java technologies, such as JavaServer Faces and Facelets, are used for building(xây dựng) interactive(tương tác) web applications. (Frameworks can also be used for this purpose(mục đích).) Although(Mặc dù) servlets and JavaServer Faces and Facelets pages can be used to accomplish similar things (thực hiện những điều tương tự), each has its own strengths (mỗi cái có điểm mạnh riêng của nó). Servlets are best suited (thích hợp nhất) for service-oriented applications (hướng dịch vụ) (web service endpoints can be implemented as servlets) and the control functions (các chức năng kiểm soát) of a presentation-oriented application (ứng dụng định hương trình bày), such as dispatching(gửi đi) requests and handling(xử lý) nontextual data (dữ liệu không liên quan). JavaServer Faces and Facelets pages are more appropriate (thích hợp) for generating text-based markup (văn bản đánh dấu), such as XHTML, and are generally(thường) used for presentation-oriented applications (ứng dụng định hương trình bày).

    Web components are supported(được hỗ trợ) by the services of a runtime platform called a web container. A web container provides such services as request dispatching (yêu cầu gửi đi), security, concurrency(đồng thời), and lifecycle management (quản lý vòng đời). A web container also gives(cho phép) web components access to such APIs as naming, transactions, and email.

   Certain aspects (một số khía cạnh) of web application behavior(hành vi) can be configured(định cấu hình) when the application is installed, or deployed, to the web container. The configuration information can be specified(quy định) using Java EE annotations or can be maintained(duy trì) in a text file in XML format called a web application deployment descriptor (DD). A web application DD must conform (phải phù hợp) to the schema(giản đồ) described(được mô tả) in the Java Servlet specification(đặc tả).

    This chapter gives(đưa ra) a brief overview (tổng quan ngắn gọn) of the activities involved (các hoạt động liên quan) in developing web applications. First, it summarizes(tóm tắt) the web application lifecycle and explains(giải thích) how to package and deploy very simple web applications on GlassFish Server. The chapter then (chương sau đó) moves on to configuring web applications and discusses (thảo luận) how to specify(chỉnh định) the most commonly used configuration parameters (tham số cấu hình thông dụng nhất).

6.2 Web Application Lifecycle

A web application consists(bao gồm) of web components; static resource files, such as images and cascading style sheets (CSS); and helper classes and libraries. The web container provides(cung cấp) many supporting services that enhance(tăng cường) the capabilities(khả năng) of web components and make them easier to develop. However(tuy nhiên), because a web application must take (phải lấy) these services into account, the process for creating and running a web application is different from (khác với) that of traditional(truyền thông) stand-alone Java classes.

The process for creating, deploying, and executing a web application can be summarized(tóm tắt) as follows:
1. Develop the web component code.
2. Develop the web application deployment descriptor, if necessary.
3. Compile the web application components and helper classes referenced by the components.
4. Optionally, package the application into a deployable unit.
5. Deploy the application into a web container.
6. Access a URL that references the web application.

Developing web component code is covered(bao phủ) in the later(sau) chapters. Steps 2 through 4 are expanded(mở rộng) on in the following sections(các phần sau) and illustrated(minh họa) with a Hello, World–style, presentation-oriented application (ứng dụng trình bày). This application allows a user to enter a name into an HTML form and then displays a greeting(lời chào) after the name is submitted.













Không có nhận xét nào:

Đăng nhận xét