2.5. 퀵스타트 예제 검토


2.5.1. helloworld 빠른 시작 살펴보기

helloworld 빠른 시작에서는 JBoss EAP에 간단한 서블릿을 배포하는 방법을 보여줍니다. 비즈니스 로직은 서비스에 캡슐화되며, 이 논리는 CDI(Contexts and dependency Cryostat) 5.1로 제공되며 서블릿에 주입됩니다. 이 빠른 시작은 서버를 올바르게 구성하고 시작했는지 확인하는 시작점입니다.

명령줄을 사용하여 이 빠른 시작을 빌드하고 배포하는 자세한 지침은 helloworld 빠른 시작 디렉터리의 루트에 있는 README.html 파일에서 확인할 수 있습니다. 이 문서에서는 JBoss Tools를 사용하여 빠른 시작을 실행하는 방법을 설명하고 JBoss Tools를 설치하고 Maven을 구성하고 helloworld 빠른 시작을 성공적으로 실행하는 방법을 설명합니다.

참고

JBoss Tools는 JBoss EAP 8.0에서 더 이상 사용되지 않습니다. 이 기능에 대한 개선 사항은 없으며 향후 릴리스에서 제거될 수 있습니다.

2.5.1.1. 디렉터리 구조 검사

helloworld 빠른 시작 코드는 QUICKSTART_HOME/helloworld/ 디렉터리에서 확인할 수 있습니다. helloworld 빠른 시작은 서블릿 및 CDI 8080으로 구성됩니다. 애플리케이션의 article -INF/ 디렉터리에는 버전 번호 1.1 및 all 의 empty- discovery-mode 가 있는 beans.xml 파일도 포함되어 있습니다. 이 마커 파일은 WAR를 8080 아카이브로 식별하고 JBoss EAP에 이 애플리케이션에서 빈을 찾고 CDI를 활성화하도록 지시합니다.

src/main/webapp/ 디렉터리에는 quickstart의 파일이 포함되어 있습니다. 이 예제의 모든 구성 파일은 beans.xml 파일을 포함하여 src /main/webapp/ 내의 website-INF / 디렉터리에 있습니다. src/main/webapp/ 디렉터리에는 간단한 메타 새로 고침을 사용하여 사용자의 브라우저를 http://localhost:8080/helloworld/HelloWorld 에 있는 서블릿으로 리디렉션하는 index.html 파일도 포함되어 있습니다. 빠른 시작에는 web.xml 파일이 필요하지 않습니다.

2.5.1.2. HelloWorldServlet.java 코드 검토

패키지 선언 및 가져오기는 이러한 목록에서 제외되었습니다. 전체 목록은 빠른 시작 소스 코드에서 사용할 수 있습니다.

참고

JBoss Tools는 JBoss EAP 8.0에서 더 이상 사용되지 않습니다. 이 기능에 대한 개선 사항은 없으며 향후 릴리스에서 제거될 수 있습니다.

사전 요구 사항

  • JBoss 툴 설치. 자세한 내용은 JBoss Tools 설치 가이드의 설치 방법을 참조하십시오.
  • helloworld 빠른 시작을 실행합니다.
  • 웹 브라우저를 열고 http://localhost:8080/helloworld 에서 애플리케이션에 액세스하여 helloworld 빠른 시작이 JBoss EAP에 성공적으로 배포되었는지 확인합니다.

프로세스

  1. HelloWorldServlet 코드를 검토합니다.

    HelloWorldServlet.java 파일은 src/main/java/org/jboss/as/quickstarts/helloworld/ 디렉터리에 있습니다. 이 서블릿은 브라우저에 정보를 전송합니다.

    예: HelloWorldServlet 클래스 코드

    42 @SuppressWarnings("serial")
    43 @WebServlet("/HelloWorld")
    44 public class HelloWorldServlet extends HttpServlet {
    45
    46     static String PAGE_HEADER = "<html><head><title>helloworld</title></head><body>";
    47
    48     static String PAGE_FOOTER = "</body></html>";
    49
    50     @Inject
    51	   HelloService helloService;
    52
    53     @Override
    54     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    55         resp.setContentType("text/html");
    56         PrintWriter writer = resp.getWriter();
    57         writer.println(PAGE_HEADER);
    58         writer.println("<h1>" + helloService.createHelloMessage("World") + "</h1>");
    59         writer.println(PAGE_FOOTER);
    60         writer.close();
    61     }
    62
    63 }

