본문 바로가기

WEB_Programming

J2EE Tutorials > Getting Started with Web Applications

Chapter 3 Getting Started with Web Applications

웹 애플리케이션은 웹 혹은 애플리케이션 서버의 동적 확장 버젼이다. 여기에는 2가지 웹 애플리케이션이 있다.

Web Applications

Java 2 플랫폼에서 web components 는 웹 서버를 위해서 동적으로 확장 가능하도록 지원되는 컴포넌트이다. Web components는 Java servlet, JSP page, web service endpoint등을 말한다. 웹 클라이언트와 웹 애플리케이션은 Figure 3–1에서 보는바와 같이 표현된다. 클라이언트는 HTTP 요청을 통해서 서버로 요청을 보낸다. 웹 서버는 Java Servlet과 JavaServer Page 기술을 이용하여 HTTPServletRequest 객체에 대한 요청을 변경하여 처리한다. 이 객체는 웹 컴포넌트로 전달된 것으로, 이것은 JavaBeans컴포넌트 혹은 동적으로 생성된 컨텐츠를 가진 데이터베이스와 상호 통신하게 된다.  웹 컴포넌트는 HTTPServletResponse로 생성할 수 있으며, 혹은 다른 웹 컴포넌트로 전달이 가능하다. 결국에는 웹 컨테이너는 HTTPServletResponse객체를 생성하게 된다. 웹 서버는 이러한 객체를 클라이언트로 반환하도록 변경작업을 수행하게 된다.

Figure 3–1 Java Web Application Request Handling

Diagram of web application request handling. Clients
and web components communicate using HttpServletRequest and HttpServletResponse.

Servlets 은 자바 프로그래밍 언어로 작성된 클래스들로 요청을 처리하고, 응답을 생성하게 된다. JSP pages 는 텍스트 기반의 문서로 서블릿을 수행할 수 있다. 그러나 정적 컨텐츠를 더욱 쉽게 개발 할 수 있도록 지원해준다. 비록 servlet과 JSP 페이지는 서로 변경가능하도록 된 구조이다. 서블릿은 service-oriented 애플리케이션을 만들기에 적합하다. (웹 서비스의 엔드포인트는 서블릿으로 구현되어 있다.) 그리고 presentation-oriented application의 컨트롤 기능을 수행한다. 이것은 요청에 대해서 디스패쳐 작업을 수행하고, 텍스트 형태가 아닌 데이터를 핸들링 하게 된다. JSP 페이지는 HTML과 같이 text-based 로 생성되어야 할 내용에 더욱 적합하게 구성되어 잇으며, Scalable Vector Graphics (SVG),와 Wireless Markup Language(WML), XML등을 다룬다.

Java Servlet과 JSP 기술의 소개에서 추가적으로 Java 기술과 프레임워크들은 Figure 3–2의 구조로 상호 연관되어 잇다.

Figure 3–2 Java Web Application Technologies

Diagram of web application technologies. JavaServer Pages,
the JSP Standard Tag Library, and JavaServer Faces rest on JavaServlet technology.

Java Servlet 기술은 모두 웹 애플리케이션 기술을 기반으로 하고 있다. 그래서 servlet 을 위해 작성된 코드가 아니라도, Chapter 4, Java Servlet Technology에서 잘 알려진 기술들을 이용할 수 있다. 각 기술은 추상화 되어 있는 레벨로서 웹 애플리케이션 프로토타이핑과 더 빠른 개발을 위해서 더욱 관리하기 쉽고, 확장가능하면서, 견고하게 만들 수있도록 해준다.

웹 컴포넌트는 웹 컨테이너라고 불리는 실행 플랫폼의 서비스에 의해서 지원된다. 웹 컨테이너는 요청에 대한 디스패치, 보안, 병행성, 그리고 라이프사이클 관리등의 기능을 지원한다. 또한 웹 컴포넌트가, naming, transactions, email과 같은 API를 통해서 접근 할 수 있도록 지원해준다.

웹 애플리케이션의 행동에 대한 특정 사항은 애플리케이션이 인스톨 될때 혹은 디플로이 된경우에 설정될 수 있도록 할 수 있다. 설정 정보는 XML 형식으로 web application deployment descriptor (DD)라고 불리는 텍스트 파일로 관리된다. DD는 Java Servlet Specification에 기술된 스키마를 이용해야만 한다.

