ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Spring] 스프링 MVC : Hello 예제 작성
    프로그래밍/Spring 2016. 7. 4. 14:59
    반응형

    다양한 종류의 웹프레임워크 중에서 국내 기업 환경에서 사용하기에 적합한 프레임워크중 하나가 스프링 MVC


    POM.xml파일은 다음의 설정 정보를 담음


    * 의존 모듈

    - 서블릿, JSP

    - 스프링 MVC 모듈 및 스프링 MVC가 필요로 하는 모듈들

    * 웹 테스트를 위한 서버 설정

    - 서블릿, JSP, JSTL 을 위한 의존 설정, 스프링 MVC실행을 위한 의존 설정

    - 메이븐 웹 프로젝트를 실행하기위한 플러그인 설정


    [POM.xml]

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>lee.lee</groupId>
        <artifactId>lee</artifactId>
        <name>Spring MVC 2</name>
        <packaging>war</packaging>
        <version>1.0.0-BUILD-SNAPSHOT</version>
        <properties>
            <java-version>1.6</java-version>
            <org.springframework-version>3.1.1.RELEASE</org.springframework-version>
            <org.aspectj-version>1.6.10</org.aspectj-version>
            <org.slf4j-version>1.6.6</org.slf4j-version>
        </properties>
        <dependencies>
            <!-- Spring -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${org.springframework-version}</version>
                <exclusions>
                    <!-- Exclude Commons Logging in favor of SLF4j -->
                    <exclusion>
                        <groupId>commons-logging</groupId>
                        <artifactId>commons-logging</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${org.springframework-version}</version>
            </dependency>
     
            <!-- AspectJ -->
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjrt</artifactId>
                <version>${org.aspectj-version}</version>
            </dependency>
     
            <!-- Logging -->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>${org.slf4j-version}</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>jcl-over-slf4j</artifactId>
                <version>${org.slf4j-version}</version>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
                <version>${org.slf4j-version}</version>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.15</version>
                <exclusions>
                    <exclusion>
                        <groupId>javax.mail</groupId>
                        <artifactId>mail</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>javax.jms</groupId>
                        <artifactId>jms</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>com.sun.jdmk</groupId>
                        <artifactId>jmxtools</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>com.sun.jmx</groupId>
                        <artifactId>jmxri</artifactId>
                    </exclusion>
                </exclusions>
                <scope>runtime</scope>
            </dependency>
     
            <!-- @Inject -->
            <dependency>
                <groupId>javax.inject</groupId>
                <artifactId>javax.inject</artifactId>
                <version>1</version>
            </dependency>
     
            <!-- Servlet -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <version>2.5</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>jsp-api</artifactId>
                <version>2.1</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>
     
            <!-- Test -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.7</version>
                <scope>test</scope>
            </dependency>
        </dependencies>
        <build>
            <plugins>
                <plugin>
                    <artifactId>maven-eclipse-plugin</artifactId>
                    <version>2.9</version>
                    <configuration>
                        <additionalProjectnatures>
                            <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                        </additionalProjectnatures>
                        <additionalBuildcommands>
                            <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                        </additionalBuildcommands>
                        <downloadSources>true</downloadSources>
                        <downloadJavadocs>true</downloadJavadocs>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>2.5.1</version>
                    <configuration>
                        <source>1.6</source>
                        <target>1.6</target>
                        <compilerArgument>-Xlint:all</compilerArgument>
                        <showWarnings>true</showWarnings>
                        <showDeprecation>true</showDeprecation>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>exec-maven-plugin</artifactId>
                    <version>1.2.1</version>
                    <configuration>
                        <mainClass>org.test.int1.Main</mainClass>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>
    cs


    * 스프링 MVC를 위한 설정을 web.xml에 추가


    Dispatcher 등록후 DispatcherServlet은 내부적으로 스프링 컨테이너를 생성하는데 contextConfigLocation 초기화 파라미터를 이용해서 컨테이너를 생성할 때 사용할 설정 파일을 지정한다. 여기에서는 mvc-quick-start.xml이라는 파일을 스프링 설정 파일로 사용한다.

    Dispatcher 서블릿에 대한 매핑을 *.do로 지정하여 웹브라우저 요청 중에서 확장자가 do로 끝나는 모든 요청을 dispatcher 서블릿이 처리하게 된다.

    UTF-8 필터를 설정하여 인코딩 문제를 해결한다.




    [web.xml]

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
     
        <!-- The definition of the Root Spring Container shared by all Servlets 
            and Filters -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/root-context.xml</param-value>
        </context-param>
     
        <!-- Creates the Spring Container shared by all Servlets and Filters -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
     
        <!-- Processes application requests -->
        <servlet>
            <servlet-name>appServlet</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
     
        <servlet-mapping>
            <servlet-name>appServlet</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
     
        <servlet>
            <servlet-name>dispatcher</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>/WEB-INF/mvc-quick-start.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
     
        <servlet-mapping>
            <servlet-name>dispatcher</servlet-name>
            <url-pattern>*.do</url-pattern>
        </servlet-mapping>
     
    </web-app>
     
    cs


    * 스프링 컨트롤러 구현

    web.xml의 DispatcherServlet설정이나 스프링 MVC설정은 프로젝트 시작 시점에 설정하면 대부분 완료되며 실제 컨트롤러와 뷰를 구현하는데 많은 시간이 할당된다.

    예제에서 사용할 컨트롤러 클래스의 구현은 아래와 같다.

    클래스가 스프링 MVC컨트롤러임을 지정, hello()메서드가 /hello.do로 들어오는 요청을 처리함을 지정

    뷰에 "greeting"이라는 이름으로 "안녕하세요"라는 데이터 전달

    리턴값 "hello"를 뷰이름으로 사용




    [HelloController.java]

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    package lee.lee.lee;
     
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
     
    @Controller
     
    public class HelloController {
        @RequestMapping("/hello.do")
        public String hello(Model model) {
            model.addAttribute("greeting""안녕하세요");
            return "hello";
        }
     
    }
     
    cs


    * JSP를 이용한 뷰 구현

    스프링 MVC에서 뷰(View)는 응답결과를 생성해주는 기능을 제공하는데 스프링은 기본적으로 JSP를 포함하여 템플릿 엔진을 지원한다.


    [hello.jsp]

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <%@ page language="java" contentType="text/html; charset=EUC-KR"
        pageEncoding="EUC-KR"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
    <title>Insert title here</title>
    </head>
    <body>인사말 : ${greeting }
    </body>
    </html>
    cs


    * 스프링 MVC 설정 파일 작성

    스프링이 제공하는 mvc네임 스페이스를 사용해서 설정하며 ViewResolver는 JSP를 뷰로 사용한다.


    [mvc-quick-start.xml]

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    <?xml version="1.0" encoding="UTF-8"?>
     
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:mvc="http://www.springframework.org/schema/mvc" 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
     
        <mvc:annotation-driven />
     
        <bean id="viewResolver"
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/views/" />
            <property name="suffix" value=".jsp" />
        </bean>
     
        <bean class="lee.lee.lee.HelloController" />
     
    </beans>
    cs


    반응형

    댓글

Designed by Tistory.