2.5.1.2.1. HelloWorldServlet 세부 정보

이 서블릿은 브라우저로 정보를 보냅니다.

Expand
표 2.1. HelloWorldServlet 세부 정보
라인참고

43

필요한 것은 @WebServlet 주석을 추가하고 서블릿에 액세스하는 데 사용되는 URL에 대한 매핑을 제공하는 것입니다.

46-48

모든 웹 페이지에는 올바르게 구성된 HTML이 필요합니다. 이 빠른 시작에서는 정적 문자열을 사용하여 최소 헤더 및 footer 출력을 작성합니다.

50-51

이러한 줄은 실제 메시지를 생성하는 HelloService CDI 8080을 주입합니다. HelloService의 API를 변경하지 않는 한, 이 접근 방식을 통해 뷰 계층을 변경하지 않고 나중에 HelloService 구현을 변경할 수 있습니다.

58

이 줄은 서비스를 호출하여 "Hello World" 메시지를 생성하고 HTTP 요청에 씁니다.

  1. HelloService 코드를 검토합니다.

    HelloService.java 파일은 src/main/java/org/jboss/as/quickstarts/helloworld/ 디렉터리에 있습니다. 이 서비스는 단순히 메시지를 반환합니다. XML 또는 주석 등록이 필요하지 않습니다.

    예: HelloService 클래스 코드

    public class HelloService {
    
        String createHelloMessage(String name) {
            return "Hello " + name + "!";
        }
    }

2.5.2. 숫자별 퀵스타트 살펴보기

numberguess quickstart는 비대시적인 간단한 애플리케이션을 생성하고 JBoss EAP에 배포하는 방법을 보여줍니다. information is displayed using a Cryostat view and business logic is encapsulated in two CDI 빈. 숫자 별 빠른 시작에서는 1에서 100 사이의 숫자를 추측하려고 10 번 있습니다. 각 시도 후, 귀하의 추측이 너무 높은지 너무 낮은지 여부를 알려줍니다.

숫자 빠른 시작 코드는 QUICKSTART_HOME/ numberguess / 디렉토리에서 찾을 수 있습니다. 여기서 QUICKSTART_HOME 은 JBoss EAP 빠른 시작을 다운로드하여 압축을 해제한 디렉터리입니다. numberguess quickstart는 다수의 빈, 구성 파일,JSF(JSF) 뷰로 구성되며 WAR 모듈로 패키징됩니다.

명령줄을 사용하여 이 빠른 시작을 빌드하고 배포하는 자세한 지침은 numberguess quickstart 디렉터리의 루트에 있는 README.html 파일에서 확인할 수 있습니다. 다음 예제에서는 JBoss Tools를 사용하여 빠른 시작을 실행합니다.

참고

JBoss Tools는 JBoss EAP 8.0에서 더 이상 사용되지 않습니다. 이 기능에 대한 개선 사항은 없으며 향후 릴리스에서 제거될 수 있습니다.

2.5.2.1. 숫자 구성 파일 검사

이 예제의 모든 구성 파일은 퀵 스타트의 QUICKSTART_HOME/numbergues/src/main/webapp/ websites-INF/ 디렉터리에 있습니다.

