This page applies to Jetty 7 and Jetty 8. For Jetty 9 documentation please look to the Documentation Hub.


Contents

 [hide]

Introduction

Jetty has a slogan, "Don't deploy your application in Jetty, deploy Jetty in your application." What this means is that as an alternative to bundling your application as a standard WAR to be deployed in Jetty, Jetty is designed to be a software component that can be instantiated and used in a Java program just like any POJO. Put another way, running Jetty in embedded mode means putting an HTTP module into your application, rather than putting your application into an HTTP server.

This tutorial takes you step-by-step from the simplest Jetty server instantiation to running multiple web applications with standards-based deployment descriptors. The source for most of these examples is part of the standard Jetty project.

Before doing this tutorial, it is worth while to do the Hello World tutorial. This tutorial is also available as a Embedding Jetty Webinar recording.

Jetty Version
The code in this tutorial is from Jetty 7, but should also work on Jetty 8. For the latest stable code, follow the links to the code xref from the latest release, which might vary slightly from the code examples given on this page.

Details

To embed a Jetty server, the following steps are typical:

  1. Create the server
  2. Add/Configure Connectors
  3. Add/Configure Handlers
  4. Add/Configure Servlets/Webapps to Handlers
  5. Start the server
  6. Wait (join the server to prevent main exiting)

Creating a Server

The following code from SimplestServer.java instantiates and runs the simplest possible Jetty server:

public class SimplestServer
{
    public static void main(String[] args) throws Exception
    {
        Server server = new Server(8080);
        server.start();
        server.join();
    }
}

This runs an HTTP server on port 8080. It is not a very useful server as it has no handlers and thus returns a 404 error for every request.


Writing Handlers

To produce a response to a request, Jetty requires a Handler to be set on the server. A handler may:

  • Examine/modify the HTTP request.
  • Generate the complete HTTP response.
  • Call another Handler (see HandlerWrapper).
  • Select one or many Handlers to call (see HandlerCollection).

Hello World Handler

The following code based on HelloHandler.java shows a simple hello world handler:

public class HelloHandler extends AbstractHandler
{
    public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) 
        throws IOException, ServletException
    {
        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);
        response.getWriter().println("<h1>Hello World</h1>");
    }
}

The parameters passed to the handle method are:

  • target–the target of the request, which is either a URI or a name from a named dispatcher.
  • baseRequest–the Jetty mutable request object, which is always unwrapped.
  • request–the immutable request object, which might have been wrapped.
  • response–the response, which might have been wrapped.

The handler sets the response status, content-type and marks the request as handled before it generates the body of the response using a writer.

The following code from OneHandler.java shows how a Jetty server can use this handler:

public static void main(String[] args) throws Exception
{
    Server server = new Server(8080);
    server.setHandler(new HelloHandler());
 
    server.start();
    server.join();
}

You now know everything you need to know to write an HTTP server based on Jetty. However, complex request handling is typically built from multiple Handlers. We will look in later sections at how you can combine handlers like aspects. You can see some of the handlers available in Jetty in the org.eclipse.jetty.server.handlerpackage.

Configuring Connectors

To configure the HTTP connectors that the server uses, you can set one or more connectors on the server. You can configure each connector with details such as interface, port, buffer sizes, timeouts, etc.

The following code is based on ManyConnectors.java and shows how to set and configure connectors for the Hello World example:

public class ManyConnectors
{
    public static void main(String[] args) throws Exception
    {
        Server server = new Server();
 
        SelectChannelConnector connector0 = new SelectChannelConnector();
        connector0.setPort(8080);
        connector0.setMaxIdleTime(30000);
        connector0.setRequestHeaderSize(8192);
 
        SelectChannelConnector connector1 = new SelectChannelConnector();
        connector1.setHost("127.0.0.1");
        connector1.setPort(8888);
        connector1.setThreadPool(new QueuedThreadPool(20));
        connector1.setName("admin");
 
        SslSelectChannelConnector ssl_connector = new SslSelectChannelConnector();
        String jetty_home = 
          System.getProperty("jetty.home","../jetty-distribution/target/distribution");
        System.setProperty("jetty.home",jetty_home);
        ssl_connector.setPort(8443);
        SslContextFactory cf = ssl_connector.getSslContextFactory();
        cf.setKeyStore(jetty_home + "/etc/keystore");
        cf.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
        cf.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");
 
        server.setConnectors(new Connector[]{ connector0, connector1, ssl_connector });
 
        server.setHandler(new HelloHandler());
 
        server.start();
        server.join();
    }
}

Understanding Handler Collections, Wrappers and Scopes

Complex request handling is typically built from multiple Handlers that can be combined in various ways:

  • Handler Collection holds a collection of other handlers and calls each handler in order. This is useful for combining statistics and logging handlers with the handler that generates the response.
  • Handler List is a Handler Collection that calls each handler in turn until either an exception is thrown, the response is committed or the request.isHandled() returns true. It can be used to combine handlers that conditionally handle a request.
  • Handler Wrapper is a handler base class that can be used to daisy chain handlers together in the style of aspect-oriented programming. For example, a standard web application is implemented by a chain of a context, session, security and servlet handlers.
  • Context Handler Collection uses the longest prefix of the request URI (the contextPath) to select a specific ContextHandler to handle the request.

See also How to Write a Jetty Handler.

Configuring a File Server

The following code from FileServer.java uses a HandlerList to combine the ResourceHandler with the DefaultHandler:

public class FileServer
{
    public static void main(String[] args) throws Exception
    {
        Server server = new Server();
        SelectChannelConnector connector = new SelectChannelConnector();
        connector.setPort(8080);
        server.addConnector(connector);
 
        ResourceHandler resource_handler = new ResourceHandler();
        resource_handler.setDirectoriesListed(true);
        resource_handler.setWelcomeFiles(new String[]{ "index.html" });
 
        resource_handler.setResourceBase(".");
 
        HandlerList handlers = new HandlerList();
        handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
        server.setHandler(handlers);
 
        server.start();
        server.join();
    }
}

The resource handler is passed the request first and looks for a matching file in the local directory to serve. If it does not find a file, the request passes to the default handler which generates a 404 (or favicon.ico).

Configuring a File Server with XML

Now is a good time to remind you that the Jetty XML configuration format can render simple Java code into XML configuration. So the File Server example above can be written with a little reordering in Jetty XML as follows:

<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">
 
<Configure id="FileServer" class="org.eclipse.jetty.server.Server">
 
    <Call name="addConnector">
      <Arg>
          <New class="org.eclipse.jetty.server.nio.SelectChannelConnector">
            <Set name="port">8080</Set>
          </New>
      </Arg>
    </Call>
 
    <Set name="handler">
      <New class="org.eclipse.jetty.server.handler.HandlerList">
        <Set name="handlers">
	  <Array type="org.eclipse.jetty.server.Handler">
	    <Item>
	      <New class="org.eclipse.jetty.server.handler.ResourceHandler">
	        <Set name="directoriesListed">true</Set>
		<Set name="welcomeFiles">
		  <Array type="String"><Item>index.html</Item></Array>
		</Set>
	        <Set name="resourceBase">.</Set>
	      </New>
	    </Item>
	    <Item>
	      <New class="org.eclipse.jetty.server.handler.DefaultHandler">
	      </New>
	    </Item>
	  </Array>
        </Set>
      </New>
    </Set>
