JAVA/웹 프로그래밍 - Spring

Spring MVC2 - 5. SpringMVC2

DesignatedRoom 2020. 12. 21. 22:41

아래의 글을 읽어보자.

designatedroom87.tistory.com/336?category=909022

 

프로젝트를 Maven 프로젝트로 변경하기

아래의 내용을 참고해보자. designatedroom87.tistory.com/334?category=909022 Maven 설치 및 설정 우리가 앞에서 서블릿에서 게시판 만들기에서 이미지 업로드 시에 cos.jar파일을 WEB-INF/lib폴더에 추가해..

designatedroom87.tistory.com

 

프로젝트를 다시 만들자. maven project로 만든다.

 

webapp폴더 하위에 WEB-INF폴더 만들고 이 폴더에 web.xml을 만든다.

web.xml

더보기
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>El</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
   <servlet>
  	<servlet-name>dispatcher</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>dispatcher</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
  
</web-app>

 

 

pom.xml

더보기
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.iot</groupId>
  <artifactId>springmvc2</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  
   <properties>
		<java-version>1.8</java-version>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
		<org.springframework-version>5.2.9.RELEASE</org.springframework-version>
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>1.6.6</org.slf4j-version>
	</properties>
	
	<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-api -->
<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-api</artifactId>
    <version>9.0.39</version>
</dependency>


<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.2.9.RELEASE</version>
    <scope>test</scope>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.9.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.9.RELEASE</version>
</dependency>

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

<!-- mybatis -->
<!-- mybatis 프레임워크 사용하기 위해 -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis</artifactId>
		    <version>3.5.5</version>
		</dependency>
		<!-- mybatis와 spring 연동하기 위해 -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis-spring</artifactId>
		    <version>2.0.5</version>
		</dependency>
<!-- jdbc Connection Pool -->
		<dependency>
	        <groupId>com.zaxxer</groupId>
	        <artifactId>HikariCP</artifactId>
	        <version>3.4.5</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>
		<!-- 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>
				
	</dependencies>
</project>

 

 

WEB-INF폴더에 spring bean configuration file 을 만들고 이름을 dispatcher-servlet라고 하자.

dispatcher-servlet.xml

더보기
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="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-4.3.xsd">

<!-- 컨트롤러를 등록( springmvc2패키지에 컨트롤러가 있다. ) -->
 <context:component-scan base-package="springmvc2" />
<!-- <bean id="index" class="springmvc2.IndexController" /> -->

<!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	<property name="order" value="2" />	
	<property name="prefix" value="/WEB-INF/view/" />
	<property name="suffix" value=".jsp" />
</bean> -->

</beans>

 

아래와 같이 dispatcher-servlet파일을 연 상태에서 좌측하단에 다음과 같은 목록이 보인다.

그리고, Namespaces를 선택해서 아래와 같이 context를 선택한다.  

 

src/main/java에 class파일을 만드는데 이름은 IndexController를 만든다.

IndexController.java

package springmvc2;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController 
{	
	@RequestMapping("/index")
	public String index() {	
		System.out.println("index.jsp실행");
		return "index.jsp";	
	}
}

 

webapp폴더에 index.jsp파일을 만든다.

그리고 webapp폴더에 index.html파일도 만든다.

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>index.jsp</h1>
</body>
</html>

 

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>index.html</h1>
</body>
</html>

 

index.html파일을 실행시키면 내부 서버 오류가 뜬다.

index.jsp를 실행시키면 정상적으로 뜬다. 

위의 정보로 부터 알 수 있는 사실은 스프링을 통한 웹 접근 시, jsp는 접근 가능하지만 html은 접근 불가능하다.

http://localhost:9090/index이라 주소 입력하면 내부 서버 오류가 뜬다.

위의 사실을 통해 알 수 있는 사실은 web.xml에서 설정한 dispatcher-servlet은 메인컨트롤러를 등록하는 작업으로서

어노테이션을 이용하여 등록가능 하지만 패키지가 존재하여야 한다.

어노테이션을 사용하지 않을 경우 IndexController.java 파일은

스프링의 Controller 인터페이스를 구현해야 하며 WEB-INF/dispatcher-servlet.xml에 bean 등록을 해줘야 한다. 

 

IndexController의 메소드를 다음과 같이 변경하고 http://localhost:9090/index로 접속해보자.

오류가 발생할 것이다.

@RequestMapping("/index")
	public void index() {	
		System.out.println("index.jsp실행");
		//return "index.jsp";	
	}

 

webapp폴더에 aaa폴더를 만들고 index.jsp파일을 만들어서 내용을 다음과 같이 적어보자.

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>aaa/index.jsp</h1>
</body>
</html>

 

그리고 IndexController.java를 다음과 같이 변경해보자.

@RequestMapping("/aaa/") 은 의미는 url에서 localhost:9090/aaa/index 를 의미한다.

package springmvc2;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("aaa")
public class IndexController 
{	
	@RequestMapping("/index")
	public String index() {	
		System.out.println("index.jsp실행");
		return "index.jsp";	
	}
}

 

웹 주소에 http://localhost:9090/aaa/index 라고 입력하면 aaa/index.jsp 내용이 나온다.

그리고, 다시 IndexController.java의 내용을 아래와 같이 변경해보자.