This chapter gives a brief overview of the activities involved in developing web applications. First it summarizes the web application life cycle. Then it describes how to package and deploy very simple web applications on the Application Server. It moves on to configuring web applications and discusses how to specify the most commonly used configuration parameters. It then introduces an example, Duke’s Bookstore, which illustrates all the Java EE web-tier technologies, and describes how to set up the shared components of this example. Finally it discusses how to access databases from web applications and set up the database resources needed to run Duke’s Bookstore.

Web Application Life Cycle

웹 애플리케이션은 웹 컴포넌트, 이미지와 같은 정적 리소스 파일, 그리고 헬퍼 클래스, 라이브러리로 구성된다. 웹 컨테이너는 웹 컴포넌트를 수용할 수 있도록 많은 서비스를 지원해주고 있고, 쉽게 만들 수 있도록 구조화 되어 있다. 그러나 웹 애플리케이션이 이러한 서비스를 이용해야 하는 이유는, 전통적인 stand-alone 자바 클래스와는 다르게, 웹 애플리케이션 상에서 수행되기 때문이다.

    생성을 위한 프로세스, 디플로이, 웹 애플리케이션의 실행의 순서는 다음과 같은 순서로 되어 있다.

  1. 웹 컴포넌트 코드 작성

  2. 웹 애플리케이션 배치 디스크립션 작성

  3. 웹 애플리케이션 컴포넌트의 컴파일과 컴포넌트에 의해서 참조되는 헬퍼 클래스 컴파일

  4. 추가적인 디플로이 가능한 유닛을 패키징 하기

  5. 웹 컨테이너에 디플로이 하기

  6. 웹 애플리케이션 에퍼런스 URL 접근하기

웹 컨텐츠 코드 개발은 차후 챕터에서 다룰 것이다. Step2와 4는 다음 섹션에서 Hello, World-style presentations-oriented 애플리케이션에 묘사되어 있는 내용으로 다음과 같다. 이 애플리케이션은 HTML 폼에서 사용자 이름을 획득하고(Figure 3–3), 전달된 이름을 이용하여 인사하는 부분(Figure 3–4)로 구성된다.

Figure 3–3 Greeting Form

Screen capture of Duke's greeting, "Hello, my name is
Duke. What's yours?" Includes a text field for your name and Submit and Reset
buttons.
Figure 3–4 Response

Screen capture of Duke's response, "Hello, Charlie!"

Hello 애플리케이션은 2개의 웹 컴포넌트를 가지고 있다. 이것은 greeting과 response가 그것이다. 이번 챕터에서는 2개의 애플리케이션 버젼에 대해서 논의할 것이다. JSP 버젼을 hello1이라고 할 것이고, JSP를 이용하여 구현된 것이다. 그리고, 두번째 서블릿 버젼을 작성할 것이다. 2개의 버젼은 패키징, 디플로이, 설정, 그리고 애플리케이션 실행 항목에 다룰 것이다. Chapter 2, Using the Tutorial Examples예제에서는 이러한 예제를 보여준다.

튜토리얼 번들을 인스톨하고 난뒤에 다음 디렉토리 소스에서 그 내용을 확인할 수 있을 것이다.

  • tut-install/javaeetutorial5/examples/web/hello1/

  • tut-install/javaeetutorial5/examples/web/hello2/

Web Modules

Java EE 아키텍쳐에서는 웹 컴포넌트와 이미지와 같은 static 웹 컨텐츠 파일이 있으며, 이것을 web resource라고 부르는 것이 있다. 웹 모듈은 작은 크기로 디플로이 가능한 것을 이야기 하며, 웹 리소스의 유닛을 이용한다. Java EE의 웹 모듈은 Java Servlet 스펙에 정의된 웹 애플리케이션과 대응된다.

추가적으로 웹 컴포넌트와 웹 리소스, 웹 모듈은 두가지 다른 위치에 존재하게 된다.

  • 서버사이드 유틸리트 클래스들(데이터베이스 빈, 쇼핑카드등). 종종 이러한 클래스는 자바빈 콤포넌트 클래스이다.

  • 클라이언트 사이드 클래스들(애플릿, 유틸리티 클래스들)

웹 모듈은 스펙 구조를 가지고 있다. 웹 모듈의 최상위 레벨은 애플리케이션의 document root에 속한다. document root는 JSP 페이지가 존재하며, client-side 클래스들 그리고 아카이프 파일, 그리고 정적 웹 리소스들가 저장된다.