사전 요구 사항

  • JBoss 툴 설치. 자세한 내용은 JBoss Tools 설치 가이드의 설치 방법을 참조하십시오.
  • numberguess quickstart를 실행합니다.
  • 웹 브라우저를 열고 이 URL에서 애플리케이션에 액세스하여 numberguess quickstart가 JBoss EAP에 성공적으로 배포되었는지 확인합니다. http://localhost:8080/numberguess.
참고

JBoss Tools는 JBoss EAP 8.0에서 더 이상 사용되지 않습니다. 이 기능에 대한 개선 사항은 없으며 향후 릴리스에서 제거될 수 있습니다.

프로세스

  1. faces-config.xml 파일을 검사합니다.

    이 빠른 시작에서는 faces-config.xml 파일 이름의 Cryostat 2.2 버전을 사용합니다. 표준 버전의 Telelet은 Cryostat 2.2의 기본 보기 처리기이므로 구성이 필요하지 않습니다. 이 파일은 root 요소로만 구성되며 애플리케이션에서 Cryostat를 사용하도록 설정해야 함을 나타내는 마커 파일일 뿐입니다.

    <faces-config version="2.2"
       xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
          http://xmlns.jcp.org/xml/ns/javaee
          http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
    
    </faces-config>
  2. beans.xml 파일을 검사합니다.

    beans.xml 파일에는 모든 의 버전 번호 1.1과 metrics -discovery-mode 가 포함되어 있습니다. 이 파일은 WAR를 빈 아카이브로 식별하는 마커 파일이며 JBoss EAP에 이 애플리케이션에서 빈을 찾고 CDI를 활성화하도록 지시합니다.

    <beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="
          http://xmlns.jcp.org/xml/ns/javaee
          http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
        bean-discovery-mode="all">
    </beans>
참고

이 빠른 시작에는 web.xml 파일이 필요하지 않습니다.

2.5.2.2. Cryostat 코드 검사

Cryostat는 소스 파일에 .xhtml 파일 확장자를 사용하지만 .jsf 확장자를 사용하여 렌더링된 보기를 제공합니다. home.xhtml 파일은 src/main/webapp/ 디렉터리에 있습니다.

예: Cryostat 소스 코드

19<html xmlns="http://www.w3.org/1999/xhtml"
20	xmlns:ui="http://java.sun.com/jsf/facelets"
21	xmlns:h="http://java.sun.com/jsf/html"
22	xmlns:f="http://java.sun.com/jsf/core">
23
24	<head>
25	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
26	<title>Numberguess</title>
27	</head>
28
29	<body>
30	<div id="content">
31		<h1>Guess a number...</h1>
32		<h:form id="numberGuess">
33
34		<!-- Feedback for the user on their guess -->
35	<div style="color: red">
36		<h:messages id="messages" globalOnly="false" />
37		<h:outputText id="Higher" value="Higher!"
38 		  rendered="#{game.number gt game.guess and game.guess ne 0}" />
39		<h:outputText id="Lower" value="Lower!"
40		   rendered="#{game.number lt game.guess and game.guess ne 0}" />
41	</div>
42
43	<!-- Instructions for the user -->
44	<div>
45	I'm thinking of a number between <span
46	id="numberGuess:smallest">#{game.smallest}</span> and <span
47	id="numberGuess:biggest">#{game.biggest}</span>. You have
48	#{game.remainingGuesses} guesses remaining.
49	</div>
50
51	<!-- Input box for the users guess, plus a button to submit, and reset -->
52	<!-- These are bound using EL to our CDI beans -->
53	<div>
54	Your guess:
55	<h:inputText id="inputGuess" value="#{game.guess}"
56		required="true" size="3"
57		disabled="#{game.number eq game.guess}"
58		validator="#{game.validateNumberRange}" />
59		<h:commandButton id="guessButton" value="Guess"
60			action="#{game.check}"
61			disabled="#{game.number eq game.guess}" />
62	</div>
63	<div>
64	<h:commandButton id="restartButton" value="Reset"
65	action="#{game.reset}" immediate="true" />
66	</div>
67	</h:form>
68
69	</div>
70
71	<br style="clear: both" />
72
73	</body>
74</html>

