1. JScape, iNet Factory: com.jscape.inet.ftp.Ftp
  2. /n software, IP*Works: ipworks.Ftp
  3. Enterprise Distributed Technologies, Java FTP Client Library: com.enterprisedt.net.ftp.FTPClient
  4. IBM alphaWorks, FTP Bean Suite: com.ibm.network.ftp.protocol.FTPProtocol
  5. SourceForge, JFtp: net.sf.jftp.net.FtpConnection
  6. The Jakarta Project, Jakarta Commons/Net: org.apache.commons.net.ftp.FTPClient
  7. JavaShop JNetBeans: jshop.jnet.FTPClient
  8. Sun, JDK: sun.net.ftp.FtpClient
  9. Florent Cueto, JavaFTP API: com.cqs.ftp.FTP
  10. Bea Petrovicova, jFTP: cz.dhl.ftp.Ftp
  11. The Globus Project, Java CoG Kit: org.globus.io.ftp.FTPClient

 

출처

 

Java FTP client libraries reviewed

Learn how the available libraries stack up against each other

http://www.javaworld.com/javaworld/jw-04-2003/jw-0404-ftp.html

'java core' 카테고리의 다른 글

[펌] 로드 존슨의 J2EE Development Without EJB 정리 컬럼  (0) 2005.10.28
자바 파서. java parser  (0) 2005.10.20
이벤트 모델  (0) 2005.09.16
[펌] JVM 관련  (0) 2005.09.15
[TIP]자바 실행, 컴파일때 shell 이용법  (0) 2005.06.11
Posted by '김용환'
,

에디터 폰트 설정방법

 

from okjsp.

Posted by '김용환'
,

이클립스에서 탭을 공백으로 처리하기

 

 - 메뉴 Window > Preferences

 - Java > Editor > Typing 에서 Insert space for taps 체크할 것

 - Java > Code Formatter > Style 에서 Insert tabs for indentation, not spaces 언체크할 것

 

위와같이 설정하면 탭키를 평소처럼 사용할 수 있으며,

탭키 대신 공백이 들어갑니다.

 

이클립스 소스창에서 탭을 공백으로 넣어주는게 좋습니다.

이유는 다른 에디터로 열어보았을때 깨짐현상이 없습니다.

특히 리눅스 vi로 열어보아도 깨지지 않습니다.

적극 권장합니다.

참고로 소스의 탭 크기는 4를 권장합니다.(2 안됨!!!)

 

Posted by '김용환'
,

이벤트 모델

java core 2005. 9. 16. 02:13

Michael Elhadad

Software Engineering - Fall 1999


Lecture 10: Event Models

Motivation

  • Generic notions and patterns around event, notification, listener, adapter.
  • CORBA Event Services: Event Channels, push, pull and hybrid modes
  • Introduction to Java's Event Model
  • Events, Listeners and Adapters
  • Types of adapters: demultiplexing, wrappers, distributed, queuing, filtering.

References

Read The Java Event Model from the Sun Java Tutorial.

More on Java events in SWING.

Read Schmidt's columns on Corba's event system (the examples are translated in Java in the previous lecture notes):

  1. Distributed Callbacks and Decoupled Communication in CORBA, SIGS, Vol 8. No 9. October 1996.

    This column examines distributed callbacks in CORBA and illustrates why they are useful for decoupling relationships between consumers and suppliers in object-oriented communication applications. The source code examples are based on the HP ORB Plus CORBA implementation.

  2. OMG Event Object Service, SIGS, Vol. 9, No 2. February, 1997.

    This column outlines the roles of the key components in the OMG Events Service, examines the IDL interfaces of the Events Service components in detail, shows how to use it to build a flexible implementation of the distributed stock quoter system, and evaluates the strengths and weaknesses of the OMG Event Services model and its specification.

  3. Overcoming Drawbacks with the OMG Events Service,, SIGS, Vol. 9, No 6. June, 1997. (updated April 7th, 1997)

    This column describes techniques for overcoming drawbacks with the OMG Events Service. These techniques range from changing the COS Events Service specification, to changing implementations of the COS Events Service specification, as well as changing applications that use a COS Events Service implementation.

Events

Events are objects or messages used when a software components wants to notify a state change to other components.

An Event model is a software architecture (a set of classes and interfaces) that determine how components can:

  1. On the event source side:
    1. create and describe events
    2. trigger (or fire) events
    3. distribute events to interested components
  2. On the event listener side:
    1. subscribe to event sources
    2. react to events when received
    3. remove the subscription to event sources when desired
Terminology often used refers to:
  1. Event Source or Provider: the sender of events
  2. Event: the object sent
  3. Event Listener or Event Sink or Consumer: the receiver of events.

Properties of Event Services

The most important properties:
  1. Synchronous vs. asynchronous events: does the consumer react immediately to the event? does the producer wait for the consumer to finish reacting?
  2. Connection topology: can producers and consumers be connected in complex topologies (fan-in, fan-out)? does the service require a centralized event registration mechanism or can it be distributed?
  3. Push vs. Pull: do producers inform consumers (push) or reversely do consumers ask producers for events (pull)? Can hybrid models be supported?
  4. Distributed vs. single process events
  5. Quality of Service (QoS): does the service insure that the channel between producer and consumer can reserve bandwidth to allow time-critical events to reach consumers whenever needed?
  6. Directed vs. undirected events: it is desirable that the producer can trigger events without knowing the identity of the consumers and vice-versa, that consumers can subscribe to event sources without knowing the identity of the potential producers.
  7. Typed vs. untyped events: with untyped events, consumers can listen to any type of events. This adds to flexibility but costs in security (no compile-time check).
  8. Persistent: what happens if the event channel process exits? It should keep the event queues in a persistent store and restore them upon restart. Also, if an event channel or a source is used, whenever it is shut down, it should keep the list of registered listeners to restore it upon restart.
  9. Security: does anyone check if consumers are authorized to subscribe to an event notification service?
  10. Filtering: who is in charge of filtering events, consumer or producer? How difficult is it to define filtering constraints?
The conclusion is that the definition of an event model can be difficult, and must be adapted by analyzing the trade-offs of each application.

The Java Event Model: Part 1

Java defines the following basis to help define new event types:
  1. class EventObject: is serializable and remembers the Source object.
  2. interface EventListener: is used only to tag interfaces that extend it so that run-time type information can recognize them.
When defining a new event, the following conventions are followed:
  1. A new class extending EventObject is defined. It is named using the pattern xxxEvent.
  2. A new interface extending EventListener is defined. It is named using the pattern xxxListener
  3. The interface xxxListener defines functions to react to the xxxEvent family. They are named using the pattern onxxx(xxxEvent).
  4. The producer of the xxxEvent implements 3 methods:
    1. void addxxxListener(xxxListener l): adds l to the list of interested listeners.
    2. void removexxxListener(xxxListener l): removes l from the list.
    3. void notifyxxx(): creates an xxxEvent and sends it to all interested listeners.
  5. The consumers of the event define an instance of a class that implements the xxxListener interface and register this class with an xxxEvent producer using the addxxxListener() method.
  6. The producer fires events by calling notifyxxx().
This is the simplest application of the model. It is:
  1. synchronous
  2. simple direct topology (direct link producer/consumer)
  3. push
  4. non distributed (except if the onxxx() method is a remote invocation, but this is not desirable because this is a synchronous model and the remote invocation would block the event notification loop).
  5. No handling of quality of service: there is no priority among listeners - they are simply added to the list of listeners, which could grow. The time it takes to notify a listener is therefore unbounded.
  6. Directed (consumers and producers know about each other)
  7. Typed (the xxxEvent type is used)
  8. The addxxxListener is in charge of checking security
  9. Filtering is performed by the producer in the notifyxxx() method or by the consumer in the onxxx() method. There is no "declarative" setting of event filtering.

The Java Event Model: Example 1

The following code illustrates how to implement the simplest application of the Java event model:
// Define a new event
public class StockPriceChangeEvent extends EventObject {
  private long newPrice;
  public StockPriceChangeEvent(Object source, long np) {
    super(source);
    newPrice = np;
  }
  public long getNewPrice() {
    return newPrice;
  }
  // Type-safe access to source
  public Stock getStock() {
    return (Stock)getSource();
  }
}

// Define new listener interface
public interface StockListener extends EventListener {
  public abstract void onStockPriceChange(StockPriceChangeEvent e);
}

// Define a source for the event
public class Stock {
  private long currentPrice;
  private Vector stockListeners = new Vector();
  private String name;

  public Stock(String n) {name = n;}

  public setPrice(long np) {
    currentprice = np;
    notifyStockPriceChange();
  }

  public synchronized void addStockListener(StockListener l) {
    stockListeners.addElement(l);
  }