document root 는 하위 디렉토리로 WEB-INF라는 이름의 디렉토리를 가지고 있으며, 여기에는 다음과 같은 파일과 디렉토리가 있다.
  • web.xml: 웹 디플로이 디스크립터 정보가 있다.

  • 태그라이브러리 디스크립터 파일(see Tag Library Descriptors)

  • classes: 서버사이드 클래스들을 포함하는 디렉토리, 서블릿, 유틸 클래스, JavaBeans 컴포넌트

  • tags: 태그 파일을 포함하는 디렉토리, 이것은 태그 라이브러리에 구현된 내용을 가지고 있다. (see Tag File Location)

  • lib: 서버사이드 클래스에 의해서 호출되는 라이브러리로 JAR 아카이브 파일을 포함한다.

모듈이 어떠한 서블릿, 필터, 리스너 컴포넌트를 포함하고 있지 않다면, 웹 애플리케이션 디프로이 디스크립터는 필요가 없다. 다른말로, 웹 모듈이 오직 JSP 페이지나, 정적 파일만을 가지고 잇따면 web.xml에 포함될 필요가 없다는 말이다. hello1 예에서 첫번째로 논의한 Packaging Web Modules에서 확인해 볼수 있으며, 오직 JSP 페이지와 이미지 파일만 존재한다. 그러므로 디플로이 드스크립터가 필요 없게 된다.

만약 application-specific 하위 디렉토리를 document root 혹은 WEB-INF/classes/ 디렉토리에 생성할 수 있다.

웹 모듈은 풀려진 파일로 디플로이 되거나, JAR로 알려진 아카이프 파일(WEB 아카이브 파일 : WAR)로 디플로이 될 수 있다. WAR파일은 jar 파일과 다르기 때문에 WAR파일 확장자 이름을 .war로 만들어서 배포한다. 웹 모듈은 이동성있게 기술된다. 다른 컨테이너에 디플로이를 원한다면 쉽게 할 수 있도록 구성되어 있다.

애플리케이션 서버에 WAR파일로 디플로이 하면, 파일은 runtime deployment descriptor을 포함해야한다. runtime deployment descriptor은 XML 파일이며, context root와 애플리케이션 서버의 리소스의 이름과 매핑을 할 수 있는 정보가 들어가게 된다. Application Server 웹 애플리케이션 DD는 sun-web.xml이며, WEB-INF 디렉토리에 web application DD와 같이 위치하게 된다. 웹 모듈의 구조는 Figure 3–5에서 보여주는 것과 같다.

Figure 3–5 Web Module Structure

Diagram of web module structure. WEB-INF and web pages
are under the root. Under WEB-INF are descriptors and the lib, classes, and
tags directories.

Packaging Web Modules

web 모듈은 특정 상황에서 웹 모듈을 디플로이 하고자 할때, WAR 파일로 반드시 패키징 해야한다. jar 커맨드를 통해서 현재 디렉토리에 놓여진 웹 모듈을 패키징 할 수 있고, 아니면 Ant 유틸리티나 IDE 툴을 이용하여 패키징이 가능하다. 이번 튜토리얼에서는 어떻게 NetBeans IDE를 이용하는지 그리고 Ant 빌드와 패키지, 그리고 샘플 애플리케이션을 디플로이 하는것에 대해서 배울 것이다.

    hello1 애플리케이션을 NetBean IDE를 이용하여 빌드한다. 그리고 다음 명령어를 실행한다.

  1. Select File->Open Project.

  2. Open Projet 다이얼로그에서 다음 위치로 간다.

    tut-install/javaeetutorial5/examples/web/
  3. hello1 폴더를 선택한다.

  4. Main Project 체크 박스를 선택하고 연다.

  5. Open Project를 선택한다.

  6. 프로젝트 탭에서 오른쪽 클릭을 눌러 hello1 프로젝트와 Build를 선택한다.

    To build the hello1 application using the Ant utility, follow these steps:

  1. In a terminal window, go to tut-install/javaeetutorial5/examples/web/hello1/.

  2. Type ant. This command will spawn any necessary compilations, copy files to the tut-install/javaeetutorial5/examples/web/hello1/build/ directory, create the WAR file, and copy it to the tut-install/javaeetutorial5/examples/web/hello1/dist/ directory.