다음 행 번호는 JBoss Tools에서 파일을 볼 때 표시되는 행 번호입니다.

참고

JBoss Tools는 JBoss EAP 8.0에서 더 이상 사용되지 않습니다. 이 기능에 대한 개선 사항은 없으며 향후 릴리스에서 제거될 수 있습니다.

Expand
표 2.2. Cryostat 세부 정보
라인참고

36-40

이는 사용자에게 보낼 수 있는 메시지입니다: "Higher!" 및 "Lower!"

45-48

사용자가 추측할 때 추측할 수 있는 숫자의 범위가 작아집니다. 이 문장은 유효한 추측의 범위를 확인하기 위해 변경됩니다.

55-58

이 입력 필드는 value 표현식을 사용하여 metrics 속성에 바인딩됩니다.

58

유효성 검사기 바인딩은 사용자가 실수로 추측할 수 있는 범위 외부에서 번호를 입력하지 않도록 하는 데 사용됩니다. 유효성 검사기가 여기에 없는 경우 사용자는 경계가 없는 숫자에 추측을 사용할 수 있습니다.

59-61

사용자가 서버에 추측을 보낼 수 있는 방법이 있어야 합니다. 여기에서 8080의 작업 메서드에 바인딩합니다.

2.5.2.3. 숫자 클래스 파일을 검사합니다.

모든 숫자 빠른 시작 소스 파일은 QUICKSTART_HOME/ numberguess /src/main/java/org/jboss/as/quickstarts/numberguess/ 디렉토리에서 확인할 수 있습니다. 패키지 선언 및 가져오기는 이러한 목록에서 제외되었습니다. 전체 목록은 빠른 시작 소스 코드에서 사용할 수 있습니다.