  public synchronized void removeStockListener(StockListener l) {
    stockListeners.removeElement(l);
  }

  protected void notifyStockPriceChange() {
    StockPriceChangeEvent e = new StockPriceChangeEvent(this, currentPrice);
    for (int i = 0; i < stockListeners.size(); i++ ) {
      StockListener l = (StockListener)stockListeners.elementAt(i);
      l.onStockPriceChange(e);
    }
  }
}

// Define a listener for the event
public class Trader implements StockListener {
  public Trader() {
    ibm = new Stock("ibm");
    ibm.addStockListener(this);
  }

  ...
	
  public onStockPriceChange(StockPriceChangeEvent e) {
    if (e.getNewPrice() > 103) {
      Buy(e.getStock());
    }
  }
}


As shown in the code, event sources must deal with the issue of registration of listeners and distribution of events when they work in push mode. Java provides classes to support this aspect of the problem.

Event Adapters

Adapters are intermediary objects -- objects that come between event sources and their targets. Adapters allow the decoupling of sources and targets. This is desirable in several scenarios:
  1. Demultiplexing adapters: the same adapter can receive events from several sources and trigger a single event on the targets.
  2. Generic adapters: are useful to allow wiring of sources and targets that are not type compatible. The adapter maintains a map to make events of different types correspond to each other.
  3. Distributed adapters: take care of the remote interfaces to send events to remote targets. For example, a CORBA event-adapter allows an event source to connect to targets on any machine related through the ORB.
  4. Queuing adapters: When using a synchronous event-model, a queuing adapter is important to decouple the posting of an event with the execution of the callback on the targets. The queuing adapter just records the event and the source can keep working. The targets can handle the event when they have time.
  5. Filtering adapters: apply rules to determine which targets should be informed, and which should not be informed of each type of event.
The following Swing example illustrates a good usage of event adapters and the technique of using inner classes as event adapters.
Last modified June 13th, 1999 Michael Elhadad

'java core' 카테고리의 다른 글

자바 파서. java parser  (0) 2005.10.20
자바 ftp client 라이브러리.  (0) 2005.10.13
[펌] JVM 관련  (0) 2005.09.15
[TIP]자바 실행, 컴파일때 shell 이용법  (0) 2005.06.11
Runtime  (0) 2005.06.06
Posted by '김용환'
,

[펌] JVM 관련

java core 2005. 9. 15. 20:17

'java core' 카테고리의 다른 글

자바 ftp client 라이브러리.  (0) 2005.10.13
이벤트 모델  (0) 2005.09.16
[TIP]자바 실행, 컴파일때 shell 이용법  (0) 2005.06.11
Runtime  (0) 2005.06.06
millisecond를 가지고 구하기  (0) 2005.05.13
Posted by '김용환'
,
-------------------------------------------------------------------------

작성자: 김인태 (http://blog.naver.com/inking007)

제목: Axis WebService 설치및 테스트

참고 : http://www.javaworld.com/javaworld/jw-04-2003/jw-0411-axis_p.html

-------------------------------------------------------------------------

 

Axis 설치

 

1) Apache Tomcat 설치

   버전 4.1  이상 Full 버전으로 설치해야만 한다.

 

2) JDK 설치

   버전 1.3 이상으로 설치 해야만 한다.

 

3) Axis 다운로드 후 CLASSPATH를 설정한다.

 

c:\axis에 설치했다고 가정하면 다음과 같이 설정해 준다.

set AXIS_HOME=c:\axis
set AXIS_LIB=%AXIS_HOME%\lib
set AXISCLASSPATH=%AXIS_LIB%\axis.jar;%AXIS_LIB%\commons-discovery.jar;
    %AXIS_LIB%\commons-logging.jar;%AXIS_LIB%\jaxrpc.jar;%AXIS_LIB%\saaj.jar;
    %AXIS_LIB%\log4j-1.2.8.jar;%AXIS_LIB%\xml-apis.jar;%AXIS_LIB%\xercesImpl.jar;%AXIS_LIB%\wsdl4j.jar

set CLASSPATH=%CLASSPATH%;%AXISCLASSPATH%

 

CLASSPATH에 있는 xml-apis.jar 파일과 xercesImpl.jar 파일은 http://xml.apache.org/xerces2-j/ 에 접속해서 다운로드 받으면 된다.

 

4) c\axis\webapps\axis 디렉토리를 tomcat의 webapps에 복사한다.

 

5) 톰켓 실행

 

6) 테스트

 

> 연결 테스트

http://localhost:8080/axis

 

> 라이브러리 테스트

http;//localhost:8080/axis/happyaxis.jsp

 

> SOAP 테스트

http://localhost:8080/axis/services/Version?method=getVersion

다음과 같이 출력되어야 한다. (build date와 version등은 다를수 있다.)

  <?xml version="1.0" encoding="UTF-8" ?>
  <soapenv:Envelope
   xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Body>
   <getVersionResponse
    soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
    <getVersionReturn
     xsi:type="xsd:string">
     Apache Axis version: 1.1 Built on Apr 04, 2003 (01:30:37 PST)
    </getVersionReturn>
   </getVersionResponse>
   </soapenv:Body>
  </soapenv:Envelope>

 

> AdminClient 테스트

cd c:\axis\stock 

java -cp %AXISCLASSPATH% org.apache.axis.client.AdminClient -lhttp://localhost:8080/axis/services/AdminService deploy.wsdd

ClassNotFoundException 오류가 발생한경우 CLASSPATH를 확인해 볼것

 

deploy가 성공했는지 확인한다.

http://localhost:8080/axis/servlet/AxisServlet

다음과 같이 웹서비스가 설치되었는지 확인해 본다.

  urn:xmltoday-delayed-quotes (wsdl) 
        test 
        getQuote

 

> 클라이언트 수행 테스트

java -cp .;%AXISCLASSPATH% samples.stock.GetQuote -lhttp://localhost:8080/axis/servlet/AxisServlet  -uuser1 -wpass1 XXX

 

실행결과가 55.25가 출력된 경우.. 성공!!

 

 

웹서비스를 알려면 SOAP, WSDL, WSDD 대해서 꼭 알아야 한다.

 

자세한 내용은 추후에 설명하도록 한다.

 

SOAP (Simple Object Access Protocol)

WSDL (Web Service Description Langauge)

WSDD (Web Service Deployment Descriptor)

 

프로그램을 작성하는 순서

 

1. 서버 Interface와 구현 Class를 작성한후 컴파일 한다.

 

2. 구현 클래스로 부터 WSDL 파일을 생성한다.

 

3. WSDL 파일로 부터 deploy.wsdd 파일을 생성한다.

 

4. deploy.wsdd 파일을 이용해서 웹서비스를 deploy하고 server-config.wsdd 파일을 생성 수정한다.

 

5. 구현클래스로 부터 client-side 클래스를 생성한다.

 

 

프로그램 작성 플로우

 

 

   

 

1) 자바 Interface와 자바 Implement 클래스 작성

//begin - HelloIF.java

package webservice.hello;

public interface HelloIF extends java.rmi.Remote {
    public String hello(java.lang.String name) throws java.rmi.RemoteException;
}
//end - HelloIF.java

 

//begin - HelloImpl.java

package webservice.hello;

public class HelloImpl implements HelloIF {
    public HelloImpl() {
    }

    public String hello(String name) {
        System.out.println(name);
        return "hi " + name;
    }
}

//end - HelloImpl.java

 

컴파일

javac -d . HelloImpl.java

컴파일 후 webservice/hello 디렉토리밑에 HelloImpl.class 와 HelloIF.class가 생성되었는지 확인한다.

 

생성된 class파일을 C:\lecture\Tomcat 4.1\webapps\axis\WEB-INF\classes 디렉토리에 패키지 디렉토리를 포함해서 복사한다.

 

2) 구현 클래스로부터 WSDL 작성

java org.apache.axis.wsdl.Java2WSDL -o c:\javaprogram\webservice\hello\Hello.wsdl -l http://localhost:8080/axis/services/Hello -n http://hello.webservice -pwebservice.hello http://hello.webservice webservice.hello.HelloIF

 