Deploying a WAR File

You can deploy a WAR file to the Application Server in a few ways:

  • Copying the WAR into the domain-dir/autodeploy/ directory.

  • Using the Admin Console.

  • By running asadmin or ant to deploy the WAR.

  • Using NetBeans IDE.

All these methods are described briefly in this chapter; however, throughout the tutorial, you will use ant and NetBeans IDE for packaging and deploying.

Setting the Context Root

A context root identifies a web application in a Java EE server. You specify the context root when you deploy a web module. A context root must start with a forward slash (/) and end with a string.

In a packaged web module for deployment on the Application Server, the context root is stored in sun-web.xml.

    To edit the context root, do the following:

  1. Expand your project tree in the Projects pane of NetBeans IDE.

  2. Expand the Web Pages and WEB-INF nodes of your project.

  3. Double-click sun-web.xml.

  4. In the editor pane, click Edit As XML.

  5. Edit the context root, which is enclosed by the context-root element.

Deploying a Packaged Web Module

If you have deployed the hello1 application, before proceeding with this section, undeploy the application by following one of the procedures described in Undeploying Web Modules.

Deploying with the Admin Console

  1. Expand the Applications node.

  2. Select the Web Applications node.

  3. Click the Deploy button.

  4. Select the radio button labeled “Package file to be uploaded to the Application Server.”

  5. Type the full path to the WAR file (or click on Browse to find it), and then click the OK button.

  6. Click Next.

  7. Type the application name.

  8. Type the context root.

  9. Select the Enabled box.

  10. Click the Finish button.

Deploying with asadmin

To deploy a WAR with asadmin, open a terminal window or command prompt and execute


asadmin deploy full-path-to-war-file

Deploying with Ant

To deploy a WAR with the Ant tool, open a terminal window or command prompt in the directory where you built and packaged the WAR, and execute


ant deploy

Deploying with NetBeans IDE

    To deploy a WAR with NetBeans IDE, do the following:

  1. Select File->Open Project.

  2. In the Open Project dialog, navigate to your project and open it.

  3. In the Projects tab, right-click the project and select Undeploy and Deploy.

Testing Deployed Web Modules

Now that the web module is deployed, you can view it by opening the application in a web browser. By default, the application is deployed to host localhost on port 8080. The context root of the web application is hello1.

    To test the application, follow these steps:

  1. Open a web browser.

  2. Enter the following URL in the web address box:


    http://localhost:8080/hello1
  3. Enter your name, and click Submit.

The application should display the name you submitted as shown in Figure 3–3 and Figure 3–4.

Listing Deployed Web Modules

The Application Server provides two ways to view the deployed web modules: the Admin Console and the asadmin command.

    To use the Admin Console:

  1. Open the URL http://localhost:4848/asadmin in a browser.

  2. Expand the nodes Applications->Web Applications.

Use the asadmin command as follows:


asadmin list-components

Updating Web Modules

    A typical iterative development cycle involves deploying a web module and then making changes to the application components. To update a deployed web module, you must do the following:

  1. Recompile any modified classes.

  2. If you have deployed a packaged web module, update any modified components in the WAR.

  3. Redeploy the module.

  4. Reload the URL in the client.

Updating a Packaged Web Module

This section describes how to update the hello1 web module that you packaged.

First, change the greeting in the file tut-install/javaeetutorial5/examples/web/hello1/web/index.jsp to

<h2>Hi, my name is Duke. What’s yours?</h2>

To update the project in NetBeans IDE:

  • Right-click on the project and select Build.

  • Right-click on the project and select Undeploy and Deploy.

To update the project using the Ant build tool:

  • Type ant to copy the modified JSP page into the build directory.

  • Type ant deploy to deploy the WAR file.

To view the modified module, reload the URL in the browser.

You should see the screen in Figure 3–6 in the browser.

Figure 3–6 New Greeting

Screen capture of Duke's new greeting, "Hi, my name is
Duke. What's yours?" Includes a text field for your name and Submit and Reset
buttons.

Dynamic Reloading

If dynamic reloading is enabled, you do not have to redeploy an application or module when you change its code or deployment descriptors. All you have to do is copy the changed JSP or class files into the deployment directory for the application or module. The deployment directory for a web module named context-root is domain-dir/applications/j2ee-modules/context-root. The server checks for changes periodically and redeploys the application, automatically and dynamically, with the changes.

