Srpring MVC - Controller

brave_chicken·2024년 4월 30일

잇(IT)생 챌린지

목록 보기
40/90

https://www.youtube.com/watch?v=tctY0ODCoig
https://www.youtube.com/watch?v=sUQP57rg8EI

Controller

웹서버가 하는 일

  • 정적리소스(이미지,css,js,정적 html파일)를 서비스

  • Json,xml 데이터서비스

  • 클라이언트의 요청을 받고 클라이언트에게 응답을 보낼 수 있는 기능

  • http통신

    **동적리소스는 db에서 불러와서 값이 변하기도

웹어플리케이션서버(Web Application Server - WAS)

  • http통신
  • 웹서버 + 어플리케이션서버(서블릿컨테이너..)
  • 비지니스로직을 수행하고 수행결과를 만들기
  • 동적 html, servlet, jsp, 스프링mvc

SSR(서버사이드렌더링)

  • 서버에서 뷰를 만들어서 클라이언트에게 전달
  • ex. JSP, 타임리프
    jsp실행결과는 다 동적html

CSR(클라이언트사이드렌더링)

  • react, vue.js

  • 클라이언트가 서버한테 요청을 보내면 서버가 클라이언트에게 데이터(단순문자열, JSON, xml)만 전송

  • 클라이언트에서 데이터를 받아서 실행결과를 만들기(자바스크립트(jQuery)로)

  • Ajax(Asynxhronous Jabascript And XML)로 요청
    => 화면전체가 바뀌지않고 일부만 바뀐다.
    => url,data를 넘기면 실행결과가 JSON으로 리턴

    **동기통신(화면이 반짝하며 바뀜)-비동기통신(화면일부만바뀜)

[컨트롤러 만들기]

  • spring mvc프레임워크에서 서비스되도록 하려면 컨트롤러를 만들어야 한다.
  • 컨트롤러로 인식되기 위해서는 @Controller를 클래스 위에 선언
  • 메소드를 정의해서 처리하고 싶은 일들을 처리하도록 작업
  • view를 실행하기 위한 작업도 jsp를 직접 실행할 수 없고 컨트롤러를 통해서 실행

1. 메소드를 정의

1) 메소드명은 사용자정의로 작성

public 리턴타입 메소드명(매개변수...){
 			//서블릿에서 처리하는 작업을 구현
 		}

2) 메소드 선언부 위에 매핑정보를 정의

- @RequestMapping("/path")

실습

main

TestController

  • 서블릿의 역할을 수행
  • @Controller로 정의하지 않으면 스프링MVC에서 실행되는 컨트롤러로 인식하지 않는다.
  • 무조건 @Controller로 정의
@Controller
public class TestController {
	//뷰를 요청하는 경우 String임
	@RequestMapping("/test.html")//주소라서 중복되면안됨
	public String test() {
		System.out.println("컨트롤러요청");
		return "test/test";//WEB-INF/test/test.jsp를 찾겠다는 말
	}
}

test.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>TestController실행결과</h1>
	<hr/>
</body>
</html>

web.xml

<?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 https://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/config/servlet-config.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>

servlet-config.xml

<?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 https://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context https://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/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<!-- annotation을 사용하기 위해서 스프링 IoC컨테이너가 스캔할 패키지 등록 -->
	<context:component-scan base-package="com.multi.springmvc" />
	<context:component-scan base-package="main"/>
	<context:component-scan base-package="test"/>
	
</beans:beans>

web.xml/servlet-config.xml는 동일
http://localhost:8089/springmvc/index.html

indexController

@Controller
public class indexController {
	@RequestMapping("/index.html")
	public String index() {
		return "index";
	}
}

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>첫화면</h1>
	<hr/>
	<h3><a href="/springmvc/test.html">테스트컨트롤러요청</h3>
	<h3><a href="/springmvc/gugu">구구요청</h3>
	
	<form method="post" action="/springmvc/test.html">
		<input type="submit" value="테스트컨트롤러요청">
	</form>
	
	<form method="get" action="/springmvc/gugu">
		<input type="submit" value="구구요청">
	</form>
</body>
</html>

test => 미션

GuGuController

@Controller
public class GuGuController {
	@RequestMapping("/gugu")
	public String showgugu() {
		System.out.println("구구단실행");
		return "test/gugu";
	}
}

gugu.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>
	<h2>구구단</h2>
</body>
</html>

web.xml

<?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 https://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/config/servlet-config.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>

servlet-config.xml

<?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 https://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context https://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/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<!-- annotation을 사용하기 위해서 스프링 IoC컨테이너가 스캔할 패키지 등록 -->
	<context:component-scan base-package="com.multi.springmvc" />
	<context:component-scan base-package="main"/>
	<context:component-scan base-package="test"/>
	
</beans:beans>

test 프로젝트 미션

springmvc프로젝트 개설
pom.xml파일 변경(매번하던 버전변경, 밑쪽 서블릿)
프로젝트- 프로퍼티스- 프로젝트페셋에서도 변경
xml파일 두개 위치랑 내용 일부 수정

본 포스팅은 멀티캠퍼스의 멀티잇 백엔드 개발(Java)의 교육을 수강하고 작성되었습니다.

0개의 댓글