Java2WSDL 인자 (http://ws.apache.org/axis/java/reference.html)

인자

의미

-o 파일경로

wsdl 생성 위치

-l URL

client가 접속할 URL

-n  네임스페이스

WSDL의 타켓 네임스페이스

-p패키지 네임스페이스

네임스페이스와 네임스페이스 매핑

Target

인터페이스 이름

 

 

생성된 wsdl 파일

 

 

<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions targetNamespace="
http://hello.webservice" xmlns:impl="http://hello.webservice" xmlns:intf="http://hello.webservice" xmlns:apachesoap="http://xml.apache.org/xml-soap" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
<!--WSDL created by Apache Axis version: 1.2alpha
Built on Dec 01, 2003 (04:33:24 EST)-->

   <wsdl:message name="helloResponse">

      <wsdl:part name="helloReturn" type="xsd:string"/>

   </wsdl:message>

   <wsdl:message name="helloRequest">

      <wsdl:part name="in0" type="xsd:string"/>

   </wsdl:message>

   <wsdl:portType name="HelloIF">

      <wsdl:operation name="hello" parameterOrder="in0">

         <wsdl:input name="helloRequest" message="impl:helloRequest"/>

         <wsdl:output name="helloResponse" message="impl:helloResponse"/>

      </wsdl:operation>

   </wsdl:portType>

   <wsdl:binding name="HelloSoapBinding" type="impl:HelloIF">

      <wsdlsoap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>

      <wsdl:operation name="hello">

         <wsdlsoap:operation soapAction=""/>

         <wsdl:input name="helloRequest">

            <wsdlsoap:body use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://hello.webservice"/>

         </wsdl:input>

         <wsdl:output name="helloResponse">

            <wsdlsoap:body use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://hello.webservice"/>

         </wsdl:output>

      </wsdl:operation>

   </wsdl:binding>

   <wsdl:service name="HelloIFService">

      <wsdl:port name="Hello" binding="impl:HelloSoapBinding">

         <wsdlsoap:address location="http://localhost:8080/axis/services/Hello"/>

      </wsdl:port>

   </wsdl:service>

</wsdl:definitions>

 

 

 

3), 4)  WSDL 파일로 부터 deploy.wsdd 파일 생성 및 client-side 자바 클래스 생성

 

java org.apache.axis.wsdl.WSDL2Java -o c:\javaprogram\webservice\hello\ -d Application -s c:\javaprogram\webservice\hello\Hello.wsdl

 

c:\javaprogram\webservice\hello 디렉토리 하위에 webservice/hello 새로운 디렉토리가 생성된것을 확인 할수 있다.

그 디렉토리에 deploy.wsdd 파일과 새롭게 생성된 자바 파일이 존재해야 한다.

 

WSDL2Java 인자

인자

의미

-o 디렉토리경로

wsdd 파일과 클래스파일이 생길 디렉토리

-d  scope

설치 영역 Application, Request , Session

-s

wsdd 파일 생성

Target

wsdl 파일 경로

 

deploy.wsdd 파일 수정

 

wsdd 파일은 wsdl 파일만 가지고 생성되었기 때문에 실제 구현클래스가 무엇인지 제대로 설정이 안되어 있으므로 그부분을 수정해 주어야한다.

 

 

<deployment

    xmlns="http://xml.apache.org/axis/wsdd/"

    xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">

 

  <!-- Services from HelloIFService WSDL service -->

 

  <service name="Hello" provider="java:RPC" style="rpc" use="encoded">

      <parameter name="wsdlTargetNamespace" value="http://hello.webservice"/>

      <parameter name="wsdlServiceElement" value="HelloIFService"/>

      <parameter name="wsdlServicePort" value="Hello"/>

      <parameter name="className" value="webservice.hello.HelloImpl"/>

      <parameter name="wsdlPortType" value="HelloIF"/>

      <operation name="hello" qname="operNS:hello" xmlns:operNS="http://hello.webservice" returnQName="helloReturn" returnType="rtns:string" xmlns:rtns="http://www.w3.org/2001/XMLSchema" >

        <parameter name="in0" type="tns:string" xmlns:tns="http://www.w3.org/2001/XMLSchema"/>

      </operation>

      <parameter name="allowedMethods" value="hello"/>

      <parameter name="scope" value="Application"/>

 

  </service>

</deployment>

 

 

서비스 디플로이먼트

java org.apache.axis.client.AdminClient -lhttp://localhost:8080/axis/services/AdminService deploy.wsdd

 

디플로이먼트 확인하기

http://localhost:8080/axis/servlet/AxisServlet

'Hello' 라는 서비스가 설치된것을 확인할 수 있다.

 

서비스 테스트하기

 

'web' 카테고리의 다른 글

Trust in E-commerce  (0) 2006.07.20
FTP의 passive, active mode 설명  (0) 2006.02.20
[펌] web.xml 사용법  (0) 2005.07.23
Tomcat 4.1.12 버전에서 서블릿 접근  (0) 2005.02.08
web.xml 설명.  (0) 2005.02.04
Posted by '김용환'
,

이클립스의 버젼이 올라가서, 새로운 환경설정대신 과거 버젼의 환경설정으로 바꾸고 싶다면,

과거버젼의 configuration 디렉토리의 파일을 새로운 버젼의 configuration 디렉토리로 복사한다.

 

프로젝트만 복사하고 싶을 경우

 C:\이클립스\configuration\.settings의
org.eclipse.ui.prefs
org.eclipse.ui.ide.prefs
파일을 복사한다. 그러면, 예전의 프로젝트 형태 그대로 사용이 가능하다.

 

그리고, 이클립스 자체가 vm이라서 처음 로딩속도가 느리다면,

eclipse.ini 파일에서
에서 minimum vm size를 64메가이상으로 수정을 하면 속도가 빨라진다.

256메가까지 올리면 최초 로딩속도는 빠르겠지만, 시간이 지나면 메모리 릭이 생겨서, 다시 부팅해야할지 모른다.

 

 

Posted by '김용환'
,

[펌] web.xml 사용법

web 2005. 7. 23. 02:52
Understanding web.xml Files | 펌글 2004/11/23 11:22
http://blog.naver.com/joy7600/40008189699

http://www.shockrave.com/v1/handlers/index.cfm?id=19399&method=full

 

Understanding web.xml Files

by Matt Horn
Technical Writer
Macromedia

Deployment Descriptor Overview

Deployment descriptors are text-based XML files whose elements describe how to deploy and assemble components into a specific environment. They also contain information about the components that can specify settings not contained in the code of the components themselves, such as initialization parameters and security settings.

This section explains the various types of deployment descriptors found in J2EE-compliant systems and then focuses on the web.xml file, the web component deployment descriptor.

Types of deployment descriptors

Deployment descriptors come in several flavors as defined by the J2EE specification. There are three major deployment descriptors, which correspond to three major pieces of the J2EE:

  • J2EE application deployment descriptor. J2EE applications contain one or more J2EE modules and one J2EE application deployment descriptor. The J2EE application deployment descriptor is stored as /META-INF/application.xml and is defined in the J2EE specification. Its major function is to point to the modules within the application. J2EE applications are typically stored and deployed as enterprise application archive (EAR) files.
  • EJB module deployment descriptor. EJB modules contain one or more EJB components. The EJB module deployment descriptor is stored as /META-INF/ejb-jar.xml and is defined in the EJB specification. Its major function is to define and configure EJBs. EJB modules are typically stored and deployed as Java archive (JAR) files.
  • Web module deployment descriptor. Web modules contain one or more web components (such as servlets, JSPs, or HTML files). The web module deployment descriptor is stored as /WEB-INF/web.xml and is defined in the Servlet specification. Its major function is to define the web component settings. Web modules are typically stored and deployed as web application archive (WAR) files.

This article does not address the J2EE application client module and J2EE connector module, which also have their own deployment descriptors. Furthermore, Tag Library Descriptor (TLD) files which describe custom JSP tag libraries are not discussed.

The following illustration shows two web modules, app1.war and app2.war, each containing an assortment of web components (such as JSPs, and servlets) as well as static web files (HTML files and GIFs), within a J2EE application. It also shows an EJB module with EJB components (app_ejbs.jar). Notice that just as each web and EJB module has its own deployment descriptor, so does the J2EE application.

Why you need deployment descriptors

Deployment descriptors relate installation and configuration information about applications to the application servers. They can also be used to convey information about the application to other people involved in the development process.

If you want to create an application that can be deployed without the headache of manually configuring its components, then packaging it as a WAR, JAR, or EAR file is the best approach. Each of these files requires a deployment descriptor.

Overlapping elements

The following bulleted lists are meant to show the overlap of deployment descriptor elements.

Common elements in all descriptors (web.xml, application.xml, and ejb- jar.xml):

  • Icons
  • Description
  • Display name

Elements in only web.xml and ejb-jar.xml deployment descriptors:

  • Naming environment entries
  • EJB references
  • Connection factory references
  • Security elements

Elements in application.xml deployment descriptor only:

  • Module descriptions
  • Security roles

Elements in web.xml deployment descriptor only:

  • Servlet definitions
  • Servlet mappings
  • Error pages
  • Form-based authentication configuration

Elements in ejb-jar.xml deployment descriptor only:

  • Transaction elements
  • Persistence elements