This capability is useful in a development environment, because it allows code changes to be tested quickly. Dynamic reloading is not recommended for a production environment, however, because it may degrade performance. In addition, whenever a reload is done, the sessions at that time become invalid and the client must restart the session.

    To enable dynamic reloading, use the Admin Console:

  1. Select the Applications Server node.

  2. Select the Advanced tab.

  3. Check the Reload Enabled box to enable dynamic reloading.

  4. Enter a number of seconds in the Reload Poll Interval field to set the interval at which applications and modules are checked for code changes and dynamically reloaded.

  5. Click the Save button.

    In addition, to load new servlet files or reload deployment descriptor changes, you must do the following:

  1. Create an empty file named .reload at the root of the module:


    domain-dir/applications/j2ee-modules/context-root/.reload
  2. Explicitly update the .reload file’s time stamp each time you make these changes. On UNIX, execute


    touch .reload

For JSP pages, changes are reloaded automatically at a frequency set in the Reload Poll Interval field. To disable dynamic reloading of JSP pages, set the Reload Poll Interval field value to –1.

Undeploying Web Modules

You can undeploy web modules in four ways: you can use NetBeans IDE, the Admin Console, the asadmin command, or the Ant tool.

    To use NetBeans IDE:

  1. Ensure the Sun Java System Application Server is running.

  2. In the Runtime window, expand the Sun Java System Application Server instance and the node containing the application or module.

  3. Right-click the application or module and choose Undeploy.

    To use the Admin Console:

  1. Open the URL http://localhost:4848/asadmin in a browser.

  2. Expand the Applications node.

  3. Select Web Applications.

  4. Click the check box next to the module you wish to undeploy.

  5. Click the Undeploy button.

Use the asadmin command as follows:


asadmin undeploy context-root

To use the Ant tool, execute the following command in the directory where you built and packaged the WAR:


ant undeploy

Configuring Web Applications

Web applications are configured by means of elements contained in the web application deployment descriptor.

The following sections give a brief introduction to the web application features you will usually want to configure. A number of security parameters can be specified; these are covered in Chapter 30, Securing Web Applications.

In the following sections, examples demonstrate procedures for configuring the Hello, World application. If Hello, World does not use a specific configuration feature, the section gives references to other examples that illustrate how to specify the deployment descriptor element.

Mapping URLs to Web Components

When a request is received by the web container it must determine which web component should handle the request. It does so by mapping the URL path contained in the request to a web application and a web component. A URL path contains the context root and an alias:


http://host:port/context-root/alias

Setting the Component Alias

The alias identifies the web component that should handle a request. The alias path must start with a forward slash (/) and end with a string or a wildcard expression with an extension (for example, *.jsp). Since web containers automatically map an alias that ends with *.jsp, you do not have to specify an alias for a JSP page unless you wish to refer to the page by a name other than its file name.

    The hello2 application has two servlets that need to be mapped in the web.xml file. You can edit a web application’s web.xml file in NetBeans IDE by doing the following:

  1. Select File->Open Project.

  2. In the Open Project dialog, navigate to:


    tut-install/javaeetutorial5/examples/web/
  3. Select the hello2 folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

  6. Expand the project tree in the Projects pane.

  7. Expand the Web pages node and then the WEB-INF node in the project tree.

  8. Double-click the web.xml file inside the WEB-INF node.

The following steps describe how to make the necessary edits to the web.xml file, including how to set the display name and how to map the servlet components. Because the edits are already in the file, you can just use the steps to view the settings.

    To set the display name:

  1. Click General at the top of the editor to open the general view.

  2. Enter hello2 in the Display Name field.

    To perform the servlet mappings:

  1. Click Servlets at the top of the editor to open the servlets view.

  2. Click Add Servlet.

  3. In the Add Servlet dialog, enter GreetingServlet in the Servlet Name field.

  4. Enter servlets.GreetingServlet in the Servlet Class field.

  5. Enter /greeting in the URL Pattern field.

  6. Click OK.

  7. Repeat the preceding steps, except enter ResponseServlet as the servlet name, servlets.ResponseServlet as the servlet class, and /response as the URL pattern.

