ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 12. Spring MVC framework 설정하기
    Back-end Developer/Spring Framework, 설정 및 실습 2019. 1. 9. 15:58

    드디어 스프링 프로젝트를 직접 만들어 볼 텐데요.

    역시나.. 설정은 필요합니다.

    예전에 STS 사용할때도 초기 설정 제대로 안했다가, 중간에 에러 막터져서 고생한 기억이 새록새록나네요.

    하하.. 그만큼 초기 설정이 중요하니 꼭 빼먹지마시고, 다른 툴을 사용하시더라고 꼭 찾아보시고 따라하세요!!



    프로젝트 생성 및 재설정


    new -> other -> Spring Legacy Project 선택

    -> Template: Spring MVC project 선택 -> package 경로 설정, 완료

    저는 패키지 경로를 늘 하던대로, 'kr.ac.snut.web' 으로 잡았습니다. 개개인 마다 선호하는 방식으로 해주시면 됩니다.^^


    dependencies 파일 보시면 아시겠지만, Id 설정들이 잘못되어있는게 보입니다... 헠쓰!

    좌측 프로젝트 트리에서 우리가 생성한 프로젝트에서 마우스 오른쪽 버튼 클릭!


    project Refactor -> rename Maven Project에서

    group Idkr.ac.snut.web (본인이 지정한 패키지 경로)

    artifact IdhelloSpringMVC (본인이 생성한 프로젝트 명)


    이대로 다 따라오셨다면, dependencies 설정들이 알맞게 바꼈을거에요.

    이제 프로젝트 properties -> Web Project Settings -> Context root를 프로젝트 명으로 변경


    Context root



    마찬가지로 Project Facet도 재설정 해주세요.


     Project Facet


    pom.xml의 overview 탭에서 자바와 스프링 버전도 자신이 쓰는것으로 바꿔주세요.

    저는 자바는 1.8, 스프링은 4.2.5 사용합니다.


    그리고 pom.xml 탭에가서 maven compiler plugin 버전도 변경해주세요.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
                 <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>2.5.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                        <compilerArgument>-Xlint:all</compilerArgument>
                        <showWarnings>true</showWarnings>
                        <showDeprecation>true</showDeprecation>
                    </configuration>
                </plugin>
    cs


    마지막으로 Java Resources 파일내 main 파일에 존재하는 패키지 명도 우리가 설정 했던 이름 그대로 바꿔주시면 됩니다.



    HomeController


    프로젝트 생성시에 자동으로 생성된 컨트롤러입니다.

    Main class로 보시면 될 것 같아요. 물론 완전 같은것으로 보시면 안됩니다..ㅎㅎ


    HomeController.java

    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
    package kr.ac.snut.web;
     
    import java.text.DateFormat;
    import java.util.Date;
    import java.util.Locale;
     
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
     
    /**
     * Handles requests for the application home page.
     */
    @Controller
    public class HomeController {
        
        private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
        
        /**
         * Simply selects the home view to render by returning its name.
         */
        @RequestMapping(value = "/", method = RequestMethod.GET)
        public String home(Locale locale, Model model) {
            logger.info("Welcome home! The client locale is {}.", locale);
            
            Date date = new Date();
            DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
            
            String formattedDate = dateFormat.format(date);
            
            model.addAttribute("serverTime", formattedDate );
            
            return "home";
        }
        
    }
    cs


    우선 가장 먼저 보이는 것은 '@Controller'네요.

    거의 뭐 대놓고 지가 컨트롤러라고 광고하네? 라고 생각하실 수 있는데, 뭐 틀린말은 아니구요.

    원래 우리가 같은 방식으로 쓰던 어노테이션이 있습니다.


    바로 '@Component'인데요. 

    이 컨트롤러 어노테이션은 Component와 동일한 역할을 하는 동시에 컨트롤러 임을 보여줍니다.



    그 다음엔 '@RequestMapping'이 등장합니다.

    내부에 value = '/', 이런 인자가 존재합니다.

    말 그대로 요청을 매핑하는 역할입니다. 요청은 Get Method를 사용하구요.


    좀 더 자세하게 말해보면,

    우리가 만든 프로젝트 'https://localhost:8080/helloSpringMVC' 경로로 들어와 끝에 '/'의 입력을 받아들이면,

    아래의 home 메소드가 실행 될 수 있도록 해주는 기능입니다.



    다음으로 home 메소드는 어떤 구성을 하고 있을까요?


    우선 인자로는 locale(지역, 한국)을 받아오고, 그 옆에는 그냥 우리가 흔히 아는 모델을 인자로 받아옵니다.

    그리고 시간함수를 호출해서, 시간을 dateFormat이라는 변수에 시간, 시간, 지역 순으로 저장하고,

    해당 변수를 다시 함수를 통해 문자열로 변형합니다.

    마지막으로 변형된 문자열을 serverTime이라는 이름으로, model attribute에 결과를 담습니다.


    그리고 반환을 home을 하는데, 이는 프로젝트 내의 home.jsp파일을 불러옵니다.

    (위의 동작에 대한 내용은 밑에서 다시 얘기 해볼게요.)


     home.jsp

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ page session="false" %>
    <html>
    <head>
        <title>Home</title>
    </head>
    <body>
    <h1>
        Hello world!  
    </h1>
     
    <P>  The time on the server is ${serverTime}. </P>
    </body>
    </html>
     
    cs


    해당 파일의 경로

    src -> main -> webapp -> WEB-INF -> views -> home.jsp

    이렇게 불려진 home.jsp는 place holder를 통해 우리가 받아온 서버시간을 출력해줍니다.



    실행 결과


    우리가 만든것은 아니지만, 코드 이해도 했으니 실행한번 해보겠습니다.


    헠쓰.. 한글이 깨져나오네요. UTF-8 인코딩 설정도 해줍시다.

    web.xml에 filter를 입력해주세요.


    web.xml filter 추가

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
        <filter>  
            <filter-name>encodingFilter</filter-name>  
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
            <init-param>  
               <param-name>encoding</param-name>  
               <param-value>UTF-8</param-value>  
            </init-param>  
            <init-param>  
               <param-name>forceEncoding</param-name>  
               <param-value>true</param-value>  
            </init-param>  
        </filter>
    cs



    재실행 해볼게요.


    잘 나오네요. ㅋㅋㅋㅋ 기분이 좋으니 절로 웃음이^___^/



    web.xml


    열어본 김에 web.xml 코드도 살짝 뒤적뒤적해봅시다.

    우선 눈에 띄는건 sevlet 태그에 dispatcher servlet 클래스가 보이네요.

    이 클래스는 모든 요청에 대하여, 처리해주는 클래스입니다. 


    Dispatcher Servlet class 구조



    그리고 servlet-context.xml이 바로 설정 파일입니다.


    servlet-context.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
    <?xml version="1.0" encoding="UTF-8"?>
    <beans:beans xmlns="http://www.springframework.org/schema/mvc"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:beans="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
     
        <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
        
        <!-- Enables the Spring MVC @Controller programming model -->
        <annotation-driven />
        <context:component-scan base-package="kr.ac.snut.web" />
     
        <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
        <resources mapping="/resources/**" location="/resources/" />
     
        <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
        <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <beans:property name="prefix" value="/WEB-INF/views/" />
            <beans:property name="suffix" value=".jsp" />
        </beans:bean>
        
    </beans:beans>
    cs


    annotation-driven, context:component-scan은 해당 패키지를 찾아 어노테이션을 주입합니다.


    그리고 bean 태그는 view 관련 내용입니다.

    이게 바로! 아까 home controller에서 반환한 home 값에 대한 처리를 보여줍니다.


    그래서 home이 반환되면, prefix로 'WEB-INF/views/' 라는 경로를 붙여주고,

    뒤에 suffix로 '.jsp' 파일 형식을 붙여주는데요.

    따라서 결과적으로 우리가 반환한 home이라는 단어가 'WEB-INF/views/home.jsp'가 되어 해당 파일을 불러오게 되는것이죠.


    그냥 실행할 땐 몰랐는데 이렇게 파헤쳐보니 다 설정이 되어있었네요. ㅎㅎ

    끝날때가 다 되어가니, 빨리 혼자 뭘 만들어보고 싶은 욕구가 생기네요! 힘냅시다~

    반응형

    댓글

Designed by minchoba.