As you can see, there can be overlapping of elements in the deployment descriptors. Each of the modules have their own common elements such as descriptions, icons and display names. While these elements share element names and syntax, it is important to remember that they affect only the module whose deployment descriptor they are in.

However, sometimes the modules define elements that interact with other module's elements. For example, the application.xml, ejb-jar.xml and web.xml files can all define security roles. It is the role of the application assembler to make sure that the descriptors complement one another rather than provide contradictory configuration information.

For complete descriptions of the various XML files and their allowed values, you can view the DTDs in the module specifications. The elements of the web.xml file are described in detail in "web.xml Elements".

The rest of this article provides information on the web application deployment descriptor file. For information on the EJB and J2EE deployment descriptors, refer to their respective specifications.

Introduction to the web.xml File

The web.xml file is used by the J2EE application server during deployment of a web module. It describes the web components used by that web module, environment variables, and security requirements. This information is stored as /WEB-INF/web.xml. For example, the default application's deployment descriptor might be stored as /usr/jrun/servers/default/default-app/WEB-INF/web.xml.

You must add a web.xml deployment descriptor to any WAR file you want to deploy as a web application. You can then add your web module to a J2EE application, which has its own deployment descriptor (application.xml) in addition to the web module's web.xml.

Who creates web.xml files

JRun and the web component creator share in the creation of the web.xml deployment descriptor. Some but not all of the settings in the web.xml file can be created or edited programmatically by using JMC panels. For example, there is currently no panel to write user/role/group information to the web.xml file.

For detailed information on which elements in a web.xml file can be defined by JMC panels, review the descriptions in the following sections. A table in third part of this series lists all the primary elements and shows which JMC panel defines that element.

web.xml Elements

The web.xml file can define the following information, as defined by the web application deployment descriptor data type definition (DTD) in the Servlet specification:

Note the following syntax rules for a DTD:

  • * Specify this element as many times as necessary (zero or more). This element is optional.
  • ? Specify this element one time only. This element is optional.
  • + Specify this element one or more times. This element is required if its super-element is used.
Note: All web application deployment descriptors must begin with the following DOCTYPE declaration:


The web.xml file contains the following types of elements:

  • web-app element
  • application elements
  • servlet elements
  • security elements
  • environment variables
  • EJB references

These elements are described in the next two parts of this three-part series. The second installment discusses the types of elements contained in the web.xml file. The third installment discusses using environment variables and creating web.xml files, and shows complete examples of web.xml files. Click here to read the next installment.

 

Understanding the web.xml Deployment Descriptor, Part 2

This is the second installment of a three installment series, and describes the syntax of web.xml files. This second installment has two parts. The continuation of this second installment can be viewed here. The first installment introduced the basics of deployment descriptors. The third installment discusses using environment variables and creating web.xml files, and shows complete examples of web.xml files.

web-app element

<web-app>web.xml elements</web-app>
<web-app>

The web-app element wraps all other elements in the web.xml file. Each web.xml file contains a single web-app element, which is the root of the deployment descriptor and wraps all other elements in the file.

Application elements

Application elements define attributes that apply to an entire web application.

General application elements

General application elements allow you to specify a description and application name. When you create an application using the Create An Application panel in the JMC, you cannot set the general elements described in this section. You can set them in the Edit An Application panel or use a text or XML editor and edit the web.xml file directly.

<description>description</description>? <display-name>name</display-name>?
<description>description</description>?

Provides a description of the web application. Define this element in the Application Description field on the Edit An Application panel of the JMC.

<display-name>name</display-name>?

Provides a short web application name. This element is intended for use in graphical programming tools. You define this element in the Application Display Name field on the Edit An Application panel of the JMC.

Icon

Icon elements are used in graphical programming tools to represent the web application. Application-level icon elements cannot be defined in the JMC. You can specify them by editing the web.xml file using a text editor or an XML editor.

<icon>? <large-icon>file path</large-icon>? <small-icon>file path</small-icon>? </icon>
<icon>?

Defines an icon.

<Large-icon>?

Location within the web application of a 32x32 GIF or JPEG file containing an icon image.

<Small-icon>?

Location within the web application of a 16x16 GIF or JPEG file containing an icon image.

Context-param*

Context-param elements define application-level parameters. These parameters are available to servlets through the ServletContext object. You can also think of the servlet context as the web application container environment. You can define context-param elements in the JMC, as described below.

<context-param>* <param-name>name</param-name> <param-value>value</param-value> <description>description</description>? </context-param>
<context-param>*

Defines a context parameter.

<param-name>

Specifies the parameter name. You define this element through the Variable Name field on the Application Variables panel in the JMC.

<param-value>

Specifies the parameter value. You define this element through the Variable Value field on the Application Variables panel in the JMC.

<Description>

Specifies the parameter description. This parameter cannot be set in the JMC. You can specify it by editing the web.xml file using a text editor or an XML editor.

For more information on the variables available to the components in a servlet container environment, refer to "Environment Variables".

Welcome-file-list?

The welcome-file-list element contains welcome-file elements, which specify one or more files to be used as the default welcome file (such as index.htm). You typically define welcome files through the JMC, using the File Settings panel for the web application (in the JMC, these are known as default documents).

<welcome-file-list>? <welcome-file>file name</welcome-file>+ </welcome-file-list>
<welcome-file-list>?

Contains one or more welcome-file elements.

<welcome-file>+

Specifies a default welcome file.

Error-page*

The error-page element maps an HTTP error code or a Java exception to a file. JRun displays this file upon encountering the error code or exception type. This element cannot be set in the JMC. You can specify it by editing the web.xml file using a text editor or an XML editor.

For more information on how error pages are used, refer to Developing Applications with JRun.

<error-page>* <error-code>HTTP error code</error-code> <exception-type>Java exception class</exception-type> <location>location</location> </error-page>
<error-page>*

Contains elements that define an HTTP error code or Java exception.

<error-code>

Specifies an HTTP error code. You specify either error-code or exception-type; you cannot specify both.

<exception-type>

Specifies a Java exception class. You specify either error-code or exception-type; you cannot specify both.

<location>

Specifies the location of the error-page in the web application.

Session-config*

The session-config element defines the session-timeout parameter for the web application. You can access this value through the getMaxInactiveInterval method of the HttpSession object. You define this element through the Session Timeout(min) field on the web Application Session panel in the JMC.

Note that getMaxInactiveInterval returns a value in seconds while the session-timeout element is in minutes; for example, if you set session-timeout to 5, getMaxInactiveInterval returns 300.

<session-config>* <session-timeout>timeout in minutes</session-timeout>? </session-config>
<session-config>*

Contains the session-timeout parameter.

<session-timeout>?

Specifies the session timeout interval in minutes.

Servlet-mapping*

The servlet-mapping element specifies the servlet that JRun invokes when it encounters the associated URL pattern.

<servlet-mapping>* <servlet-name>name</servlet-name> <url-pattern>mapping pattern</URL-pattern> </servlet-mapping>
<servlet-mapping>*

Contains servlet mapping elements.

<servlet-name>

Specifies the registered servlet name (also known as the alias), as defined in the JMC or the servlet element. You define this element through the Virtual Path/Extension field on the Servlet URL Mappings panel in the JMC.

<URL-pattern>

Specifies a URL pattern. When a URL that matches URL-pattern is encountered, JRun invokes the associated servlet. You define this element through the Servlet Invoked field on the Servlet URL Mappings panel in the JMC.

Mime-mapping*

The mime-mappings element contains one or more extension/mime-type pairs, each of which associates a file extension with a MIME type.

<mime-mapping>* <extension>extension</extension> <mime-type>mime type</mime-type> </mime-mapping>
<mime-mapping>*

Contains an extension/mime-type pair.

<extension>

Specifies a file extension. You define this element through the MIME Type Extension field on the MIME Type Mappings panel in the JMC.

<mime-type>

Specifies the MIME type associate with the extension. You define this element through the MIME Type field on the MIME Type Mappings panel in the JMC.

For example, if you are creating a WAP applications, you might add the following MIME mappings:

<mime-mapping> <extension>wml</extension> <mime-type>text/vnd.wap.wml</mime-type> </mime-mapping> <mime-mapping> <extension>wbmp</extension> <mime-type>image/vnd.wap.wbmp</mime-type> </mime-mapping>

Taglib*

The taglib element provides information on a tag library that is used by JSP pages within a web application. You cannot define the taglib element through the JMC. You can specify it by editing the web.xml file using a text editor or an XML editor.

<taglib>* <taglib-uri>uri</taglib-uri> <taglib-location>location</taglib-location> </taglib>
<taglib>*

Contains elements that associate a taglib URI with a physical location.

<taglib-uri>

Specifies a URI that JSP pages use to identify the tag library in the taglib directive. For example, /eistaglib.

<taglib-location>