</Configure>

You can run this XML file from the FileServerXml.java class:

public class FileServerXml
{
    public static void main(String[] args) throws Exception
    {
        Resource fileserver_xml = Resource.newSystemResource("fileserver.xml");
        XmlConfiguration configuration = new XmlConfiguration(fileserver_xml.getInputStream());
        Server server = (Server)configuration.configure();
        server.start();
        server.join();
    }
}

Using Spring to Configure a File Server

You can also use the Spring framework to assemble Jetty servers. The file server example above can be written in Spring configuration as:

<beans>
  <bean id="Server" class="org.eclipse.jetty.server.Server" init-method="start" destroy-method="stop">
 
    <property name="connectors">
      <list>
        <bean id="Connector" class="org.eclipse.jetty.server.nio.SelectChannelConnector">
          <property name="port" value="8080"/>
        </bean>
      </list>
    </property>
 
    <property name="handler">
      <bean id="handlers" class="org.eclipse.jetty.server.handler.HandlerList">
        <property name="handlers">
          <list>
            <bean class="org.eclipse.jetty.server.handler.ResourceHandler">
              <property name="directoriesListed" value="true"/>
              <property name="welcomeFiles">
                <list>
                  <value>index.html</value>
                </list>
              </property>
              <property name="resourceBase" value="."/>
            </bean>       
            <bean class="org.eclipse.jetty.server.handler.DefaultHandler"/>
          </list>
        </property>
      </bean>
    </property>
  </bean>
</beans>

See also How to Configure Jetty with Spring.

Setting Contexts

ContextHandler is a HandlerWrapper that responds only to requests that have a URI prefix that matches the configured context path.

Requests that match the context path have their path methods updated accordingly, and the following optional context features applied as appropriate:

* A Thread Context classloader.
* A set of attributes
* A set of init parameters
* A resource base (aka document root)
* A set of virtual host names

Requests that don't match are not handled.

The following code is based on OneContext.java and sets context path and classloader for the hello handler:

public class OneContext
{
    public static void main(String[] args) throws Exception
    {
        Server server = new Server(8080);
 
        ContextHandler context = new ContextHandler();
        context.setContextPath("/hello");
        context.setResourceBase(".");
        context.setClassLoader(Thread.currentThread().getContextClassLoader());
        server.setHandler(context);
 
        context.setHandler(new HelloHandler());
 
        server.start();
        server.join();
    }
}

Creating Servlets

Servlets are the standard way to provide application logic that handles HTTP requests. Servlets are like constrained Handlers with standard ways to map specific URIs to specific servlets. The following code is based on HelloServlet.java:

public class HelloServlet extends HttpServlet
{
    private String greeting="Hello World";
    public HelloServlet(){}
    public HelloServlet(String greeting)
    {
        this.greeting=greeting;
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType("text/html");
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().println("<h1>"+greeting+"</h1>");
        response.getWriter().println("session=" + request.getSession(true).getId());
    }
}

Setting a ServletContext

ServletContextHandler is a specialization of ContextHandler with support for standard servlets. The following code from OneServletContext shows three instances of the helloworld servlet registered with a ServletContextHandler:

public class OneServletContext
{
    public static void main(String[] args) throws Exception
    {
        Server server = new Server(8080);
 
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        server.setHandler(context);
 
        context.addServlet(new ServletHolder(new HelloServlet()),"/*");
        context.addServlet(new ServletHolder(new HelloServlet("Buongiorno Mondo")),"/it/*");
        context.addServlet(new ServletHolder(new HelloServlet("Bonjour le Monde")),"/fr/*");
 
        server.start();
        server.join();
    }
}

Setting a Web Application Context

Web Applications context is a variation of ServletContextHandler that uses the standard layout and web.xml to configure the servlets, filters and other features:

public class OneWebApp
{
    public static void main(String[] args) throws Exception
    {
        String jetty_home = System.getProperty("jetty.home","..");
 
        Server server = new Server(8080);
 
        WebAppContext webapp = new WebAppContext();
        webapp.setContextPath("/");
        webapp.setWar(jetty_home+"/webapps/test.war");
        server.setHandler(webapp);
 
        server.start();
        server.join();
    }
}

If during development, you have not assembled your application into a WAR file, you can run it from its source components with something like:

public class OneWebAppUnassembled
{
    public static void main(String[] args) throws Exception
    {
        Server server = new Server(8080);
 
        WebAppContext context = new WebAppContext();
        context.setDescriptor(context+"/WEB-INF/web.xml");
context.setResourceBase("../test-jetty-webapp/src/main/webapp"); context.setContextPath("/"); context.setParentLoaderPriority(true);   server.setHandler(context);   server.start(); server.join(); } }

Configuring a Context Handler Collection

Context Handler Collection uses the longest prefix of the request URI (the contextPath) to select a specific context. The following example combines the previous two examples in a single Jetty server:

public class ManyContexts
{
    public static void main(String[] args) throws Exception
    {
        Server server = new Server(8080);
 
        ServletContextHandler context0 = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context0.setContextPath("/ctx0");
        context0.addServlet(new ServletHolder(new HelloServlet()),"/*");
        context0.addServlet(new ServletHolder(new HelloServlet("Buongiorno Mondo")),"/it/*");
        context0.addServlet(new ServletHolder(new HelloServlet("Bonjour le Monde")),"/fr/*");
 
        WebAppContext webapp = new WebAppContext();
        webapp.setContextPath("/ctx1");
        webapp.setWar(jetty_home+"/webapps/test.war");
 
        ContextHandlerCollection contexts = new ContextHandlerCollection();
        contexts.setHandlers(new Handler[] { context0, webapp });
 
        server.setHandler(contexts);
 
        server.start();
        server.join();
    }
}

Embedding JSP

Embedding JSP support can be a bit confusing if you look at the Jars under the lib/jsp directory in the jetty distribution. This is because we have to ship from Eclipse with the JSP bundles that are marked up as OSGi bundles, which you cannot directly download from Maven Central. There are dependencies available in Maven Central that work because they were the actual source for the OSGi bundles themselves. The OSGi bundles are simply these Maven Central artifacts decomposed into a few extra bundles.

An example of what you can use follows:

[INFO] org.eclipse.jetty:jetty-jsp-2.1:jar:7.2.2-SNAPSHOT
[INFO] +- org.eclipse.jetty:jetty-util:jar:7.2.2-SNAPSHOT:provided
[INFO] +- org.mortbay.jetty:jsp-2.1-glassfish:jar:2.1.v20100127:provided
[INFO] |  +- org.eclipse.jdt.core.compiler:ecj:jar:3.5.1:provided
[INFO] |  +- org.mortbay.jetty:jsp-api-2.1-glassfish:jar:2.1.v20100127:provided
[INFO] |  \- ant:ant:jar:1.6.5:provided
[INFO] \- javax.servlet:servlet-api:jar:2.5:provided

