본문으로 바로가기

스프링 MVC 프로젝트를 생성한 기본 구조를 그대로 써도 상관없다. 다만 구조를 바꾼다면 web.xml의 경로만 잘 설정해주면 아무 문제없이 잘 돌아간다. 구성을 바꾸는 이유는 아직은 잘 모르겠다. 개인 프로젝트로 구조를 변경하지 않고도 문제없이 완성했었다. 개인적인 생각으로는 보기 편해서 그런 거 같다. 기본 구조는 설정 파일들과 view 파일들이 섞여 있지만 새로 구성한 구조는 기능별로 묶여진 느낌이 들기도 한다. 그리고 프로젝트 구성도 사람마다 조금씩 다른 거 같다. 딱히 정해진 구조도 없는 거 같아서 그냥 구조를 바꾼다면 그 경로를 알맞게 지정해준다는 것만 유의하면 된다. 구조를 재정의하지 않아도 무리없이 사용가능하다. 



1. contextConfigLocation 변경 

servlet, context 폴더를 이동할 것이다. web.xml에서 이들의 param-name을 contextConfigLocation이라 한다. 나는 servlet과 context 모두를 한꺼번에 옮겼지만, context만 옮기는 분들도 있다. 나는 쉽게 찾기 위해서 통째로 resources 패키지에 넣었다. 어떻게 넣든 헷갈리지 않고 잘 설정하면 아무 문제없다.


1-1. webapp -  WEB-INF - spring 폴더 복사


1-2. src/main/resources에 붙여넣기

패키지 모양으로 보인다면 http://addio3305.tistory.com/44 참고


1-3. webapp - WEB-INF - spring 폴더 삭제


1-4. xml 이름 변경

servlet-context.xml -> action-servlet.xml

root-context.xml -> context-root.xml

지금은 하나의 파일로만 되어 있지만 나중에는 여러 파일이 추가 될 것이다. 이러한 확장성을 생각하여 특정 폴더안에 있는 설정 파일들을 모두 읽어올 수 있게끔 파일들의 이름을 수정한다. 이렇게 변경해놓으면 서블릿 설정을 변경할 때 한번에 다 불러오기 편하다.



2. 서블릿 설정 변경 (web.xml)

context와 servlet 파일들의 폴더를 이동했으니, 이제 경로를 맞춰주자.


2-1. 기존 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
<?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