Specifies the location of the tag library's TLD file. For example, /WEB-INF/tld/eistaglib.tld.

Resource-ref*

The resource-ref* element declares a web application's reference to an external resource. You cannot define the resource-ref element through the JMC. You specify it by editing the web.xml file using a text editor or an XML editor.

<resource-ref>* <description>description</description>? <res-ref-name>resource factory reference name</res-ref-name> <res-type>java class</res-type> <res-auth>CONTAINER or SERVLET</res-auth> </resource-ref>
<resource-ref>*

Contains elements that describe an external reference.

<Description>?

Specifies a brief description.

<res-ref-name>

Specifies the resource factory reference name.

<res-type>

Specifies the Java class of the data source.

<res-auth>

Indicates that the application performs a resource login programmatically (SERVLET) or JRun signs on automatically using principal mapping information provided by the deployer (CONTAINER).

Servlet elements

Servlet elements define servlets and their usage. You typically define servlet settings through the JMC. The servlet element has the following general form:

<servlet>*  sub-elements </servlet> 

This is the second installment of a three installment series, and describes the syntax of web.xml files. This second installment has two parts. The continuation of this second installment can be viewed here. The first installment introduced the basics of deployment descriptors. The third installment discusses using environment variables and creating web.xml files, and shows complete examples of web.xml files.

 

Understanding the web.xml Deployment Descriptor, Part 2 (continued)

This is the continuation of the second installment of a three part series, and describes the syntax of web.xml files. The first part of the second installment can be found here. The first installment introduced the basics of deployment descriptors. The third installment discusses using environment variables and creating web.xml files, and shows complete examples of web.xml files.

The following sections describe the contents of the servlet element:

General servlet elements

<icon>? <large-icon>file path</large-icon>? <small-icon>file path</small-icon>? </icon> <servlet-name>name</servlet-name> <display-name>name</display-name>? <description>description</description>? <servlet-class>fully qualified class name</servlet-class> <jsp-file>file name</JSP-file>
<icon>?

For more information on the icon element, refer to "Icon". You define these elements in the Large Icon and Small Icon fields on the Servlet Definitions panel of the JMC. Note that you cannot define the application-level icons in the JMC.

<Servlet-name>

Specifies the registered name of the servlet. Other servlets and JSP pages reference the servlet using either this name or its class name. Define this element in the Name field of the Servlet Definitions panel of the JMC.

<Display-name>?

Provides a short servlet name. Intended for use in graphical programming tools. Define this element in the Display Name field on the Servlet Definitions panel of the JMC.

<Description>?

Provides a description of the servlet. You define this element in the Description field on the Servlet Definitions panel of the JMC.

<servlet-class>

Specifies the fully qualified class name for the servlet. A servlet element can contain either servlet-class or JSP-file; it cannot contain both. Define this element in the Class Name field on the Servlet Definitions panel of the JMC.

<JSP-file>

Specifies the full path to a JSP file within the web application. A servlet element can contain either servlet-class or JSP-file; it cannot contain both. You define this element in the Class Name field on the Servlet Definitions panel of the JMC.

Init-param*

The init-param element defines servlet-level parameters. You typically define servlet parameters through the JMC.

<init-param>* <param-name>name</param-name> <param-value>value</param-value> <description>description</description>? </init-param>
<init-param>*

Contains elements that define a servlet-level initialization parameter.

<param-name>

Specifies the parameter name. Define this element in the Init Arguments field on the Servlet Definitions panel of the JMC.

<param-value>

Specifies the parameter value. Define this element in the Init Arguments field on the Servlet Definitions panel of the JMC.

<Description>?

Specifies a description for the initialization parameter. You cannot define this element through the JMC. You specify it by editing the web.xml file using a text editor or an XML editor.

For more information on the variables available to the components in a servlet container environment, refer to "Environment Variables".

Load-on-startup?

The presence of this element indicates that JRun loads the servlet at startup. Define this element using the Servlet Preload Order dialog box from the Servlet Definitions panel in the JMC. For more information, refer to the JRun Setup Guide.

<load-on-startup>optional sequence</load-on-startup>?
<load-on-startup>?

Specifies that JRun loads the servlet at startup time. You can optionally enclose a positive integer to indicate a relative loading sequence. JRun loads lower integers before higher integers.

For example, the following code indicates that FredServlet gets loaded first, followed by TomServlet.

<servlet> <servlet-name>FredServlet</servlet-name> ... <load-on-startup>1</load-on-startup> ... </servlet> <servlet> <servlet-name>TomServlet</servlet-name> ... <load-on-startup>2</load-on-startup> ... </servlet>

Security-role-ref*

The security-role-ref element declares a security role reference in the servlet code. You cannot define this element through the JMC. You specify it by editing the web.xml file using a text editor or an XML editor.

<security-role-ref>* <description>description</description>? <role-name>name</role-name> <role-link>role from security-role</role-link> </security-role-ref>
<security-role-ref>*

Contains a security role reference.

<Description>?

Specifies a brief description.

<role-name>

Specifies the security role reference used within the servlet's code.

<role-link>

Specifies the related role name, as defined in the user data store.

Security elements

Web.xml security elements specify the resources to be secured and the roles authorized to access secure resources. You cannot define these elements through the JMC. You specify them by editing the web.xml file using a text editor or an XML editor.

For more information on the security elements in the web.xml file, refer to Developing Applications with JRun.

Security-constraint*

The security-constraint element associates security constraints with one or more web resource collections and has the following general form:

<security-constraint>*  sub-elements </security-constraint>

The following discussions describe the contents of the security-constraint element:

web-resource-collection+

The web-resource-collection+ element identifies the resources and HTTP methods to which a security constraint applies.

<web-resource-collection>+ <web-resource-name>name</web-resource-name> <description>description</description>? <URL-pattern>pattern</URL-pattern>* <http-method>method</HTTP-method>* </web-resource-collection>
<web-resource-collection>+

Contains elements that identify the resources and HTTP methods to which a security constraint applies.

<web-resource-name>

Specifies the name of the web resource collection.

<Description>?

Specifies a description for the web resource collection.

<URL-pattern>*