프로세스

  1. Random.java Qualifier 코드 검토

    한정자는 두 빈 사이에 모호성을 제거하는 데 사용되며 둘 다 유형에 따라 주입할 수 있습니다. @Random 한정자는 임의의 숫자를 삽입하는 데 사용됩니다.

    @Target({ TYPE, METHOD, PARAMETER, FIELD })
    @Retention(RUNTIME)
    @Documented
    @Qualifier
    public @interface Random {
    
    }
  2. MaxNumber.java Qualifier 코드 검토

    @MaxNumber 한정자 는 허용되는 최대 수를 삽입하는 데 사용됩니다.

    @Target({ TYPE, METHOD, PARAMETER, FIELD })
    @Retention(RUNTIME)
    @Documented
    @Qualifier
    public @interface MaxNumber {
    }
  3. Generator.java 코드 검토

    Generator 클래스는 생산자 메서드를 통해 난수를 생성하여 동일한 값을 통해 최대 가능한 수를 노출합니다. 이 클래스는 애플리케이션 범위이므로 매번 다른 임의의 값을 얻지 못합니다.

    @SuppressWarnings("serial")
    @ApplicationScoped
    public class Generator implements Serializable {
    
        private java.util.Random random = new java.util.Random(System.currentTimeMillis());
    
        private int maxNumber = 100;
    
        java.util.Random getRandom() {
            return random;
        }
    
        @Produces
        @Random
        int next() {
            // a number between 1 and 100
            return getRandom().nextInt(maxNumber - 1) + 1;
        }
    
        @Produces
        @MaxNumber
        int getMaxNumber() {
            return maxNumber;
        }
    }
  4. game .java 코드 검토

    세션 범위의 game 클래스는 애플리케이션의 주요 진입점입니다. 게임 설정 또는 재설정, 사용자의 추측을 캡처 및 검증하고, Cryostats Message를 사용하여 사용자에게 피드백을 제공해야 합니다. 구성 후 라이프사이클 후 메서드를 사용하여 @Random Instance<Integer> metrics에서 임의의 번호를 검색하여 게임 초기화를 수행합니다.

    클래스의 @Named 주석을 확인합니다. 이 주석은 Jakarta Expression Language (이 경우 #{ game} )를 사용하여 Cryostat 뷰에 액세스할 수 있도록 하려면만 필요합니다.

    @SuppressWarnings("serial")
    @Named
    @SessionScoped
    public class Game implements Serializable {
    
        /**
         * The number that the user needs to guess
         */
        private int number;
    
        /**
         * The users latest guess
         */
        private int guess;
    
        /**
         * The smallest number guessed so far (so we can track the valid guess range).
         */
        private int smallest;
    
        /**
         * The largest number guessed so far
         */
        private int biggest;
    
        /**
         * The number of guesses remaining
         */
        private int remainingGuesses;
    
        /**
         * The maximum number we should ask them to guess
         */
        @Inject
        @MaxNumber
        private int maxNumber;
    
        /**
         * The random number to guess
         */
        @Inject
        @Random
        Instance<Integer> randomNumber;
    
        public Game() {
        }
    
        public int getNumber() {
            return number;
        }
    
        public int getGuess() {
            return guess;
        }
    
        public void setGuess(int guess) {
            this.guess = guess;
        }
    
        public int getSmallest() {
            return smallest;
        }
    
        public int getBiggest() {
            return biggest;
        }
    
        public int getRemainingGuesses() {
            return remainingGuesses;
        }
    
        /**
         * Check whether the current guess is correct, and update the biggest/smallest guesses as needed. Give feedback to the user
         * if they are correct.
         */
        public void check() {
            if (guess > number) {
                biggest = guess - 1;
            } else if (guess < number) {
                smallest = guess + 1;
            } else if (guess == number) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Correct!"));
            }
            remainingGuesses--;
        }
    
        /**
         * Reset the game, by putting all values back to their defaults, and getting a new random number. We also call this method
         * when the user starts playing for the first time using {@linkplain PostConstruct @PostConstruct} to set the initial
         * values.
         */
        @PostConstruct
        public void reset() {
            this.smallest = 0;
            this.guess = 0;
            this.remainingGuesses = 10;
            this.biggest = maxNumber;
            this.number = randomNumber.get();
        }
    
        /**
         * A JSF validation method which checks whether the guess is valid. It might not be valid because there are no guesses left,
         * or because the guess is not in range.
         *
         */
        public void validateNumberRange(FacesContext context, UIComponent toValidate, Object value) {
            if (remainingGuesses <= 0) {
                FacesMessage message = new FacesMessage("No guesses left!");
                context.addMessage(toValidate.getClientId(context), message);
                ((UIInput) toValidate).setValid(false);
                return;
            }
            int input = (Integer) value;
    
            if (input < smallest || input > biggest) {
                ((UIInput) toValidate).setValid(false);
    
                FacesMessage message = new FacesMessage("Invalid guess");
                context.addMessage(toValidate.getClientId(context), message);
            }
        }
    }
Red Hat logoGithubredditYoutubeTwitter

자세한 정보

평가판, 구매 및 판매

커뮤니티

Red Hat 문서 정보

Red Hat을 사용하는 고객은 신뢰할 수 있는 콘텐츠가 포함된 제품과 서비스를 통해 혁신하고 목표를 달성할 수 있습니다. 최신 업데이트를 확인하세요.

보다 포괄적 수용을 위한 오픈 소스 용어 교체

Red Hat은 코드, 문서, 웹 속성에서 문제가 있는 언어를 교체하기 위해 최선을 다하고 있습니다. 자세한 내용은 다음을 참조하세요.Red Hat 블로그.

Red Hat 소개

Red Hat은 기업이 핵심 데이터 센터에서 네트워크 에지에 이르기까지 플랫폼과 환경 전반에서 더 쉽게 작업할 수 있도록 강화된 솔루션을 제공합니다.

Theme

© 2026 Red Hat
맨 위로 이동