2-2. 변경 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
<?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>classpath*:spring/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>classpath*:spring/appServlet/*-servlet.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

- 9행 : 스프링 설정파일들을 읽어온다. spring 폴더에 context-*.xml인 파일들을 모두 읽어온다.  context들을 기능별로 분리하여 한꺼번에 불러오기 위한 것이다. (context-common.xml, context-datasource.xml 등등) 파일들의 이름을 변경한 이유이다. 물론 context-root.xml 파일에 설정을 다 해 놓고 하나만 불러와도 된다. 근데 이렇게 하면 설정파일들을 수정할 때 찾기가 힘들어진다. 그래서 context 기능별로 분리하는 게 좋다.


- 21행 : sping 폴더안의 appServlet 폴더 안에 있는 *-servlet.xml 파일들을 모두 읽어온다. 이것도 마찬가지이다.

이제 context 파일이나 servlet 파일들을 추가할 때 context-XXX.xml 이나 XXX-serlvet.xml로 만들면 자동적으로 설정파일들이 읽어와 진다.


- 28행 : 서블릿에 요청을 할 때, 요청을 전달할 url을 뜻한다. 이 패턴 외의 요청은 허락하지 않는다. *.do를 넣으면 .do로만 요청을 전달한다. Controller의 RequestMapping으로 요청 url을 적는 부분에서 사용할 url의 패턴을 뜻한다. 요청 패턴이 다르면 controller에서 비즈니스 로직을 찾지 못하니 요청 패턴을 잘 기억해둬야 한다. 보통 .do를 많이 쓰는데, 나는 귀찮기 때문에 그냥 / 를 쓴다.


** classpath 경로

프로젝트 우클릭 > properties > Deployment Assembly

위에서 classpath 경로를 확인할 수 있는데, 

/src/main/resoucres 에 파일을 생성하여 빌드를 하면 WEB-INF/classes 에 들어감을 나타낸다. 


2-3. 서버를 실행하고 오류가 안뜨면 성공



3. index.jsp 추가

프로젝트를 실행하면 home.jsp가 실행된다. 이것은 컨트롤러의 맵핑을 거쳐 실행되는데, 서버를 실행하고 컨트롤러에 들어갔다가 다시 jsp로 가는 건 비효율적이고 우리가 제어하기 힘들다. 따라서 서블릿을 통해서 프로젝트가 실행되면 index.jsp가 실행되도록 만들어보자.


3-1. webapp폴더 밑에 index.jsp 추가

** 위치 중요

WEB-INF 밑에 있는 jsp는 보안상 바로 접근할 수 없다. 컨트롤러를 통해(요청패턴을 통해) 접근을 할 수 있다. 하지만 webapp밑에 있는 파일들은 주소만 치면 바로 들어갈 수 있다. 그래서 단순 주소만으로 접근 가능하게 index.jsp를 만들고 그 다음부터 컨트롤러를 통해 접근하게 만드는 것이다.


index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=utf-8">
<title>Insert title here</title>
</head>
<body>
<h1>index.jsp</h1>
</body>
</html>
cs



3-2. web.xml에 <welcome-file>추가

1
2
3
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
cs

<webapp></webapp>태그 안에 아무곳에나 넣어줘도 된다. 나는 맨 위에 뒀다. 이렇게 설정하면 서버가 실행되면서 web.xml에서 welcome-file을 읽어서 webapp에 있는 index.jsp가 실행된다. 



3-3. HelloController(com.tody.lovely 패키지) 삭제 및 home.jsp 삭제

이제 필요없는 걸 삭제 해주자.



3-4. 서버 실행

짠!



4. UTF-8 설정

web.xml에 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    <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>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>
cs

<webapp></webapp> 태그 안에 아무곳에나 넣어줘도 된다. 나는 맨 밑에 넣어줬다.

- 13행 : 서블릿 설정을 변경할 때 요청 url 패턴을 변경한 것과 똑같은 걸로 해줘야 한다. 만약 서블릿의 요청 url을 *.do로 했다면 13행의 url 패턴을 *.do로 해줘야 한다.




5. 최종 web.xml 및 디렉토리 구조

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
51
52
53
<?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">
    
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
 
    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:spring/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>classpath*:spring/appServlet/*-servlet.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>
    
    <!-- utf-8 설정 -->
    <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>
      </filter>
      <filter-mapping>
          <filter-name>encodingFilter</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>
 
</web-app>
cs



디렉토리 구조

개발 소스 디렉토리나 sql, resources, views 같은 현재 없는 디렉토리들은 나중에 개발하면서 차차 추가될 것이다. 먼저 이렇게 만들어 놓고 개발을 시작해도 되지만, 개발하면서 필요한 것만 추가해도 된다. 디렉토리 구조를 상세하게 보여주려고 미리 추가해놓은 것이다. 



views 폴더가 아닌 wepabb폴더에 있는 index.jsp에 css를 적용하고 싶으면 하면 된다. 굳이 하지 않아도 된다.

6. 서버 주소 경로 변경

스타일시트(css) 경로를 설정하기 위해서 주소를 변경한다. css가 있는 resources와 index가 같은 경로에 있어야 한다. 지금 서버를 실행시키면 http://localhost:8080/(프로젝트명) 이렇게 뜰텐데, 그때 F12(개발자도구)를 키면 왼쪽 사진처럼 index의 위치가 프로젝트 폴더 안에 들어가 있는 것을 확인할 수 있다. 이런식으로 설정되어 있으면 css를 적용하기가 힘들어진다. http://localhost:8080 로 바꾼뒤에 서버를 실행시키고 F12를 켜면 오른쪽 사진과 같이 index의 위치가 reosurces와 같은 경로에 있는 것을 확인할 수 있다. 이렇게 되어 있으면 css를 적용하기 쉬워진다. 다른 아무 웹사이트에 들어가서 F12를 켜봐도 resources와 index가 같은 경로에 있는 것을 확인할 수 있을 것이다. 만약에 index.jsp를 주소로 쳐서 들어가는 경우(<welcom-file>태그로 지정해준 경우)가 아닌, index.jsp가 컨트롤러를 통해서 들어간다면 굳이 안해도 된다.


변경전 주소 http://localhost:8080/lovely/


6-1. Servers 탭 - Tomcat 더블클릭 - Modules 


6-2. 프로젝트 클릭 - Edit - Path에 /(프로젝트명) -> / 변경


6-3. 변경된거 확인후, ctrl+s(save)


6-4. 서버 실행

http://localhost:8080로 보이고 index.jsp 페이지가 실행되면 성공



설정 끝! ♪\(●'∀'●)ノ♪


참고 : http://addio3305.tistory.com/