Identifies the resources to be secured (for example, /store/*).

<HTTP-method>*

Specifies the HTTP method for which the security constraint applies. If you do not specify this element, JRun applies the security constraint to all methods.

Auth-constraint?

The auth-constraint element specifies the roles that can access the web resource collection.

<auth-constraint>? <description>description</description>? <role-name>name</role-name>* </auth-constraint>
<auth-constraint>?

Contains elements that specify the roles that can access the collection.

<Description>?

Specifies a description for the constraint.

<Role-name>*

Specifies the roles that can access the resources affected by web-resource-collection.

Login-config?

The login-config element specifies authentication instructions. For complete examples of the login-config element, refer to Developing Applications with JRun.

<login-config>? <auth-method>BASIC or FORM</auth-method>? <realm-name>name</realm-name>? <form-login-config>sub-elements</form-login-config>? </login-config>
<login-config>?

Contains elements that specify authentication instructions.

<auth-method>?

Specifies the user validation method. This can be either HTTP challenge/response (BASIC) or an HTML login form (FORM). If you specify FORM, you must specify the form-login-config element.

<realm-name>?

Specifies the realm name to use in HTTP BASIC authorization. If you omit this element, JRun uses the name of the JRun server hosting the application as the realm name.

<form-login-config>?

Specifies a login page and an error page through the following sub-elements:

  • form-login-page specifies the path to a page containing a login form.
  • form-error-page specifies the path to a page containing an error form.

Environment entries

The env-entry element declares application-level environment variables. You cannot define this element through the JMC. You specify it by editing the web.xml file using a text editor or an XML editor.

<env-entry>* <description>description</description>? <env-entry-name>name</env-entry-name> <env-entry-value>value</env-entry-value>? <env-entry-type>type</env-entry-type> </env-entry>
<env-entry>*

Contains elements that define the application's environment entry.

<Description>?

Specifies a description for the environment entry.

<env-entry-name>

Specifies the name of the environment entry.

<env-entry-value>?

Specifies the value of the environment entry.

<env-entry-type>

Specifies the fully-qualified Java type of env-entry-value. Legal values are as follows:

  • java.lang.Boolean
  • java.lang.String
  • java.lang.Integer
  • java.lang.Float
  • java.lang.Double

For more information on the variables available to the components in a servlet container environment, refer to "Environment Variables".

EJB references

The ejb-ref element declares a reference to an Enterprise JavaBean. You cannot define this element through the JMC. You specify it by editing the web.xml file using a text editor or an XML editor.

<EJB-ref>* <description>description</description>? <ejb-ref-name>name</EJB-ref-name> <ejb-ref-type>type</EJB-ref-type> <home>home interface</home> <remote>remote interface</remote> <ejb-link>ejb name</ejb-link>? </ejb-ref>
<ejb-ref>*

Contains elements that declare an EJB.

<Description>?

Specifies a description for the EJB.

<ejb-ref-name>

Specifies the JNDI name that servlets use to get a reference to the EJB.

<ejb-ref-type>

Specifies the Java class type of the referenced EJB.

<home>

Specifies the fully qualified name of the EJB's home interface.

<remote>

Specifies the fully qualified name of the EJB's remote interface.

<ejb-link>?

Specifies that the reference is linked to an EJB in an encompassing J2EE application package. The value of this element must be the ejb-name of an EJB in the J2EE application package.

Unsupported elements

The following list outlines web.xml elements that are named in the Java Servlet Specification, version 2.2 but are not supported by JRun:

  • distributable
  • user-data-constraint

This is the continuation of the second installment of a three part series, and describes the syntax of web.xml files. The first part of the second installment can be found here. The first installment introduced the basics of deployment descriptors. The third installment discusses using environment variables and creating web.xml files, and shows complete examples of web.xml files.

Understanding the web.xml Deployment Descriptor, Part 3

This is the third part of a three-part series. This installment discusses using environment variables, creating web.xml files, and shows complete examples of web.xml files. The first installment introduced the basics of deployment descriptors. The second installment covered the syntax of web.xml files.

Environment Variables

There are two kinds of environment variables available to components within web modules that you can set in the web.xml deployment descriptor. These are:

  • Component-specific. These parameters can only be accessed from a single web component (such as a servlet or JSP) within the module. In the deployment descriptor, they are tagged as the init-param sub-elements inside the servlet element.
  • Container-specific. These variables can be accessed from all web components within the servlet container environment. They can be tagged as either env-entry or context-param elements in the deployment descriptor.

These environment variables are explained in the sections that follow.

Component-specific parameters

Component-specific parameters are set in the init-param element of the web.xml deployment descriptor. This element must be within the servlet element. You can define values and names for any number of parameters.

For example, you could define a component-specific parameter in a deployment descriptor as follows:

<servlet> <init-param> <param-name>EmailAddress</param-name> <param-value>sales@Macromedia.com</param-value> </init-param> </servlet>

Component-specific parameters are accessible through the ServletContext object's getInitParameter() method. You could write code in that specific web component that extracts the value of this parameter as follows:

String addy = this.getInitParameter("EmailAddress");

Container-specific environment variables

Container-specific environment variables can be used to provide configuration information to all web components (such as servlets and JSPs) within a web application or servlet container environment.

There are two available container-specific environment variables:

  • Container parameters
  • Application environment variables

Both types of variables can be accessed from any web component in the servlet container environment, however, they are accessed in different ways, described in the sections that follow.

Container parameters

Container parameters are set in the context-param element of the web.xml deployment descriptor. You can define names and values for any number of parameters. Accessing container parameters only returns strings.

For example, you could define a container parameter in a deployment descriptor as follows:

<context-param> <param-name>footerPage</param-name> <param-value>/data/foot11-00.html</param-value> </context-param>

Container parameters are accessible through the ServletContext object's getInitParameter() method. You could write code in that specific web component that extracts the value of this parameter as follows:

ServletContext context = this.getServletContext(); String footer = context.getInitParameter("footerPage");

While this appears very similar to the component-specific parameters, remember that these parameters can be accessed from any web component within the servlet container environment.

Application environment variables

Application environment variables are set in the env-entry element of the web.xml deployment descriptor. You can define names and values for any number of parameters. Accessing application environment variables can return several types of objects. With the env-entry-type sub-element, you can reference one of the following types of objects:

  • Boolean
  • String
  • Integer
  • Double
  • Float

The env-entry-type sub-element provides a built-in mechanism for validating the object's type. This validation takes place at deployment time. As an example, you could define an application environment variable in a deployment descriptor as follows:

<env-entry> <env-entry-name>headerPage</env-entry-name> <env-entry-value>/data/head11-00.html</env-entry-value> <env-entry-type>java.lang.String</env-entry-type> </env-entry> 

Application environment variables are accessed in the java:comp/env context through a JNDI lookup rather than from a ServletContext object. You could write code in any web component within the servlet container environment that extracts the value of this application environment variable as follows:

InitialContext context = new InitialContext(); String header = (String) context.lookup("java:comp/env/headerPage"); 

The JNDI lookup method expects the type specified by the <env-entry-type> element and will throw an exception if the returned value isn't of that type.

Creating a web.xml File

The web.xml file is created both by the JMC and the programmer since the JMC does not have panels that can make all the changes.

The easiest way to create a web.xml file is to let JRun do most of the work. The general process of creating a web.xml file follows.

1 Create an application in the JMC using the Create An Application panel. This creates a skeleton web.xml file for the application.
2 Use the Edit An Application panel to add the description and display-name elements to your web.xml deployment descriptor.
3 Use JMC panels to make any other changes to the web application settings. The following table can be used as a general guideline showing which elements can be defined by which JMC panel. For more information on which sub-elements can be defined by the JMC, refer to the specific element's description beginning in the below list.
 

web.xml element

JMC panel

icon

Cannot be defined using the JMC

display-name

Edit An Application

description

Edit An Application

distributable

Cannot be defined using the JMC

context-param

Application Variables*

servlet

Servlet Definitions*

servlet-mapping

Servlet URL Mappings

session-config

web Application Session

mime-mapping

MIME Type Mappings

welcome-file-list

File Settings

error-page

Cannot be defined using the JMC

taglib

Cannot be defined using the JMC

resource-ref

Cannot be defined using the JMC

security-constraint

Cannot be defined using the JMC

login-config

Cannot be defined using the JMC

security-role

Cannot be defined using the JMC

env-entry

Cannot be defined using the JMC

ejb-ref

Cannot be defined using the JMC

* Some, but not all, sub-elements can be set in the JMC panel.

4 Use a text editor or XML editor to define elements in the web.xml file that cannot be defined by the JMC.

Examples of web.xml Files

This section provides a basic example of a web.xml file and a security example. For more web.xml file examples, refer to the Java Servlet Specification, version 2.2.

Basic example

The following example web.xml file contains basic information.

<web-app> <display-name>JRun Demo</display-name> <description>JRun Demo</description> <session-config> <session-timeout>30</session-timeout> </session-config> <mime-mapping> <extension> txt </extension> <mime-type> text/plain </mime-type> </mime-mapping> <mime-mapping> <extension> html </extension> <mime-type> text/html </mime-type> </mime-mapping> <welcome-file-list> <welcome-file> index.html </welcome-file> </welcome-file-list> </web-app>

Security example

The following web.xml file contains entries that enable authentication.

<web-app> <display-name>Security Default</display-name> <description>Default application for testing security</description> <session-config> <session-timeout>30</session-timeout> </session-config> <mime-mapping> <extension> txt </extension> <mime-type> text/plain </mime-type> </mime-mapping> <mime-mapping> <extension> html </extension> <mime-type> text/html </mime-type> </mime-mapping> <error-page> <error-code>401</error-code> <location>/Unauthorized.html</location> </error-page> <error-page> <error-code>403</error-code> <location>/Forbidden.html</location> </error-page> <login-config> <auth-method> FORM </auth-method> <realm-name> Sales </realm-name> <form-login-config> <form-login-page> /login.html </form-login-page> <form-error-page> /loginerror.html </form-error-page> </form-login-config> </login-config> <security-constraint> <web-resource-collection> <web-resource-name>SalesInfo</web-resource-name> <url-pattern>/servlet/Sn*</URL-pattern> <http-method>GET</HTTP-method> <HTTP-method>POST</HTTP-method> <description>Sales Info Resource</description> <auth-constraint> <role-name>manager</role-name> <description>Managers only</description> </auth-constraint> </web-resource-collection> </security-constraint> <welcome-file-list> <welcome-file> index.jsp </welcome-file> <welcome-file> index.html </welcome-file> </welcome-file-list> <servlet> <servlet-name> SecureSnoop </servlet-name> <servlet-class> SecureSnoop </servlet-class> <security-role-ref> <role-name> MGR </role-name> <role-link> manager </role-link> </security-role-ref> </servlet> </web-app>

This installment discussed using environment variables, creating web.xml files, and showed complete examples of web.xml files. The first installment introduced the basics of deployment descriptors. The second installment covered the syntax of web.xml files.

'web' 카테고리의 다른 글

FTP의 passive, active mode 설명  (0) 2006.02.20
[펌] Axis Webservice 설치및 테스트  (0) 2005.09.03
Tomcat 4.1.12 버전에서 서블릿 접근  (0) 2005.02.08
web.xml 설명.  (0) 2005.02.04
server.xml  (0) 2005.02.04
Posted by '김용환'
,

c programming FAQs

c or linux 2005. 6. 23. 09:02

'c or linux' 카테고리의 다른 글

[펌] C언어 연산자 우선 순위  (0) 2005.11.15
[펌] Visual Studio 6.0의 라이브러리 링크  (0) 2005.11.05
enumeration + function pointer  (0) 2005.03.16
define 문에서 do while 문 사용이유  (0) 2005.03.15
상수 포인터  (0) 2005.03.15
Posted by '김용환'
,

C#과 자바의 비교.

etc tools 2005. 6. 14. 08:24

출처 : http://www.harding.edu/USER/fmccown/WWW/java1_5_csharp_comparison.html

 

Java (J2SE 5.0) and C# Comparison



Java

C#

Comments
// Single line
/* Multiple
    line  */

/** Javadoc documentation comments */
// Single line
/* Multiple
    line  */

/// XML comments on a single line
/** XML comments on multiple lines */
Data Types

Primitive Types
boolean
byte
char
short, int, long
float, double


Reference Types

Object   (superclass of all other classes)
String
arrays, classes, interfaces

Conversions

// int to String
int x = 123;
String y = Integer.toString(x);  // y is "123"

// String to int
y = "456"; 
x = Integer.parseInt(y);   // x is 456

// double to int
double z = 3.5;
x = (int) z;   // x is 3  (truncates decimal)

Value Types
bool
byte, sbyte
char
short, ushort, int, uint, long, ulong
float, double, decimal
structures, enumerations

Reference Types
object    (superclass of all other classes)
string
arrays, classes, interfaces, delegates

Convertions

// int to string
int x = 123;
String y = x.ToString();  // y is "123"

// string to int
y = "456";
x = int.Parse(y);   // or x = Convert.ToInt32(y);

// double to int
double z = 3.5;
x = (int) z;   // x is 3  (truncates decimal)

Constants
// May be initialized in a constructor
final double PI = 3.14;
const double PI = 3.14;

// Can be set to a const or a variable. May be initialized in a constructor.
readonly int MAX_HEIGHT = 9;

Enumerations

enum Action {Start, Stop, Rewind, Forward};

// Special type of class
enum Status {
  Flunk(50), Pass(70), Excel(90);
  private final int value;
  Status(int value) { this.value = value; }
  public int value() { return value; }
};

Action a = Action.Stop;
if (a != Action.Start)
  System.out.println(a);               // Prints "Stop"

Status s = Status.Pass;
System.out.println(s.value());      // Prints "70"

enum Action {Start, Stop, Rewind, Forward};

enum Status {Flunk = 50, Pass = 70, Excel = 90};

No equivalent.





Action a = Action.Stop;
if (a != Action.Start)
  Console.WriteLine(a);             // Prints "Stop"

Status s = Status.Pass;
Console.WriteLine((int) s);       // Prints "70"

Operators

Comparison
==  <  >  <=  >=  !=

Arithmetic
+  -  *  /
(mod)
/   (integer division if both operands are ints)
Math.Pow(x, y)

Assignment
=  +=  -=  *=  /=   %=   &=  |=  ^=  <<=  >>=  >>>=  ++  --

Bitwise
&  |  ^   ~  <<  >>  >>>

Logical
&&  ||  &  |   !

Note: && and || perform short-circuit logical evaluations

String Concatenation
+

Comparison
==  <  >  <=  >=  !=

Arithmetic
+  -  *  /
(mod)
/   (integer division if both operands are ints)
Math.Pow(x, y)

Assignment
=  +=  -=  *=  /=   %=  &=  |=  ^=  <<=  >>=  ++  --

Bitwise
&  |  ^   ~  <<  >>

Logical
&&  ||   !

Note: && and || perform short-circuit logical evaluations, no & and | equivalents

String Concatenation
+

Choices

greeting = age < 20 ? "What's up?" : "Hello";

if (x < y)
  System.out.println("greater");

if (x != 100) {   
  x *= 5;
  y *= 2;
}
else
  z *= 6;

int selection = 2;
switch (selection) {     // Must be byte, short, int, char, or enum
  case 1: x++;            // Falls through to next case if no break
  case 2: y++;   break;
  case 3: z++;   break;
  default: other++;
}

greeting = age < 20 ? "What's up?" : "Hello";

if (x < y) 
  Console.WriteLine("greater");

if (x != 100) {   
  x *= 5;
  y *= 2;
}
else
  z *= 6;

string color = "red";
switch (color) {                          // Can be any predefined type
  case "red":    r++;    break;       // break is mandatory; no fall-through
  case "blue":   b++;   break;
  case "green": g++;   break;
  default: other++;     break;       // break necessary on default
}

Loops

while (i < 10)
  i++;

for (i = 2; i <= 10; i += 2) 
  System.out.println(i);

do
  i++;
while (i < 10);

for (int i : numArray)  // foreach construct 
  sum += i;

// for loop can be used to iterate through any Collection
import java.util.ArrayList;
ArrayList<Object> list = new ArrayList<Object>();
list.add(10);    // boxing converts to instance of Integer
list.add("Bisons");
list.add(2.3);    // boxing converts to instance of Double

for (Object o : list)
  System.out.println(o);

while (i < 10)
  i++;

for (i = 2; i <= 10; i += 2)
  Console.WriteLine(i);

do
  i++;
while (i < 10);

foreach (int i in numArray) 
  sum += i;

// foreach can be used to iterate through any collection 
using System.Collections;
ArrayList list = new ArrayList();
list.Add(10);
list.Add("Bisons");
list.Add(2.3);

foreach (Object o in list)
  Console.WriteLine(o);

Arrays

int nums[] = {1, 2, 3};   or   int[] nums = {1, 2, 3};
for (int i = 0; i < nums.length; i++)
  System.out.println(nums[i]);

String names[] = new String[5];
names[0] = "David";

float twoD[][] = new float[rows][cols];
twoD[2][0] = 4.5;

int[][] jagged = new int[5][];
jagged[0] = new int[5];
jagged[1] = new int[2];
jagged[2] = new int[3];
jagged[0][4] = 5;

int[] nums = {1, 2, 3};
for (int i = 0; i < nums.Length; i++)
  Console.WriteLine(nums[i]);

string[] names = new string[5];
names[0] = "David";

float[,] twoD = new float[rows, cols];
twoD[2,0] = 4.5f;

int[][] jagged = new int[3][] {
    new int[5], new int[2], new int[3] };
jagged[0][4] = 5;

Functions
// Return single value
int Add(int x, int y) {
   return x + y;
}

int sum = Add(2, 3);

// Return no value
void PrintSum(int x, int y) {
   System.out.println(x + y);
}

PrintSum(2, 3); 

// Primitive types and references are always passed by value
void TestFunc(int x, Point p) {
   x++;
   p.x++;       // Modifying property of the object
   p = null;    // Remove local reference to object
}

class Point {
   public int x, y;
}

Point p = new Point();
p.x = 2;
int a = 1;
TestFunc(a, p);
System.out.println(a + " " + p.x + " " + (p == null) );  // 1 3 false




// Accept variable number of arguments
int Sum(int ... nums) {
  int sum = 0;
  for (int i : nums)
    sum += i;
  return sum;
}

int total = Sum(4, 3, 2, 1);   // returns 10

// Return single value
int Add(int x, int y) {
   return x + y;
}

int sum = Add(2, 3);

// Return no value
void PrintSum(int x, int y) {
   Console.WriteLine(x + y);
}

PrintSum(2, 3); 

// Pass by value (default), in/out-reference (ref), and out-reference (out)
void TestFunc(int x, ref int y, out int z, Point p1, ref Point p2) {
   x++;  y++;  z = 5;
   p1.x++;       // Modifying property of the object     
   p1 = null;    // Remove local reference to object
   p2 = null;   // Free the object
}

class Point {
   public int x, y;
}

Point p1 = new Point();
Point p2 = new Point();
p1.x = 2;
int a = 1, b = 1, c;   // Output param doesn't need initializing
TestFunc(a, ref b, out c, p1, ref p2);
Console.WriteLine("{0} {1} {2} {3} {4}",
   a, b, c, p1.x, p2 == null);   // 1 2 5 3 True

// Accept variable number of arguments
int Sum(params int[] nums) {
  int sum = 0;
  foreach (int i in nums)
    sum += i;
  return sum;
}

int total = Sum(4, 3, 2, 1);   // returns 10

Strings

// String concatenation
String school = "Harding ";
school = school + "University";   // school is "Harding University"

// String comparison
String mascot = "Bisons";
if (mascot == "Bisons")    // Not the correct way to do string comparisons
if (mascot.equals("Bisons"))   // true
if (mascot.equalsIgnoreCase("BISONS"))   // true
if (mascot.compareTo("Bisons") == 0)   // true

System.out.println(mascot.substring(2, 5));   // Prints "son"

// My birthday: Oct 12, 1973
java.util.Calendar c = new java.util.GregorianCalendar(1973, 10, 12);
String s = String.format("My birthday: %1$tb %1$te, %1$tY", c);

// Mutable string
StringBuffer buffer = new StringBuffer("two ");
buffer.append("three ");
buffer.insert(0, "one ");
buffer.replace(4, 7, "TWO");
System.out.println(buffer);     // Prints "one TWO three"

// String concatenation
string school = "Harding ";
school = school + "University";   // school is "Harding University"

// String comparison
string mascot = "Bisons";
if (mascot == "Bisons")    // true
if (mascot.Equals("Bisons"))   // true
if (mascot.ToUpper().Equals("BISONS"))   // true
if (mascot.CompareTo("Bisons") == 0)    // true

Console.WriteLine(mascot.Substring(2, 3));    // Prints "son"

// My birthday: Oct 12, 1973
DateTime dt = new DateTime(1973, 10, 12);
string s = "My birthday: " + dt.ToString("MMM dd, yyyy");

// Mutable string
System.Text.StringBuilder buffer = new System.Text.StringBuilder("two ");
buffer.Append("three ");
buffer.Insert(0, "one ");
buffer.Replace("two", "TWO");
Console.WriteLine(buffer);     // Prints "one TWO three"

Exception Handling

// Must be in a method that is declared to throw this exception
Exception ex = new Exception("Something is really wrong.");
throw ex;  

try {
  y = 0;
  x = 10 / y;
} catch (Exception ex) {
  System.out.println(ex.getMessage()); 
} finally {
  // Code that always gets executed
}

Exception up = new Exception("Something is really wrong.");
throw up;  // ha ha


try
{
  y = 0;
  x = 10 / y;
} catch (Exception ex) {      // Variable "ex" is optional
  Console.WriteLine(ex.Message);
} finally {
  // Code that always gets executed
}

Namespaces

package harding.compsci.graphics;












import
harding.compsci.graphics.Rectangle;  // Import single class

import harding.compsci.graphics.*;   // Import all classes

namespace Harding.Compsci.Graphics {
  ...
}

or

namespace Harding {
  namespace Compsci {
    namespace Graphics {
      ...
    }
  }
}

// Import all class. Can't import single class.
using Harding.Compsci.Graphics;

Classes / Interfaces

Accessibility keywords
public
private
protected
static



// Inheritance
class FootballGame extends Competition {
  ...
}

// Interface definition
interface IAlarmClock {
  ...
}

// Extending an interface 
interface IAlarmClock extends IClock {
  ...
}

// Interface implementation
class WristWatch implements IAlarmClock, ITimer {
   ...
}

Accessibility keywords
public
private
internal
protected
protected internal
static

// Inheritance
class FootballGame : Competition {
  ...
}

// Interface definition
interface IAlarmClock {
  ...
}

// Extending an interface 
interface IAlarmClock : IClock {
  ...
}

// Interface implementation
class WristWatch : IAlarmClock, ITimer {
   ...
}

Constructors / Destructors

class SuperHero {
  private int mPowerLevel;

  public SuperHero() {
    mPowerLevel = 0;
  }

  public SuperHero(int powerLevel) {
    this.mPowerLevel= powerLevel;
  }

  // No destructors, just override the finalize method
  protected void finalize() throws Throwable { 
    super.finalize();   // Always call parent's finalizer  
  }
}

class SuperHero {
  private int mPowerLevel;

  public SuperHero() {
     mPowerLevel = 0;
  }

  public SuperHero(int powerLevel) {
    this.mPowerLevel= powerLevel; 
  }

  ~SuperHero() {
    // Destructor code to free unmanaged resources.
    // Implicitly creates a Finalize method.

  }
}

Objects

SuperHero hero = new SuperHero();

hero.setName("SpamMan");
hero.setPowerLevel(3);

hero.Defend("Laura Jones");
SuperHero.Rest();  // Calling static method

SuperHero hero2 = hero;   // Both refer to same object
hero2.setName("WormWoman");
System.out.println(hero.getName());  // Prints WormWoman

hero = null;   // Free the object

if (hero == null)
  hero = new SuperHero();

Object obj = new SuperHero();
System.out.println("object's type: " + obj.getClass().toString());
if (obj instanceof SuperHero)
  System.out.println("Is a SuperHero object.");

SuperHero hero = new SuperHero();

hero.Name = "SpamMan";
hero.PowerLevel = 3;

hero.Defend("Laura Jones");
SuperHero.Rest();   // Calling static method

SuperHero hero2 = hero;   // Both refer to same object
hero2.Name = "WormWoman";
Console.WriteLine(hero.Name);   // Prints WormWoman

hero = null ;   // Free the object

if (hero == null)
  hero = new SuperHero();

Object obj = new SuperHero(); 
Console.WriteLine("object's type: " + obj.GetType().ToString());
if (obj is SuperHero)
  Console.WriteLine("Is a SuperHero object.");

Properties

private int mSize;

public int getSize() { return mSize; }
public void setSize(int value) {
  if (value < 0)
    mSize = 0;
  else
    mSize = value;
}


int s = shoe.getSize();
shoe.setSize(s+1);

private int mSize;

public int Size {
  get { return mSize; }
  set {
    if (value < 0)
      mSize = 0;
    else
      mSize = value;
  }
}

shoe.Size++;

Structs


 

No structs in Java.

struct StudentRecord {
  public string name;
  public float gpa;

  public StudentRecord(string name, float gpa) {
    this.name = name;
    this.gpa = gpa;
  }
}

StudentRecord stu = new StudentRecord("Bob", 3.5f);
StudentRecord stu2 = stu;  

stu2.name = "Sue";
Console.WriteLine(stu.name);    // Prints "Bob"
Console.WriteLine(stu2.name);   // Prints "Sue"
Console I/O
java.io.DataInput in = new java.io.DataInputStream(System.in);
System.out.print("What is your name? ");
String name = in.readLine();
System.out.print("How old are you? ");
int age = Integer.parseInt(in.readLine());
System.out.println(name + " is " + age + " years old.");


int c = System.in.read();   // Read single char
System.out.println(c);      // Prints 65 if user enters "A"

// The studio costs $499.00 for 3 months.
System.out.printf("The %s costs $%.2f for %d months.%n", "studio", 499.0, 3);

// Today is 06/25/04
System.out.printf("Today is %tD%n", new java.util.Date());

Console.Write("What's your name? ");
string name = Console.ReadLine();
Console.Write("How old are you? ");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("{0} is {1} years old.", name, age);
// or
Console.WriteLine(name + " is " + age + " years old.");

int c = Console.Read();  // Read single char
Console.WriteLine(c);    // Prints 65 if user enters "A"

// The studio costs $499.00 for 3 months.
Console.WriteLine("The {0} costs {1:C} for {2} months.\n", "studio", 499.0, 3);

// Today is 06/25/2004
Console.WriteLine("Today is " + DateTime.Now.ToShortDateString());

File I/O

import java.io.*;

// Character stream writing
FileWriter writer = new FileWriter("c:\\myfile.txt");
writer.write("Out to file.");
writer.close();

// Character stream reading
FileReader reader = new FileReader("c:\\myfile.txt");
BufferedReader br = new BufferedReader(reader);
String line = br.readLine();
while (line != null) {
  System.out.println(line);
  line = br.readLine();
}
reader.close();

// Binary stream writing
FileOutputStream out = new FileOutputStream("c:\\myfile.dat");
out.write("Text data".getBytes());
out.write(123);
out.close();

// Binary stream reading
FileInputStream in = new FileInputStream("c:\\myfile.dat");
byte buff[] = new byte[9];
in.read(buff, 0, 9);   // Read first 9 bytes into buff
String s = new String(buff);
int num = in.read();   // Next is 123
in.close();

using System.IO;

// Character stream writing
StreamWriter writer = File.CreateText("c:\\myfile.txt");
writer.WriteLine("Out to file.");
writer.Close();

// Character stream reading
StreamReader reader = File.OpenText("c:\\myfile.txt");
string line = reader.ReadLine();
while (line != null) {
  Console.WriteLine(line);
  line = reader.ReadLine();
}
reader.Close();


// Binary stream writing

BinaryWriter out = new BinaryWriter(File.OpenWrite("c:\\myfile.dat"));
out.Write("Text data");
out.Write(123);
out.Close();

// Binary stream reading
BinaryReader in = new BinaryReader(File.OpenRead("c:\\myfile.dat"));
string s = in.ReadString();
int num = in.ReadInt32();
in.Close();

Posted by '김용환'
,