If you are not using NetBeans IDE, you can add these settings using a text editor.

    To package the example with NetBeans IDE, do the following:

  1. Select File->Open Project.

  2. In the Open Project dialog, navigate to:


    tut-install/javaeetutorial5/examples/web/
  3. Select the hello2 folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

  6. In the Projects tab, right-click the hello2 project and select Build.

    To package the example with the Ant utility, do the following:

  1. In a terminal window, go to tut-install/javaeetutorial5/examples/web/hello2/.

  2. Type ant. This target will build the WAR file and copy it to the tut-install/javaeetutorial5/examples/web/hello2/dist/ directory.

To deploy the example using NetBeans IDE, right-click on the project in the Projects pane and select Undeploy and Deploy.

To deploy the example using Ant, type ant deploy. The deploy target in this case gives you an incorrect URL to run the application. To run the application, please use the URL shown at the end of this section.

To run the application, first deploy the web module, and then open the URL http://localhost:8080/hello2/greeting in a browser.

Declaring Welcome Files

The welcome files mechanism allows you to specify a list of files that the web container will use for appending to a request for a URL (called a valid partial request) that is not mapped to a web component.

For example, suppose you define a welcome file welcome.html. When a client requests a URL such as host:port/webapp/directory, where directory is not mapped to a servlet or JSP page, the file host:port/webapp/directory/welcome.html is returned to the client.

If a web container receives a valid partial request, the web container examines the welcome file list and appends to the partial request each welcome file in the order specified and checks whether a static resource or servlet in the WAR is mapped to that request URL. The web container then sends the request to the first resource in the WAR that matches.

If no welcome file is specified, the Application Server will use a file named index.XXX, where XXX can be html or jsp, as the default welcome file. If there is no welcome file and no file named index.XXX, the Application Server returns a directory listing.

    To specify a welcome file in the web application deployment descriptor using NetBeans IDE, do the following:

  1. Open the project if you haven’t already.

  2. Expand the project’s node in the Projects pane.

  3. Expand the Web Pages node and then the WEB-INF node.

  4. Double-click web.xml.

  5. Do one of the following, making sure that the JSP pages you specify are actually included in the WAR file:

    1. Click Pages at the top of the editor pane and enter the names of the JSP pages that act as welcome files in the Welcome Files field.

    2. Click XML at the top of the editor pane, specify the JSP pages using welcome-file elements and include these elements inside a welcome-file-list element. The welcome-file element defines the JSP page to be used as the welcome page.

      The example discussed in Encapsulating Reusable Content Using Tag Files has a welcome file.

Setting Initialization Parameters

The web components in a web module share an object that represents their application context (see Accessing the Web Context). You can pass initialization parameters to the context or to a web component.

    To add a context parameter using NetBeans IDE, do the following:

  1. Open the project if you haven’t already.

  2. Expand the project’s node in the Projects pane.

  3. Expand the Web Pages node and then the WEB-INF node.

  4. Double-click web.xml.

  5. Click General at the top of the editor pane.

  6. Select the Context Parameters node.

  7. Click Add.

  8. In the Add Context Parameter dialog, do the following:

    1. Enter the name that specifies the context object in the Param Name field.

    2. Enter the parameter to pass to the context object in the Param Value field.

    3. Click OK.

Alternatively, you can edit the XML of the web.xml file directly by clicking XML at the top of the editor pane and using the following elements to add a context parameter:

  • A param-name element that specifies the context object

  • A param-value element that specifies the parameter to pass to the context object

  • A context-param element that encloses the previous two elements

For a sample context parameter, see the example discussed in The Example JSP Pages.

    To add a web component initialization parameter using NetBeans IDE, do the following:

  1. Open the project if you haven’t already.

  2. Expand the project’s node in the Projects pane.

  3. Expand the Web Pages node and then the WEB-INF node.

  4. Double-click web.xml.

  5. Click Servlets at the top of the editor pane.

  6. After entering the servlet’s name, class, and URL pattern, click the Add button under the Initialization Parameters table.

  7. In the Add Initialization Parameter dialog:

    1. Enter the name of the parameter in the Param Name field.

    2. Enter the parameter’s value in the Param Value Field.

    3. Click OK.

Alternatively, you can edit the XML of the web.xml file directly by clicking XML at the top of the editor pane and using the following elements to add a context parameter:

  • A param-name element that specifies the name of the initialization parameter

  • A param-value element that specifies the value of the initialization parameter

  • An init-param element that encloses the previous two elements