package springmvc2;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/aaa/")
public class IndexController 
{	
	@RequestMapping("/index")
	public String index() {	
		System.out.println("index.jsp실행");
		return "index.jsp";	
	}
}

http://localhost:9090/aaa/index 입력하면 aaa/index.jsp라고 출력된다.

 

 

이번에는 WEB-INF폴더에 index.jsp 파일을 만들어보자.

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>/WEB-INF/index.jsp</h1>
</body>
</html>

그리고, 다시 IndexController.java의 내용을 아래와 같이 변경해보자.

package springmvc2;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/aaa/")
public class IndexController 
{	
	@RequestMapping("/index")
	public String index() {	
		System.out.println("index.jsp실행");
		return "/WEB-INF/index.jsp";	
	}
}

http://localhost:9090/aaa/index로 접속해보자.

 

 

 

WEB-INF폴더에 view폴더를 만들어서 index.jsp파일을 만들어 보자.

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>/WEB-INF/view/index.jsp</h1>
</body>
</html>

그리고, 다시 IndexController.java의 내용을 아래와 같이 변경해보자.

그리고 dispatcher-servlet.xml에서 다음의 문장을 주석해제 한다.

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	<property name="order" value="2" />	
	<property name="prefix" value="/WEB-INF/view/" />
	<property name="suffix" value=".jsp" />
</bean>

 

dispatcher-servlet.xml

http://localhost:9090/aaa/index4를 입력한다.

 

 

 

view폴더에 index4.jsp파일을 만든다.

index4.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>/WEB-INF/view/index4.jsp</h1>
</body>
</html>

그리고, 다시 IndexController.java의 내용을 아래와 같이 변경해보자.

기존의 index4메소드만 수정한다.

IndexController.java

package springmvc2;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/aaa/")
public class IndexController 
{	
	@RequestMapping("/index1")
	public String index1() {	
		System.out.println("index.jsp실행");
		return "index.jsp";	
	}
	
	@RequestMapping("/index2")
	public String index2() {	
		System.out.println("/WEB-INF/index.jsp실행");
		return "/WEB-INF/index.jsp";	
	}
	
	@RequestMapping("/index3")
	public String index3() {	
		System.out.println("/WEB-INF/view/index.jsp실행");
		return "/WEB-INF/view/index.jsp";	
	}
	
	@RequestMapping("/index4")
	public String index4() {	
		System.out.println("뷰 리졸버 실행");
		return "index4";	
	}
}

웹 페이지에서 http://localhost:9090/aaa/index4로 접속해보자.

 

requestMapping을 이용하여 함수를 실행하면 리턴값은 webapp경로를 기준으로 파일을 검색하게 된다.
리턴값은 url에 쓰여지는 값이 아니다.

 

아래의 문장은 앞에서 우리가 자주보던 웹 주소이다.

localhost:9090/index5?page=3

위의 내용을 구현한 내용은 index5.jsp파일을 view폴더에 만들어보자.

index5.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>/WEB-INF/view/index5.jsp</h1>
	${page}<br>
</body>
</html>

그리고, 다시 IndexController.java의 내용을 아래의 함수를 추가해보자.

@RequestMapping("/index5")
	public ModelAndView index5(String page) {	
		System.out.println("index5 뷰 리졸버 실행 : "+page);
		ModelAndView mv = new ModelAndView();
		mv.addObject("page",page);
		mv.setViewName("index5");
		return mv;	
	}

 

그리고 @RequestMapping("/aaa/")를 주석처리 한다.

웹 주소에 다음의 내용을 입력해보자. http://localhost:9090/index5?page=3

 

그리고 이번에는 다수의 변수를 넘겨보자.

index5.jsp파일을 다음과 같이 수정하자.

index5.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>/WEB-INF/view/index5.jsp</h1>
	${page}<br>
	${count}<br>
</body>
</html>

IndexController.java에서 index5메소드를 다음과 같이 수정하자.

@RequestMapping("/index5")
	public ModelAndView index5(String page, String count) {	
		System.out.println("index5 뷰 리졸버 실행 : "+page + " " +count);
		ModelAndView mv = new ModelAndView();
		mv.addObject("page",page);
		mv.addObject("count",count);
		mv.setViewName("index5");
		return mv;	
	}

http://localhost:9090/index5?page=3&count=10으로 접속해보자.

 

 

그리고 IndexController.java에 메소드index6을 추가한다.

@RequestMapping("/index6")
	public ModelAndView index6(HttpServletRequest request) {	
		
		String page = request.getParameter("page");
		String count = request.getParameter("count");
		
		System.out.println("index6 뷰 리졸버 실행 : "+page + " " +count);
		ModelAndView mv = new ModelAndView();
		mv.addObject("page",page);
		mv.addObject("count",count);
		mv.setViewName("index6");
		return mv;	
	}

index6.jsp파일을 view폴더에 만든다.

index6.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>/WEB-INF/view/index6.jsp</h1>
	${page}<br>
	${count}<br>
</body>
</html>

웹 페이지에 http://localhost:9090/index6?page=3&count=10 을 입력해보자.

만약 메소드 index6에서 response가 필요하면 매개변수에 선언만 해주면 된다.

한글이 깨지면 request.setCharacterEncoding("UTF-8")을 호출하자.

 

프로젝트 전체 내용

springmvc2.zip
0.02MB