스프링 MVC
스프링 MVC 설정
<packaging>war</packaging>
이 태그의 기본값은 jar로서 서블릿/JSP를 이용한 웹 어플리케이션을 개발할 경우 war를 값으로 주어야 한다.
war ( Web Application Archive )
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>_springMVC0808</groupId>
<artifactId>_springMVC0808</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.2-b02</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>11</release>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
</plugin>
</plugins>
</build>
</project>
구성요소 설정 ( @EnableWebMvc )
configureViewResolvers : JSP 이용해서 컨트롤러의 실행 결과를 보여주기 위한 설정 추가
Controller 설정 파일에서 return "hello"; 설정 시 hello.jsp로 이동
MvcConfig
package config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/view/", ".jsp");
}
}
위에 코드에서 오버라이드는 밑에 이미지 처럼 설정 해주면 된다.
web.xml 파일에 DispatcherServlet 설정 ( WEB-INF 위치에 )
( 스프링 MVC가 웹 요청을 처리하려면 DispatcherServlet 설정 필요 )
<?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" version="4.0">
<display-name>_springMVC0808</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>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
config.MvcConfig
config.ControllerConfig
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<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>
web.xml파일에서 중요한 부분은 밑에 코드다.
contextConfiguration 초기화 파라미터의 값을 지정한다. 이 파라미터에는 스프링 설정 클래스 목록을 지정한다.
각 설정 파일의 경로는 줄바꿈이나 콤마로 구분 ( 해당 글에서는 MvcConfig 클래스만 작성 )
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
config.MvcConfig
config.ControllerConfig
</param-value>
</init-param>
컨트롤러 구현
@GetMapping : HTTP 요청 메서드 중 GET 메서드에 대한 매핑을 설정한다.
Model 파라미터 : 컨트롤러의 처리 결과를 뷰에 전달할 때 사용
@RequestParam : HTTP 요청 파라미터의 값을 메서드의 파라미터로 전달할 때 사용
"greeting" : 속성에 값을 설정 ( 변수 ), 값으로는 "안녕하세요.", 와 name 파라미터의 값을 연결한 문자열을 사용한다.JSP코드에서 이 속성을 이용해서 값을 출력한다.
return "hello" : 컨트롤러의 처리 결과를 보여줄 뷰 이름으로 "hello"를 사용한다. MvcConfig 파일에 밑에 코드 부분을 통해서 hello.jsp 파일로 이동
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/view/", ".jsp");
}
package chap09;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class HelloController {
@GetMapping("/hello") // URL 입력값
public String aaa(Model model,
@RequestParam(value = "name", required = false)String name) {
model.addAttribute("greeting", "안녕하세요." + name);
return "hello";// configureViewResolvers 붙여질 값
}
@GetMapping("/add")
public String add(){
return "addForm";
}
@GetMapping("/result")
public String result(Model model,
@RequestParam(required = true, defaultValue = "0") Integer num1,
@RequestParam(required = true, defaultValue = "0") Integer num2) {
model.addAttribute("sum", num1 + num2 );
return "result";
}
}
스프링 빈으로 등록
package config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import chap09.HelloController;
@Configuration
public class ControllerConfig {
@Bean
public HelloController helloController() {
return new HelloController();
}
}
JSP 파일 생성 ( WEB-INF => view )
index 파일을 설정 안해놨기 때문에 프로젝트 Run As => ( http://localhost:9090/hello )
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>hello</title>
</head>
<body>
인사말 : ${greeting}
</body>
</html>
합계 출력 해보기
addForm.jsp ( http://localhost:9090/add )
action 부분 그냥 /result로 할 시 jsp페이지 출력 불가 밑에 코드 처럼 하거나 Servers프로젝트 server.xml에 path="/"로 설정
<Context docBase="testddd" path="/testddd" reloadable="true" source="org.eclipse.jst.jee.server:testddd"/><Context docBase="_springMVC0808" path="/" reloadable="true" source="org.eclipse.jst.jee.server:_springMVC0808"/><Context docBase="_customTag0808" path="/_customTag0808" reloadable="true" source="org.eclipse.jst.jee.server:_customTag0808"/><Context docBase="_board" path="/board" reloadable="true" source="org.eclipse.jst.jee.server:_board"/></Host>
<%@ 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>
<form action="${pageContext.request.contextPath}/result">
<input type="text" name="num1" />
<input type="text" name="num2" />
<input type="submit"/>
</form>
</body>
</html>
result.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>
합 = ${sum}
</body>
</html>
CustomTag ( 커스텀 태그 )
Date 오늘 날짜 출력 taglib 부분과 출력 부분 확인
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="tf" tagdir="/WEB-INF/tags" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<tf:now/>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="tf" tagdir="/WEB-INF/tags" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<tf:toSpan color="red" iterNum="3">ㅎㅇ </tf:toSpan>
</body>
</html>
'프로젝트 기반 자바(JAVA) 응용 SW개발자 취업과정' 카테고리의 다른 글
2023-08-10 60일차 (0) | 2023.08.10 |
---|---|
2023-08-09 59일차 (0) | 2023.08.09 |
2023-08-07 57일차 (0) | 2023.08.07 |
2023-08-04 56일차 (0) | 2023.08.04 |
2023-08-03 55일차 (0) | 2023.08.03 |