티스토리 뷰

반응형

※ Eclipse에서 Alt + Shift + R을 누르면 파일명을 검색 할 수 있으니 참고해주세요.


Step 1. 예제 소스 간단하게 정리

먼저 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 com.mycompany.test;
 
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


최소한의 테스트를 위해서 필요한 소스코드만 남겨보도록 하겠습니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.mycompany.test;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class HomeController {
 
    @RequestMapping("test.do")
    public String test(Model model) {
        model.addAttribute("serverTime""테스트" );        
        return "home";
    }    
    
}
cs


한결 보기 좋아졌습니다..


http://localhost:8080/test/test.do로 접속해보면 이상없이 수정된 것을 확인 할 수 있습니다.


소스코드를 살펴보기 전에 한가지만 먼저 알아두고 가겠습니다.


위 소스코드의 7번째 줄에 보면 @Controller라고 되어있는게 보이실 겁니다.


이와 같이 클래스, 변수, 메소드 등에 @xxx 형태로 붙어있는 것을 어노테이션(Annotation)이라고 부릅니다.






Step 2. HomeController.java 분석

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.mycompany.test;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class HomeController {
 
    @RequestMapping("test.do")
    public String test(Model model) {
        model.addAttribute("serverTime""테스트" );        
        return "home";
    }    
    
}
cs


@Controller는 이 클래스가 컨트롤러라는 것을 스프링에 알려주는 용도입니다.



@RequestMapping은 파라미터와 같은 요청이 왔을 경우 아래 메소드를 수행시키는 용도입니다. 


@Controller가 붙어있는 클래스 안에 있어야만 정상적으로 동작합니다. 


7번째 줄의 @Controller를 주석 처리 한 후 http://localhost:8080/test/test.do로 접속해보면 404에러가 나오는 것을 확인 할 수 있습니다.



12번째 줄은 뷰로 값을 전달하는 코드이고, "serverTime"은 key이고, "테스트"는 value입니다.



13번째 줄은 뷰의 이름을 리턴해주고 있습니다.



※ 다른 파일의 분석 내용까지 보셔야 완벽하게 이해를 할 수 있습니다. 다소 이해가 되지 않더라도 다음 파일의 분석 내용을 봐주시기 바랍니다.






Step 3. home.jsp 분석

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<%@ 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

HomeController.java에서 넘겨준 값을 12번 라인에서 표시해줍니다.

영어를 넘겨줬다면 잘 표현이 되었겠지만 컨트롤러에서 뷰로 넘겨주는 과정에서 한글이 깨져서 ?로 표시되고 있습니다.

web.xml에 filter를 추가해서 해결 할 수 있습니다.






Step 4. 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
26
27
28
29
<?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 />
 
    <!-- 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>
    
    <context:component-scan base-package="com.mycompany.test" />
    
    
    
</beans:beans>
 
cs


19~22번째 줄을 보면 컨트롤러에서 리턴한 뷰가 어떻게 처리되는지 알 수 있습니다.


prefix에는 모든 뷰의 공통경로가 입력되어 있고, suffix에는 모든 뷰의 공통확장자가 입력되어 있습니다.


그렇기 때문에 컨트롤러에서는 파일명만 리턴해주면 되는 것입니다.


이 기능은 스프링의 굉장히 큰 장점중에 하나입니다.


스프링을 사용하지 않고, 서블릿만을 이용해서 웹개발을 할 경우 아래 링크와 같이 각각 요청 별로 web.xml에 등록을 해줘야 하는 번거로움이 있습니다.


http://webfortj.blogspot.kr/2012/05/servlet.html



다른 부분들도 다 중요한 의미가 있지만 머리 아프기 때문에 추후에 관련이 있을 때 살펴보도록 하겠습니다.






Step 5. 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
<?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>
 
</web-app>
 
cs


18~26번째 줄에 DispatcherServlet에 대한 선언이 있습니다.


DispatcherServlet이 뭔지 잘 모르겠으신 분들은 이전 강좌의 Step 2. Spring 기본 동작 순서를 참고해주시기 바랍니다.


어떤 설정이다라는 것만 알아두고, 세세한 속성, 파라미터 등은 나중에 수정이 필요 할 때 공부하는 것이 좋을 듯 합니다.


28~31번째 줄에 보면 서블릿의 url-pattern을 설정하는 부분이 있습니다.


30번째 줄을 보면 특별한 제약없이 다 맵핑되게 되어 있는데 보통은 아래와 같이 수정을 합니다.


<url-pattern>*.do</url-pattern>


HomeController.java의 @RequestMapping의 파라미터를 "test"와 "test.do"로 바꿔가면서 테스트해보시기 바랍니다.


이제는 .do로 끝날 경우에만 제대로 맵핑이 되는 것을 확인 할 수 있을 것입니다.


※ xml파일이 수정되면 톰캣을 재시작 해주어야 변경내용이 적용됩니다.






Step 6. 한글 깨짐 처리

web.xml 파일을 아래와 같이 수정하도록 하겠습니다.


33~51번째 줄이 추가되었습니다.


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
<?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>*.do</url-pattern>
    </servlet-mapping>
 
    <!-- encoding -->    
    <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>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>    
 
</web-app>
 
cs


테스트페이지를 접속해보면 ?로 나오던 한글이 정상적으로 나오는 것을 확인 할 수 있습니다.



home.jsp파일을 아래와 같이 수정한 후 다시 접속해보도록 하겠습니다.


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



다시 한글이 깨지고 있습니다.


web.xml에 추가한 인코딩에 대한 부분은 컨트롤러에서 뷰로 넘겨줄 때만 적용되는 것임을 확인 할 수 있습니다.


뷰에 대한 인코딩 설정은 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" pageEncoding="utf-8" %>
<html>
<head>
    <title>Home</title>
</head>
<body>
<h1>
    안녕  
</h1>
 
<P>  The time on the server is ${serverTime}. </P>
</body>
</html>
 
cs








마침말

스프링에 대해서 미세하게나마 알아볼 수 있는 시간이었습니다.


제 생각에는 굉장히 쉽게 설명해 놓았다고 생각하는데 보시는 분은 어떨지 모르겠습니다.


궁금한 점이나 의견 또는 잘못된 부분에 대한 지적사항 있으시면 댓글 남겨주시면 감사하겠습니다.


반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함