You should be able to depend on one of the embedding aggregates that we provide to get these dependencies without too much trouble.

http://repo2.maven.org/maven2/org/eclipse/jetty/aggregate


출처 - http://wiki.eclipse.org/Jetty/Tutorial/Embedding_Jetty





고민의 시작은 사용법 괴상한 Tomcat 을 버리자는 것 하나. web.xml 없애고 spring.xml 도 없애서 자바 코드로 모든 설정을 하자는 것 하나. 웹 컨테이너 위에서 war 를 돌리는 것이 아니라 Servlet 컨테이너를 임베딩해서 평범한 자바 어플리케이션 실행시키듯이 main 메서드로 실행하자는 것 하나였습니다.

줄거리는 이러합니다. Jetty 서버를 임베딩해서 JettyServer POJO 를 만듭니다. 기존에 web.xml 에서 하던 Servlet Config 를 Java 코드로 대신합니다. servlet-spring.xml 설정들도 Spring Java Annotation 으로 대신합니다. 기존에 익숙하던 Servlet 모델 개념은 그대로 사용합니다.

기존에 Spring MVC 를 사용하시던 분들은 ContextLoaderListener, DispatcherServlet 에 익숙하실 겁니다. 아래 Jetty 설정 메서드들은 web.xml 에서 하던 것과 완전히 같은 기능을 합니다. 스터틱 파일 서비스를 위해서 Jetty 에 딸려오는 DefaultServlet 을 추가해줬습니다. JspServlet 도 추가했습니다.

package com.drypot.sleek.draft;

import org.apache.jasper.servlet.JspServlet;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.servlet.DispatcherServlet;

public class JettySetter {

    public JettySetter() {
    }

    public void configure(Server server) {
        setConnector(server);
        setHandler(server);
    }

    public void setConnector(Server server) {
        SelectChannelConnector connector = new SelectChannelConnector();
        connector.setPort(8080);
        server.addConnector(connector);
    }

    public void setHandler(Server server) {
        ServletContextHandler handler = new ServletContextHandler(ServletContextHandler.SESSIONS) {
            @Override
            protected boolean isProtectedTarget(String target) {
                while (target.startsWith("//"))
                    target = URIUtil.compactPath(target);
                return StringUtil.startsWithIgnoreCase(target, "/web-inf") || StringUtil.startsWithIgnoreCase(target, "/meta-inf");
            }
        };
        handler.setContextPath("/");
        handler.setMaxFormContentSize(512 * 1024 * 1024);
        handler.setResourceBase("/Users/drypot/Documents/java/sleek/drypot-sleek-web/src/main/webapp");
        addContextLoaderListener(handler);
        addDispatcherServlet(handler);
        addJspServlet(handler);
        addDefaultServlet(handler);
        server.setHandler(handler);
    }

    public void addContextLoaderListener(ServletContextHandler handler) {
        handler.addEventListener(new ContextLoaderListener());
        handler.setInitParameter("contextClass", "org.springframework.web.context.support.AnnotationConfigWebApplicationContext");
        handler.setInitParameter("contextConfigLocation", "com.drypot.sleek.draft");
    }

    public void addDispatcherServlet(ServletContextHandler handler) {
        ServletHolder holder = new ServletHolder(new DispatcherServlet());
        holder.setInitParameter("contextConfigLocation", "");
        holder.setInitOrder(3);
        handler.addServlet(holder, "/");
    }

    public void addJspServlet(ServletContextHandler handler) {
        ServletHolder holder = new ServletHolder(new JspServlet());
        holder.setInitParameter("modificationTestInterval", "5");
        holder.setInitParameter("logVerbosityLevel", "DEBUG");
        holder.setInitParameter("sendErrorToClient", "true");
        holder.setInitParameter("compilerSourceVM", "1.5");
        holder.setInitParameter("compilerTargetVM", "1.5");
        holder.setInitParameter("fork", "false");
        holder.setInitParameter("trimSpaces", "true");
        holder.setInitOrder(2);
        handler.addServlet(holder, "*.jsp");
    }

    public void addDefaultServlet(ServletContextHandler handler) {
        ServletHolder holder = new ServletHolder(new DefaultServlet());
        //holder.setInitParameter("resourceBase", "");
        holder.setInitParameter("dirAllowed", "true");
        holder.setInitParameter("welcomeServlets", "false");
        holder.setInitParameter("gzip", "false");
        handler.addServlet(holder, "*.css");
        handler.addServlet(holder, "*.js");
        handler.addServlet(holder, "*.ico");
    }