Mapping Errors to Error Screens

When an error occurs during execution of a web application, you can have the application display a specific error screen according to the type of error. In particular, you can specify a mapping between the status code returned in an HTTP response or a Java programming language exception returned by any web component (see Handling Servlet Errors) and any type of error screen.

    To set up error mappings using NetBeans IDE, do the following:

  1. Open the project if you haven’t already.

  2. Expand the project’s node in the Projects pane.

  3. Expand the Web Pages node and then the WEB-INF node.

  4. Double-click web.xml.

  5. Click Pages at the top of the editor pane.

  6. Expand the Error Pages node.

  7. Click Add.

  8. In the Add Error Page dialog:

    1. Click Browse to locate the page that you want to act as the error page.

    2. Enter the HTTP status code that will cause the error page to be opened in the Error Code field.

    3. Enter the exception that will cause the error page to load in the Exception Type field.

    4. Click OK.

Alternatively, you can click XML at the top of the editor pane and enter the error page mapping by hand using the following elements:

  • An exception-type element specifying either the exception or the HTTP status code that will cause the error page to be opened.

  • A location element that specifies the name of a web resource to be invoked when the status code or exception is returned. The name should have a leading forward slash (/).

  • An error-page element that encloses the previous two elements.

You can have multiple error-page elements in your deployment descriptor. Each one of the elements identifies a different error that causes an error page to open. This error page can be the same for any number of error-page elements.


Note –

You can also define error screens for a JSP page contained in a WAR. If error screens are defined for both the WAR and a JSP page, the JSP page’s error page takes precedence. See Handling JSP Page Errors.


For a sample error page mapping, see the example discussed in The Example Servlets.

Declaring Resource References

If your web component uses objects such as enterprise beans, data sources, or web services, you use Java EE annotations to inject these resources into your application. Annotations eliminate a lot of the boilerplate lookup code and configuration elements that previous versions of Java EE required.

Although resource injection using annotations can be more convenient for the developer, there are some restrictions from using it in web applications. First, you can only inject resources into container-managed objects. This is because a container must have control over the creation of a component so that it can perform the injection into a component. As a result, you cannot inject resources into objects such as simple JavaBeans components. However, JavaServer Faces managed beans are managed by the container; therefore, they can accept resource injections.

Additionally, JSP pages cannot accept resource injections. This is because the information represented by annotations must be available at deployment time, but the JSP page is compiled after that; therefore, the annotation will not be seen when it is needed. Those components that can accept resource injections are listed in Table 3–1.

This section describes how to use a couple of the annotations supported by a servlet container to inject resources. Chapter 25, Persistence in the Web Tier describes how web applications use annotations supported by the Java Persistence API. Chapter 30, Securing Web Applications describes how to use annotations to specify information about securing web applications.

Table 3–1 Web Components That Accept Resource Injections

Component

Interface/Class

Servlets

javax.servlet.Servlet

Servlet Filters

javax.servlet.ServletFilter

Event Listeners

javax.servlet.ServletContextListener

javax.servlet.ServletContextAttributeListener

javax.servlet.ServletRequestListener

javax.servlet.ServletRequestAttributeListener

javax.servlet.http.HttpSessionListener

javax.servlet.http.HttpSessionAttributeListener

javax.servlet.http.HttpSessionBindingListener

Taglib Listeners

Same as above

Taglib Tag Handlers

javax.servlet.jsp.tagext.JspTag

Managed Beans

Plain Old Java Objects

Declaring a Reference to a Resource

The @Resource annotation is used to declare a reference to a resource such as a data source, an enterprise bean, or an environment entry. This annotation is equivalent to declaring a resource-ref element in the deployment descriptor.

The @Resource annotation is specified on a class, method or field. The container is responsible for injecting references to resources declared by the @Resource annotation and mapping it to the proper JNDI resources. In the following example, the @Resource annotation is used to inject a data source into a component that needs to make a connection to the data source, as is done when using JDBC technology to access a relational database:

@Resource javax.sql.DataSource catalogDS;

public getProductsByCategory() {

// get a connection and execute the query

Connection conn = catalogDS.getConnection();

..

}

The container injects this data source prior to the component being made available to the application. The data source JNDI mapping is inferred from the field name catalogDS and the type, javax.sql.DataSource.

If you have multiple resources that you need to inject into one component, you need to use the @Resources annotation to contain them, as shown by the following example:

@Resources ({

@Resource (name="myDB" type=java.sql.DataSource),

@Resource(name="myMQ" type=javax.jms.ConnectionFactory)

})

The web application examples in this tutorial use the Java Persistence API to access relational databases. This API does not require you to explicitly create a connection to a data source. Therefore, the examples do not use the @Resource annotation to inject a data source. However, this API supports the @PersistenceUnit and @PersistenceContext annotations for injecting EntityManagerFactory and EntityManager instances, respectively. Chapter 25, Persistence in the Web Tier describes these annotations and the use of the Java Persistence API in web applications.

Declaring a Reference to a Web Service

The @WebServiceRef annotation provides a reference to a web service. The following example shows uses the @WebServiceRef annotation to declare a reference to a web service. WebServiceRef uses the wsdlLocation element to specify the URI of the deployed service’s WSDL file:

...

import javax.xml.ws.WebServiceRef;

...

public class ResponseServlet extends HTTPServlet {

@WebServiceRef(wsdlLocation=

"http://localhost:8080/helloservice/hello?wsdl")

static HelloService service;

Duke’s Bookstore Examples

In Chapters Chapter 4, Java Servlet Technology through Chapter 15, Internationalizing and Localizing Web Applications a common example, Duke’s Bookstore, is used to illustrate the elements of Java Servlet technology, JavaServer Pages technology, the JSP Standard Tag Library, and JavaServer Faces technology. The example emulates a simple online shopping application. It provides a book catalog from which users can select books and add them to a shopping cart. Users can view and modify the shopping cart. When users are finished shopping, they can purchase the books in the cart.

The Duke’s Bookstore examples share common classes and a database schema. These files are located in the directory tut-install/javaeetutorial5/examples/web/bookstore/. The common classes are packaged into a JAR. Each of the Duke’s Bookstore examples must include this JAR file in their WAR files. The process that builds and packages each application also builds and packages the common JAR file and includes it in the example WAR file.

The next section describes how to create the bookstore database tables and resources required to run the examples.

Accessing Databases from Web Applications

Data that is shared between web components and is persistent between invocations of a web application is usually maintained in a database. To maintain a catalog of books, the Duke’s Bookstore examples described in Chapters Chapter 4, Java Servlet Technology through Chapter 15, Internationalizing and Localizing Web Applications use the Java DB database included with the Application Server.

To access the data in a database, web applications use the new Java Persistence API (see Chapter 24, Introduction to the Java Persistence API). See Chapter 25, Persistence in the Web Tier to learn how the Duke’s Bookstore applications use this API to access the book data.

To run the Duke’s Bookstore applications, you need to first populate the database with the book data and create a data source in the application server. The rest of this section explains how to perform these tasks.

Populating the Example Database

    When you deploy any of the Duke’s Bookstore applications using ant deploy, the database is automatically populated at the same time. If you want to populate the database separately from the deploy task or are using NetBeans IDE to deploy the application, follow these steps:

  1. In a terminal window, go to the books directory or any one of the bookstore1 through bookstore6 example directories.

  2. Start the Java DB database server. For instructions, see Starting and Stopping the Java DB Database Server. You don’t have to do this if you are using NetBeans IDE. It starts the database server automatically.

  3. Type ant create-tables. This task runs a command to read the file tutorial.sql and execute the SQL commands contained in the file.

  4. At the end of the processing, you should see the following output:


    ...

    [sql] 181 of 181 SQL statements executed successfully

When you are running create-tables, don’t worry if you see a message that an SQL statement failed. This usually happens the first time you run the command because it always tries to delete an existing database table first before it creates a new one. The first time through, there is no table yet, of course.

Creating a Data Source in the Application Server

A DataSource object has a set of properties that identify and describe the real world data source that it represents. These properties include information such 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.

Data sources in the Application Server implement connection pooling. To define the Duke’s Bookstore data source, you use the installed Derby connection pool named DerbyPool.

    You create the data source using the Application Server Admin Console, following this procedure:

  1. Expand the Resources node.

  2. Expand the JDBC node.

  3. Select the JDBC Resources node.

  4. Click the New... button.

  5. Type jdbc/BookDB in the JNDI Name field.

  6. Choose DerbyPool for the Pool Name.

  7. Click OK.

Further Information about Web Applications

For more information on web applications, see: