안녕하세요. 저번 포스팅으로 Spring Legacy MVC Project가 사라져서 수동으로
프로젝트를 만드는 방법을 소개시켜드렸습니다.
https://uno-kim.tistory.com/408
Spring Legacy MVC Project 만들 수 없을 때 해결 방법
안녕하세요. 2024년 중반이 되어서도 스프링 부트가 아닌 Spring Legacy MVC Project를 통해당장이라도 작게 토이프로젝트라던가 잠깐 협업을 해야하는 경우가 있을 수 있습니다.그러나 요즘 STS-3에서부
uno-kim.tistory.com
이제는 JSP와 서버 등을 연결하는 방법에 대해서 설명하고 예시 파일을 올려서 앞으로 저나
다른사람이 이런경우 이런 포스팅을 보지않고도 바로 다운로드 받아서 쓸수 있도록 파일도 올려놓겠습니다.
1. 컨트롤러기능 만들기
이젠 빈등록을 통해서 jsp파일이 자동적으로 읽히도록 설정하는 방법에 대해 알려드리겠습니다.
우선먼저 servlet-context.xml을 수정해야합니다. 아래 bean 과 컨텍스트, mvc 태그들을 넣어줍니다.
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.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-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<context:component-scan base-package="com.example.controller"></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
com.example.controller 로 설정을 했는데 이제 이 루트를 실제로 만들어주고 컨트롤러를 만들어야합니다.
패키지를 java에 떡 하고 만들어줍니다. 그럼 자바파일의 경로는
SpringLegacy\src\main\java\com\example\controller\SelfController.java
가되겠습니다.
그리고 이제 생성한 자바소스에 소스를 입력해줍니다.
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class SelfController {
@GetMapping(value = "/hello")
public void hello() {
System.out.println("hello");
}
}
이제 한번 실행을 해서 잘나타나나 봅니다.
실행시 오류가 난다면
톰캣서버 설정을 / 로 변경해서 진행해줍니다.
그럼이제
정상적으로 헬로 콘솔이 나타납니다.
2. 컨트롤러와 - JSP 연결
servlet-context.xml에 /WEB-INF/views/ 를 넣었었습니다. 따라서 WEB-INF 폴더에 views 폴더를 만들어 jsp를 만들어줍니다.
WEB-INF폴더 내에 views 폴더를 만들고 hello.jsp 파일을 만든상태
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<h1>Hello World!!!</h1>
</body>
</html>
위 처럼 만들고 바로 새로고침을 한다면 아래처럼 나타납니다.
이것으로 컨트롤러 연결을 완료했습니다.
댓글