    public static void main(String[] args) {
        try {
            Server server = new Server();
            new JettySetter().configure(server);
            server.start();
            server.join();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}

servlet-spring.xml 을 대신하는 스프링 설정 클래스입니다. Jetty 설정부에서 contextConfigLocation 으로 Spring Component 스캐닝 범위를 설정하므로 여기에서는 @ComponentScan 어노테이션을 뺏습니다. 평소처럼 Datasource 등을 여기에 줄줄이 매달면 됩니다.

package com.drypot.sleek.draft;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableTransactionManagement
@EnableWebMvc
public class SpringConfig extends WebMvcConfigurerAdapter {

    @Autowired
    ApplicationContext context;

    @Bean
    public String someCoolObj() {
        return "The Cool One";
    }

}

테스트에 사용했던 Spring MVC 컨트롤러입니다.

package com.drypot.sleek.draft;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class DemoController {

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    @ResponseBody
    public String hello(@RequestParam String name) {
        return "Hello " + name;
    }
}

다른 글에서 자세히 언급했었는데 Java Code-base Configuration 은 Spring 3.1.0.M2 부터 가능합니다.

Spring : Code-based Configuration For Spring MVC
http://drypot.com/post/215

Spring 관련 디펜던시는

<repositories>
    <repository>
        <id>org.springframework.maven.milestone</id>
        <name>Spring Maven Milestone Repository</name>
        <url>http://maven.springframework.org/milestone</url>
    </repository>
</repositories>

<properties>
    <org.springframework.version>3.1.0.M2</org.springframework.version>
</properties>

...

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${org.springframework.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${org.springframework.version}</version>
</dependency>

Jetty 관련 디펜던시는

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
</dependency>
<dependency>
    <groupId>org.eclipse.jetty</groupId>
    <artifactId>jetty-servlet</artifactId>
    <version>8.0.0.v20110901</version>
</dependency>
<dependency>
    <groupId>org.mortbay.jetty</groupId>
    <artifactId>jsp-2.1-glassfish</artifactId>
    <version>2.1.v20100127</version>
</dependency>

JSP 처리하는 jasper 가 참 문제였는데, 예전 처럼 tomcat 에 포함된 jasper 를 그냥 가져다 쓰지 못합니다. Jetty 주위에 있는 jasper 수정판이 여러 가지인데 현재로서는 위에 포함한 아티펙트가 제일 쓰기 편합니다.

Jetty 를 쓰지 않고 개발자들에게 익숙한 Tomcat 을 써도 Embedded 스타일 코드를 쉽게 만들 수는 있습니다. 그런데 Tomcat 구조가 참으로 이상하여 당장 해놔야 겠다는 생각은 들지 않고 있는데, 인터넷 검색하시거나 org.apache.catalina.startup.Tomcat 클래스 사용하시면 별로 어렵지 않게(약간의 짜증을 수반? =,=) Tomcat 도 임베딩하실 수 있습니다.

2011-09-05 16:38


출처 - http://drypot.tumblr.com/post/11171558936/jetty-spring-jsp-noxml






이 글은 Jetty 6 버전 기준이긴 하지만, 플러그인 버전이나 의존 라이브러리에서 차이가 날 뿐 Jetty 7 버전에서도 크게 다르지 않다.

Jetty 서버를 임베딩하기 위한 pom.xml 설정

Maven 프로젝트에서 Jetty 서버를 임베딩하려면 먼저 Jetty 관련 클래스들을 사용할 수 있어야 하므로, 아래와 같이 의존 라이브러리에 Jetty 관련 artifact를 추가해 준다.

<dependencies>
    <dependency>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>jsp-api-2.1</artifactId>
        <version>6.1.14</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>servlet-api-2.5</artifactId>
        <version>6.1.14</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>jetty</artifactId>
        <version>6.1.14</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>jsp-2.1</artifactId>
        <version>6.1.14</version>
        <scope>test</scope>
    </dependency>
    ...

위 설정에서 눈여겨 볼 점은 서블릿/JSP API를 위한 artifact는 provided 범위를 갖는 반면에 Jetty 자체를 임베딩해서 실행하기 위한 artifact는 test 범위를 갖는다는 것이다. test 범위를 갖도록 한 이유는 Jetty 임베딩을 ATDD를 위한 용도로만 사용하기 때문이다.

Jetty 서버 임베딩으로 실행하기

Maven 프로젝트 구조에서 Jetty 서버를 임베딩으로 실행하고 종료하는데 사용된 코드는 다음과 같다.

public class JettyServer {

    private static Server server;
    
    public static void start() throws Exception {
        server = new Server(9090);

        WebAppContext context = new WebAppContext();
        context.setResourceBase("src/main/webapp");
        context.setContextPath("/goodjob");
        context.setParentLoaderPriority(true);

        server.setHandler(context);
        
        server.start();
    }

    public static void stop() throws Exception {
        server.stop();
    }
}

ATDD를 수행하는 코드에서는 다음과 같이 픽스처 구성시 JettyServer.start() 메서드를 이용해서 Jetty 서버를 임베딩해서 실행하고, 테스트 완료 후 JettyServer.stop() 메서드를 이용해서 Jetty 서버를 중지시켜주면 된다.

public class EndToEndTestBase {

    @BeforeClass
    public static void init() throws Exception {
        JettyServer.start();
    }

    @AfterClass
    public static void close() throws Exception {
        JettyServer.stop();
    }

}

일단, Jetty 서버를 임베딩으로 실행하면 http://localhost:9090/goodjob/authentication/login 과 같은 URL을 이용해서 실제 기능 테스트를 수행할 수 있다. 예를 들어, 웹 기능 테스트를 위한 코드는 아래와 같은 구성을 갖게 된다.

public class AllTeamsSummaryReportEndToEndTest extends EndToEndTestBase {

    @BeforeClass
    public static void initData() throws Exception {
        // 테스트 목적을 위한 데이터 초기화
        ...
    }

    @Test
    public void queryAllTeamsWeekSummaryReport() throws Throwable {
        // HtmlUnit이나 HttpClient와 같은 라이브러리를 이용해서
        // http://localhost:9090/goodjob/testurl 등 테스트 URL에 연결하고
        // 그 결과를 검증하는 코드 삽입
    }

}


출처 - http://javacan.tistory.com/entry/Jetty-Embedding-In-Maven-Project








jetty embedding


jetty를 embed해서 사용하는 방법에 대해서 쉽게 따라해 볼 수 있는 페이지이다. 

링크 : http://wiki.eclipse.org/Jetty/Tutorial/Jetty_HelloWorld


따라해보기위해서는 물론 java가 설치되어있어야한다. 

jetty 라이브러리를 다운로드하는 방법이다. 여기서는 jetty의 모든 class가 들어있는 jar를 다운로드한다. 

mkdir Demo
cd Demo
JETTY_VERSION=7.0.2.v20100331
wget -U none http://repo1.maven.org/maven2/org/eclipse/jetty/aggregate/jetty-all/$JETTY_VERSION/jetty-all-$JETTY_VERSION.jar
wget -U none http://repo1.maven.org/maven2/javax/servlet/servlet-api/2.5/servlet-api-2.5.jar



라이브러리를 다운로드 한 directory에 아래와 같은 java코드를 작성한다. 

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
 
import java.io.IOException;
 
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
 
public class HelloWorld extends AbstractHandler
{
    public void handle(String target,
                       Request baseRequest,
                       HttpServletRequest request,
                       HttpServletResponse response) 
        throws IOException, ServletException
    {
        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);
        response.getWriter().println("<h1>Hello World</h1>");
    }
 
    public static void main(String[] args) throws Exception
    {
        Server server = new Server(8080);
        server.setHandler(new HelloWorld());
 
        server.start();
        server.join();
    }
}


아래와 같이 클래스패스에 다운로드 받은 jar를 알려주고 컴파일 한다.

javac -cp servlet-api-2.5.jar:jetty-all-$JETTY_VERSION.jar HelloWorld.java


컴파일된 HelloWorld를 실행하면 서버가 뜬다. 

java -cp .:servlet-api-2.5.jar:jetty-all-$JETTY_VERSION.jar HelloWorld


난 20108포트로 띄웠다. 




브라우저로 접근한 모습



출처 - http://the-earth.tistory.com/149






September 21, 2010

How to embed Jetty Server

« Track window and widget events with AT-SPI | Main | AutoFS - Auto-Mount of Hard Drives »

The Jetty J2EE webcontainer represents a highly modularized server application. Because of that you are able to start the web server directly in Java code. For example that allows developers to deploy Servlets, JSP pages and WAR files within JUnit tests or use the webcontainer directly for other issues. The following example shows basically how to start and configure Jetty. 



package org.developers.blog.jetty.embedded;

import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.webapp.WebAppContext;

public class JettyExample {

    public static void main(String[] args) throws Exception {
        Server server = new Server();

        Connector connector = new SelectChannelConnector();
        connector.setPort(8080);
        connector.setHost("127.0.0.1");
        server.addConnector(connector);

        WebAppContext wac = new WebAppContext();
        wac.setContextPath("/");
        //expanded war or path of war file
        wac.setWar("./src/main/resources/web");
        server.addHandler(wac);
        server.setStopAtShutdown(true);

        //another way is to use an external jetty configuration file
        //XmlConfiguration configuration =
        //new XmlConfiguration(new File("/path/jetty-config.xml").toURL());
        //configuration.configure(server);

        server.start();
    }


출처 - http://developers-blog.org/blog/default/2010/09/21/How-to-embedd-Jetty-Server






Jetty는 Jetty Embeding에서 포스팅한 것 처럼 프로그램에 임베딩이 가능한 Web Server/라이브러리이다.

요즘 Spring에 맛을 들인 후 여기저기 뒤적뒤적 하고 있는데... Spring과 Jetty를 통합하는 예제를 우연찮게 발견했다.

Christopher J. Stehno라는 분의 포스팅을 보면 매우 쉽고 간결하게 통합할 수 있는 예제가 있다. Spring의 위력을 절감하게 되는 부분이다.

- Spring 설정

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="server.Server" class="org.mortbay.jetty.Server" destroy-method="stop">
        <property name="threadPool">
            <bean class="org.mortbay.thread.QueuedThreadPool">
                <property name="maxThreads" value="100" />
            </bean>
        </property>
        <property name="connectors">
            <list>
                <bean class="org.mortbay.jetty.nio.SelectChannelConnector">
                    <property name="port" value="8080" />
                    <property name="maxIdleTime" value="30000" />
                </bean>
            </list>
        </property>
        <property name="handler">
            <bean class="org.mortbay.jetty.handler.HandlerCollection">
                <property name="handlers">
                    <list>
                        <ref local="server.ContextHandlerCollection" />
                        <bean class="org.mortbay.jetty.handler.DefaultHandler" />
                        <bean class="org.mortbay.jetty.handler.RequestLogHandler">
                            <property name="requestLog">
                                <bean class="org.mortbay.jetty.NCSARequestLog">
                                    <constructor-arg value="cfg/logs/jetty-yyyy_mm_dd.log" />
                                    <property name="extended" value="false"/>
                                </bean>
                            </property>
                        </bean>
                    </list>
                </property>
            </bean>
        </property>

        <property name="userRealms">
            <list>
                <bean class="org.mortbay.jetty.security.HashUserRealm">
                    <property name="name" value="Test Realm" />
                    <property name="config" value="cfg/etc/realm.properties" />
                </bean>
            </list>
        </property>

        <property name="stopAtShutdown" value="true" />
        <property name="sendServerVersion" value="true"/>
    </bean>

    <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetObject" ref="server.Server" />
        <property name="targetMethod" value="addLifeCycle" />
        <property name="arguments">
            <list><ref local="server.ContextDeployer" /></list>
       </property>
    </bean>

    <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetObject" ref="server.Server" />
        <property name="targetMethod" value="addLifeCycle" />
        <property name="arguments">
            <list><ref local="server.WebAppDeployer" /></list>
       </property>
    </bean>

    <bean id="server.ContextHandlerCollection" class="org.mortbay.jetty.handler.ContextHandlerCollection" />

    <bean id="server.ContextDeployer" class="org.mortbay.jetty.deployer.ContextDeployer">
        <property name="contexts" ref="server.ContextHandlerCollection" />
        <property name="configurationDir">
            <bean class="org.mortbay.resource.FileResource">
                <constructor-arg value="file://./cfg/contexts" />
            </bean>
        </property>
        <property name="scanInterval" value="1" />
    </bean>

    <bean id="server.WebAppDeployer" class="org.mortbay.jetty.deployer.WebAppDeployer">
        <property name="contexts" ref="server.ContextHandlerCollection" />
        <property name="webAppDir" value="cfg/webapps" />
        <property name="parentLoaderPriority" value="false" />
        <property name="extract" value="true" />
        <property name="allowDuplicates" value="false" />
        <property name="defaultsDescriptor" value="cfg/etc/webdefault.xml" />
    </bean>
</beans>

- Main Class
public class Main {
    public static void main(String[] args) throws Exception {
        ApplicationContext context = new FileSystemXmlApplicationContext("cfg/server-context.xml");
        Server server = (Server)context.getBean("server.Server");
        server.start();
        server.join();
    }
}

여기서 설정 몇가지만 변경해 주면... 웹서버가 만들어진다.
기존에 만들었던 Embed된 소스에 즉시 적용해 봐야겠다.


출처 - http://pigmon.tistory.com/157






Posted by linuxism
,


가볍고 빠릿빠릿한 서버인 제티를 이클립스 안에서 동작하도록 설정하겠습니다.
저는 WebSocket을 쓰기 위해서 제티를 선택하였습니다.
(제티에서 WebSocket을 사용할 수 있는 인터페이스가 지원됩니다.)

검색을 해보니 메이븐의 플러그인으로 많이 사용을 하는 것 같은데
저는 메이븐 없이 사용하고 싶어서;;

준비물 : Eclipse Helios (Jetty WTP 플러그인이 Helios 버전만 지원)
http://eclipse.org/downloads/packages/release/helios/sr2

1. Jetty를 설치합니다.
다운로드 : http://download.eclipse.org/jetty/ 
버전은 7.2.0 RC 버전을 다운받습니다.


이클립스, Jetty, Jetty Plugin가 서로간의 환경을 많이 타는 것 같습니다.
왜인지 저의 경우에는 7.2버전으로 해야 제대로 실행이 되더군요.
다른 버전으로 할 때는 Dynamic Web Project 생성 시 런타임이 보이질 않았습니다.

압축 파일을 받고 적당한 곳에 압축을 풉니다.

2. 이클립스를 실행하고 Help > Install New Software 에서
제티 어댑터 플러그인을 설치합니다.


주소 : http://download.eclipse.org/jetty/updates/jetty-wtp


설치를 마치고 이클립스를 재실행합니다.

3. 이클립스의 서버 탭에서 제티 서버를 생성합니다.


설치한 제티의 경로를 지정해줍니다.


4. 이제 제티에서 실행할 웹프로젝트를 제티에 추가합니다.
Target Runtime을 제티로, Dynamic Web Module Version은 2.5로 지정합니다.

프로젝트를 생성하고..


제티에 추가시킵니다.



5. 서버 실행!!



단지 제티를 이클립스에서 실행하기 위해 혼자 시행착오를 많이 겪었습니다 ^^;
이클립스, 제티, 제티 플러그인의 버전을 계속 바꿔가며..
중간에는 제티 플러그인의 버그 때문에 또 삽질을 ㅜㅜ

그래도 마지막에 보이는 Hello Jetty!!는 뿌듯하죠.
더 자세한 매뉴얼은 http://wiki.eclipse.org/Jetty_WTP_Plugin 의 Helpful Page를 확인하시면 되겠습니다.

다음에는 제티에서 웹소켓 서블릿 / 클라이언트를 만들어보겠습니다.


출처 - http://messier219.tistory.com/48






  제티는 톰캣과 같이 웹 애플리케이션중 하나로써 가볍고, 웹 소켓을 지원하다는 이유로 사용하게 되었습니다. 이클립스에서 제티 플러그인과 웹 서버를 설치하고, Dynamic web project와 연동하는 법을 써 보겠습니다.

주의 

Eclipse Java EE 버전으로 설치되어 있어야 합니다. http://www.eclipse.org/downloads/

여기서는 Eclipse Indigo 버전으로 설치했습니다.


제티 설치

  • 제티 이클립스 플러그인 설치

이클립스의 Help - Install New Software를 누르면 나오는 다이얼로그에서 Add 버튼을 눌러

플러그인 주소를 추가해줍시다.

Location : http://download.eclipse.org/jetty/updates/jetty-wtp


잠시후 나오는 플러그인을 설치합시다. 다 되면 재시작 하라고 나오는데 재시작하면 플러그인 설치는 완료됩니다.


  • 제티 서버 설치

http://download.eclipse.org/jetty/ 여기서 제티를 받습니다. zip 파일로 된것을 받습니다.

현재 최신버전인 Stable 8.1.2.v20120308 버전으로 설치했습니다.

받은 zip 파일을 적당한 위치에 압축을 풀고 ( 저는 eclipse 가 설치된 폴더 아래에 위치했습니다. ) 

이클립스를 켜서 서버를 추가해봅시다.

이클립스의 아래쪽 보면 서버 탭이 있는데 처음 서버를 설치하는 것이면 아래와 같이 되있을겁니다. 링크를 클릭해서 서버 설치 위자드를 실행합시다.



저는 제티 8.1 버전 서버를 아래 그림과 같이 설정해주었습니다.





Browser를 눌러 제티 zip 파일이 압축 풀린 경로를 설정해 줍시다.


제티 웹 서버가 생성되었습니다.




Dynamic Web Service 프로젝트 생성 및 제티 연동

아래와 같이 프로젝트를 생성해줍시다.





index.jsp를 만듭니다.





적당히 jsp 페이지를 만듭니다.



이클립스의 서버탭에서 제티 서버를 더블클릭 - Modules 탭에서 Add Web Module 버튼을 클릭해 방금 생성한 프로젝트와 연결합니다.


JettyTest 프로젝트를 컨트롤+F11 로 실행합니다. 다음과 같은 과정으로 실행해줍니다.



java.lang.ClassNotFoundException: org.objectweb.asm.ClassVisitor 에러가 날 경우

서버탭에서 제티 서버를 더블클릭하면 나오는 창에서 Open launch configuration을 클릭합시다.


ClassPath 탭에서 위의 에러난 클래스가 있는 패키지를 추가해주면 됩니다.



....\jetty-distribution-8.1.2.v20120308\lib\annotations 경로에 있는 jar 파일을 추가하면 됩니다.

다시 실행해서 확인해 줍니다.


org.apache.jasper.JasperException: PWC6345: There is an error in invoking javac.  A full JDK (not just JRE) is required 에러가 날 경우

JDK로 설정되야 되는데 JRE로 설정되어 있어서 나오는 에러입니다.

이클립스의 메뉴에서 Window-Preferances로 들어가서 Java-Installed JREs로 들어갑시다.



JRE를 선택하고 Edit버튼을 누릅니다.




JRE설정을 JDK로 바꿉니다.

이클립스를 재시작한 후 제대로 동작하는지 확인합시다.


실행 결과


여기까지 JSP와 Jetty 서버를 연동하는 과정을 살펴봤습니다.


출처 - http://togalaxy.tistory.com/entry/Jetty-JSP-Eclipse-%EC%97%B0%EB%8F%99










'Web > WAS' 카테고리의 다른 글

jetty - maven 연동  (0) 2012.11.21
jetty - Servlet 컨테이너 임베딩(Embeding)  (0) 2012.11.20
jetty 설치 및 실행  (0) 2012.11.10
웹 애플리케이션 서버(Web Application Server; WAS)  (0) 2012.11.09
tomcat - The Context Container  (0) 2012.05.26
Posted by linuxism
,



This chart shows the most common display resolutions, with the color of each resolution type indicating the display ratio (e.g., red indicates a 4:3 ratio)


The display resolution of a digital televisioncomputer monitor or display device is the number of distinct pixels in each dimension that can be displayed. It can be an ambiguous term especially as the displayed resolution is controlled by different factors in cathode ray tube (CRT), Flat panel display which includes Liquid crystal displays, or projection displays using fixed picture-element (pixel) arrays.

It is usually quoted as width × height, with the units in pixels: for example, "1024 × 768" means the width is 1024 pixels and the height is 768 pixels. This example would normally be spoken as "ten twenty-four by seven sixty-eight" or "ten twenty-four by seven six eight".

One use of the term “display resolution” applies to fixed-pixel-array displays such asplasma display panels (PDPs), liquid crystal displays (LCDs), digital light processing(DLP) projectors, or similar technologies, and is simply the physical number of columns and rows of pixels creating the display (e.g., 1920 × 1080). A consequence of having a fixed-grid display is that, for multi-format video inputs, all displays need a "scaling engine" (a digital video processor that includes a memory array) to match the incoming picture format to the display.

Note that for broadcast television standards the use of the word resolution here is a misnomer, though common. The term “display resolution” is usually used to mean pixel dimensions, the number of pixels in each dimension (e.g., 1920 × 1080), which does not tell anything about the pixel density of the display on which the image is actually formed: broadcast television resolution properly refers to the pixel density, the number of pixels perunit distance or area, not total number of pixels. In digital measurement, the display resolution would be given in pixels per inch. In analog measurement, if the screen is 10 inches high, then the horizontal resolution is measured across a square 10 inches wide. This is typically stated as "lines horizontal resolution, per picture height;"[1] for example, analog NTSC TVs can typically display about 340 lines of "per picture height" horizontal resolution from over-the-air sources, which is equivalent to about 440 total lines of actual picture information from left edge to right edge.[1]

Contents

  [hide

[edit]Considerations

1080p progressive scan HDTV, which uses a 16:9 ratio.

Some commentators also use display resolution to indicate a range of input formats that the display's input electronics will accept and often include formats greater than the screen's native grid size even though they have to be down-scaled to match the screen's parameters (e.g., accepting a 1920 × 1080 input on a display with a native 1366 × 768 pixel array). In the case of television inputs, many manufacturers will take the input and zoom it out to "overscan" the display by as much as 5% so input resolution is not necessarily display resolution.

The eye's perception of display resolution can be affected by a number of factors – see image resolution and optical resolution. One factor is the display screen's rectangular shape, which is expressed as the ratio of the physical picture width to the physical picture height. This is known as the aspect ratio. A screen's physical aspect ratio and the individual pixels' aspect ratio may not necessarily be the same. An array of 1280 × 720 on a 16:9 display has square pixels, but an array of 1024 × 768 on a 16:9 display has rectangular pixels.

An example of pixel shape affecting "resolution" or perceived sharpness: displaying more information in a smaller area using a higher resolution makes the image much clearer or "sharper". However, most recent screen technologies are fixed at a certain resolution; making the resolution lower on these kinds of screens will greatly decrease sharpness, as an interpolation process is used to "fix" the non-native resolution input into the display's native resolution output.

While some CRT-based displays may use digital video processing that involves image scaling using memory arrays, ultimately "display resolution" in CRT-type displays is affected by different parameters such as spot size and focus, astigmatic effects in the display corners, the color phosphor pitch shadow mask (such as Trinitron) in color displays, and the video bandwidth.

[edit]Interlacing versus progressive scan

A 16:9-ratio television from the early 2000s.
Difference between screen sizes in some common devices.

Analog television systems use interlaced video scanning with two sequential scans called fields (50 PAL or 60 NTSC fields per second), one with the odd numbered scan lines, the other with the even numbered scan lines to give a complete picture or frame (25 or 30 frames per second). This is done to save transmission bandwidth but a consequence is that in picture tube (CRT) displays, the full vertical resolution cannot be realized. For example, the maximum detail in the vertical direction would be for adjacent lines to be alternately black then white. This is not as great a problem in a progressive video display but an interlace display will have an unacceptable flicker at the slower frame rate. This is why interlace is unacceptable for fine detail such as computer word processing or spreadsheets. For television it means that if the picture is intended for interlace displays the picture must be vertically filtered to remove this objectionable flicker with a reduction of vertical resolution. According to the Kell factor the reduction is to about 85%, so a 576 line PAL interlace display only has about 480 lines vertical resolution, and a 486 line NTSC interlace display has a resolution of approximately 410 lines vertical. Similarly, 1080i digital interlaced video (the "i" in 1080i refers to "interlaced") would need to be filtered to about 910 lines for an interlaced display, although a fixed pixel display (such as LCD television) eliminates the inaccuracies of scanning, and thus can achieve Kell factors as high as 95% or 1020 lines. It should be noted that the Kell Factor equally applies to progressive scan. Using a Kell factor of 0.9, a 1080p HDTV video system using a CCD camera and an LCD or plasma display will only have 1728 × 972 lines of resolution.

Fixed pixel array displays such as LCDs, plasmas, DLPs, LCoS, etc. need a "video scaling" processor with frame memory, which, depending on the processing system, effectively converts an incoming interlaced video signal into a progressive video signal. A similar process occurs in a PC and its display with interlaced video (e.g., from a TV tuner card). The downside is that interlace motion artifacts are almost impossible to remove resulting in horizontal "toothed" edges on moving objects.

In analog connected picture displays such as CRT TV sets, the horizontal scanlines are not divided into pixels, but by the sampling theorem, the bandwidth of the luma and chroma signals implies a horizontal resolution. For television, the analog bandwidth for luminance in standard definition can vary from 3 MHz (approximately 330 lines edge-to-edge; VHS) to 4.2 MHz (440 lines; live analog) up to 7 MHz (660 lines; DVD). In high definition the bandwidth is 37 MHz (720p/1080i) or 74 MHz (1080p/60).

[edit]Overscan and underscan

Most television display manufacturers "overscan" the pictures on their displays (CRTs and PDPs, LCDs etc.), so that the effective on-screen picture may be reduced from 720 × 576(480) to 680 × 550(450), for example. The size of the invisible area somewhat depends on the display device. HD televisions do this as well, to a similar extent.

Computer displays including projectors generally do not overscan although many models (particularly CRT displays) allow it. CRT displays tend to be underscanned in stock configurations, to compensate the increasing distortions at the corners.

[edit]Current standards

[edit]Televisions

Televisions are of the following resolutions:

  • Standard-definition television (SDTV):
    • 480i (NTSC standard uses an analog system of 486i split into two interlaced fields of 243 lines)
    • 576i (PAL, 720 × 576 split into two interlaced fields of 288 lines)
  • Enhanced-definition television (EDTV):
  • High-definition television (HDTV):
    • 720p (1280 × 720 progressive scan)
    • 1080i (1920 × 1080 split into two interlaced fields of 540 lines)
    • 1080p (1920 × 1080 progressive scan)
  • Ultra-high-definition television (UHDTV)
    • 2160p (3840 × 2160 progressive scan)
    • 4320p (7680 × 4320 progressive scan)
    • 8640p (15360 x 8640 progressive scan)

[edit]Computer monitors

Computer monitors have higher resolutions than most televisions. As of July 2002, 1024 × 768 Extended Graphics Array was the most common display resolution.[2][3] Many web sites and multimedia products were re-designed from the previous 800 × 600 format to the layouts optimized for 1024 × 768.

The availability of inexpensive LCD monitors has made the 5:4 aspect ratio resolution of 1280 × 1024 more popular for desktop usage. Many computer users including CADusers, graphic artists and video game players run their computers at 1600 × 1200 resolution (UXGA) or higher if they have the necessary equipment. Other recently available resolutions include oversize aspects like 1400 × 1050 SXGA+ and wide aspects like 1280 × 800 WXGA, 1440x900 WXGA+, 1680 × 1050 WSXGA+, and 1920 × 1200 WUXGA. A new more-than-HD resolution of 2560 × 1600 WQXGA was released in 30" LCD monitors in 2007. In 2010, 27" LCD monitors with the resolution 2560 × 1440 were released by multiple manufacturers including Apple,[4] and in 2012 Apple introduced a 2880 × 1800 display on the MacBook Pro.[5] Panels for professional environments, such as medical use and air traffic control, support resolutions up to 4096 × 2160.[6][7][8]

Most common display resolutions in the first half of 2012
AcronymAspect ratioWidth (px)Height (px) % of Steam users % of web users
VGA4:364048000.02n/a
SVGA4:380060000.1701.03
WSVGA17:10102460000.3102.25
XGA4:3102476805.5318.69
XGA+4:3115286400.8701.55
WXGA16:9128072001.5101.54
WXGA5:31280768n/a01.54
WXGA16:10128080004.2512.97
SXGA– (UVGA)4:3128096000.7200.72
SXGA5:41280102410.6607.49
HD~16:9136076802.3602.28
HD~16:9136676817.1919.14
SXGA+4:31400105000.18n/a
WXGA+16:10144090007.6006.61
HD+16:9160090006.8203.82
UXGA4:31600120000.53n/a
WSXGA+16:101680105010.2603.66
FHD16:91920108025.0405.09
WUXGA16:101920120003.6501.11
QWXGA16:92048115200.13n/a
WQHD16:92560144000.7200.36
WQXGA16:102560160000.19n/a
3:47681024n/a01.93
16:91093614n/a00.63
~16:91311737n/a00.35
Other01.2907.25
Notes
The Steam user statistics were gathered from users of the Steam network in its hardware survey of May 2012.[9]
The web user statistics were gathered from visitors to three million websites, normalised to counteract geolocational bias. Covers the five month period from January to May 2012.[10]
The numbers are not representative of computer users in general.

When a computer display resolution is set higher than the physical screen resolution (native resolution), some video drivers make the virtual screen scrollable over the physical screen thus realizing a two dimensional virtual desktop with its viewport. Most LCD manufacturers do make note of the panel's native resolution as working in a non-native resolution on LCDs will result in a poorer image, due to dropping of pixels to make the image fit (when using DVI) or insufficient sampling of the analog signal (when using VGA connector). Few CRT manufacturers will quote the true native resolution since CRTs are analog in nature and can vary their display from as low as 320 × 200 (emulation of older computers or game consoles) to as high as the internal board will allow, or the image becomes too detailed for the vacuum tube to recreate (i.e. analog blur). Thus CRTs provide a variability in resolution that LCDs can not provide (LCDs have fixed resolution).

In recent years the popularity of 16:9 aspect ratios has resulted in more notebook display resolutions adhering to this aspect ratio. 1366 × 768 (HD) has become popular for most notebook sizes, while 1600 × 900 (HD+) and 1920 × 1080 (FHD) are available for larger notebooks.

As far as digital cinematography is concerned, video resolution standards depend first on the frames' aspect ratio in the film stock (which is usually scanned for digital intermediate post-production) and then on the actual points' count. Although there is not a unique set of standardized sizes, it is commonplace within the motion picture industry to refer to "nK" image "quality", where n is a (small, usually even) integer number which translates into a set of actual resolutions, depending on the film format. As a reference consider that, for a 4:3 (around 1.33:1) aspect ratio which a film frame (no matter what is its format) is expected to horizontally fit inn is the multiplier of 1024 such that the horizontal resolution is exactly 1024·n points. For example, 2K reference resolution is 2048 × 1536 pixels, whereas 4K reference resolution is 4096 × 3072 pixels. Nevertheless, 2K may also refer to resolutions like 2048 × 1556 (full-aperture), 2048 × 1152 (HDTV, 16:9 aspect ratio) or 2048 × 872 pixels (Cinemascope, 2.35:1 aspect ratio). It is also worth noting that while a frame resolution may be, for example, 3:2 (720 × 480 NTSC), that is not what you will see on-screen (i.e. 4:3 or 16:9 depending on the orientation of the rectangular pixels).

[edit]Evolution of standards

The blue borders in the overscan region would have been barely visible.
640 × 200 – monitor vs. television

Many personal computers introduced in the late 1970s and the 1980s were designed to use television sets as their display devices, making the resolutions dependent on the television standards in use, including PAL and NTSC. Picture sizes were usually limited to ensure the visibility of all the pixels in the major television standards and the broad range of television sets with varying amounts of overscan. The actual drawable picture area was therefore somewhat smaller than the whole screen, and was usually surrounded by a static-colored border (see image to right). Also, the interlace scanning was usually omitted in order to provide more stability to the picture, effectively halving the vertical resolution in progress. 160 × 200, 320 × 200 and 640 × 200 on NTSC were relatively common resolutions in the era (224, 240 or 256 scanlines were also common). In the IBM PC world, these resolutions came to be used by 16-color EGA video cards.

One of the drawbacks of using a classic television is that the computer display resolution is higher than the TV could decode. Chroma resolution for NTSC/PAL televisions are bandwidth-limited to a maximum 1.5 megahertz, or approximately 160 pixels wide, which led to blurring of the color for 320- or 640-wide signals, and made text difficult to read (see second image to right). Many users upgraded to higher-quality televisions with S-Video or RGBI inputs that helped eliminate chroma blur and produce more legible displays. The earliest, lowest cost solution to the chroma problem was offered in the Atari 2600 Video Computer System and the Apple II+, both of which offered the option to disable the color and view a legacy black-and-white signal. On the Commodore 64, the GEOS mirrored the Mac OS method of using black-and-white to improve readability.

4096 color interlaced image on anAmiga from 1989.
16-color (top) and 256-color (bottom) progressive from 1980s VGA card. Ditheringis used to overcome color limitations.

The 640 × 400i resolution (720 × 480i with borders disabled) was first introduced by home computers such as the Commodore Amiga and (later) Atari Falcon. These computers used interlace to boost the maximum vertical resolution. These modes were only suited to graphics or gaming, as the flickering interlace made reading text in word processor, database, or spreadsheet software difficult. (Modern game consoles solve this problem by pre-filtering the 480i video to a lower resolution. For example, Final Fantasy XII suffers from flicker when the filter is turned off, but stabilizes once filtering is restored. The computers of the 1980s lacked sufficient power to run similar filtering software.)

The advantage of a 720 × 480i overscanned computer was an easy interface with interlaced TV production, leading to the development of Newtek's Video Toaster. This device allowed Amigas to be used for CGI creation in various news departments (example: weather overlays), drama programs such as NBC's seaQuest, WB's Babylon 5, and early computer-generated animation by Disney for the Little MermaidBeauty and the Beast, and Aladdin.

In the PC world, the IBM PS/2 VGA and MCGA (multi-color) on-board graphics chips used a non-interlaced (progressive) 640 × 480 × 16 color resolution that was easier to read and thus more-useful for office work. It was the standard resolution from 1990 to around 1996.[citation needed] The standard resolution was 800 × 600 until around 2000. Microsoft Windows XP, released in 2001, was designed to run at 800 × 600 minimum although it is possible to select the original 640 × 480 in the Advanced Settings window.LinuxFreeBSD, and most Unix variants use the X Window System and can run at any desired resolution as long as the displayand video card support it, and tend to go a long way towards being usable even on small screens, though not all applications may support very low display resolutions.

Programs designed to mimic older hardware such as Atari, Sega, or Nintendo game consoles (emulators) when attached to multiscan CRTs, routinely use much lower resolutions such as 160 × 200 or 320 × 400 for greater authenticity.

[edit]Commonly used

The list of common display resolutions article lists the most commonly used display resolutions for computer graphics, television, films, and video conferencing.

[edit]See also

[edit]References

  1. a b Robin, Michael (2005-04-01). "Horizontal resolution: Pixels or lines". Broadcast Engineering. Retrieved 2012-07-22.
  2. ^ "Higher screen resolutions more popular for exploring the internet according to OneStat.com". OneStat.com. 2002-07-24. Archived from the original on 2011-07-16. Retrieved 2012-07-22.
  3. ^ "Screen resolution 800 × 600 significantly decreased for exploring the Internet according to OneStat.com". OneStat.com. 2007-04-18. Archived from the original on 2011-07-16. Retrieved 2012-07-22.
  4. ^ Nelson, J.R. (2010-07-27). "Apple Releases New Cinema Display: 27 inches, 2560x1440 Resolution". DesktopReview. Retrieved 2012-07-22.
  5. ^ "Apple announces iOS 6, MacBook with retina display at WWDC 2012". The Times of India. 2012-06-11. Retrieved 2012-07-22.
  6. ^ "EIZO DuraVision FDH3601"
  7. ^ "EYE-LCD 6400-4K"
  8. ^ "Optik View DC801,DC802"
  9. ^ "Primary Display Resolution, The Steam hardware survey."
  10. ^ StatCounter Global Statistics — Cumulative worldwide figures for the three months November 2011 to January 2012.
  • Sony SXRD 4K Projector (SRXR110) resolution retrieved from [1]

[edit]External links


출처 - http://en.wikipedia.org/wiki/Display_resolution








Posted by linuxism
,