1. Spring Boot 설치

- java-21 설치가 되어있다는 가정

https://spring.io/ ▶ Projects메뉴 ▶ Spring tool 4 
▶ 4.24.0 - Windows X86_64 설치(spring-tool-suite-4-4.24.0.RELEASE-e4.32.0-win32.win32.x86_64.self-extracting.jar) 
▶ spring boot 폴더 만들어서 여기에 압축 풀기 ▶ contents.zip 압축 여기에 풀기 ▶ sts-4.24.0.RELEASE폴더 
▶ SpringToolSuite4.exe 가 실행파일임
파일 ▶ NEW ▶ Spring Starter Project
▶ Name test로 변경, Type Maven으로 변경, Packaging War로 변경, Java version 21로 변경, Group com.example.test로 변경, pacakge com.example.test로 변경 ▶ Dependencies 단계에서 맨아래 Web클릭 후 Spring Web 체크 ▶ Finish


* resources ▶ static : CSS 같은 정적 코드 위치
* application.properties : 설정값 작성
* src ▶ main ▶ webapp : War


2. JSP 설치

부트는 JSP를 기본적으로 지원 안함. 별도 설치 필요.
Help ▶ Eclipse MarketPlace ▶ jsp 검색 ▶ Eclipse EnterPrise Java and Web Developer Toos 3.33 설치 ▶ Confirm ▶ Accept 선택 Finish ▶ Trust Artifacts 단계에서 Select All 클릭 후 Trust Selected 클릭 ▶ Restart 클릭

webapp 폴더 안에 WEB-INF 폴더 생성 ▶ 그 안에 view 폴더 생성 

src/main/java 우클릭 패키지 com.example.test.controller 입력해서 생성 ▶ 패키지 안에 HomeController 클래스 생성 
▶ 컨트롤러 세팅

@Controller
public class HomeController {

@RequestMapping("/")
@ResponseBody
   public String home() {
        return "hello, Spring boot!!";
   }
}


▶ Run - Spring boot app로 실행해서 에러 안뜨면 세팅 성공 ▶ 브라우저에 http://localhost:8080/치면 출력 잘됨
* 톰캣이 내장되어있어서 실행 가능


3. 서버 포트 설정 변경해보기

application.properties에서 설정 변경  ▶

spring.application.name=test

#server
server.servlet.context-path=/test
server.port=8888


▶ 서버 껐다가 다시 켜기 ▶ 브라우저에 http://localhost:8888/ 입력하면 출력 잘됨


4. JSTL 의존성 주입

JSP - javax.servlet.jstl  의존성 주입 필요

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
</dependency>
=> 자카르타로 변경


pom.xml ▶ https://maven.apache.org/xsd/maven-4.0.0.xsd 에러나면 http로 바꾸거나 다운로드 ▶내용 수정

<!--JSP 사용하기위해 자카르타 추가-->
<dependency>
   <groupId>jakarta.servlet</groupId>
   <artifactId>jakarta.servlet-api</artifactId>
</dependency>

<dependency>
      <groupId>org.glassfish.web</groupId>
      <artifactId>jakarta.servlet.jsp.jstl</artifactId>
</dependency>

<dependency>
   <groupId>jakarta.servlet.jsp.jstl</groupId>
   <artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
</dependency>

<!--톰캣-->
<dependency>          
     <groupId>org.apache.tomcat.embed</groupId>
     <artifactId>tomcat-embed-jasper</artifactId>
 </dependency>

▶ views 폴더에 index.jsp 만들고 HomeController에 

@RequestMapping("/welcome")
public String welcome() {
     return "WEB-INF/views/index.jsp";
}

내용 추가 ▶ 서버 재실행 ▶ 브라우저에 http://localhost:8888/test/welcome 치면 출력 잘됨


5. View resolver 설정

application.properties ▶ 

#view resolver
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp


▶ HomeController 수정

@Controller
public class HomeController {

@RequestMapping("/")
@ResponseBody
   public String home() {
        return "hello, Spring boot!!";
   }

@RequestMapping("/welcome")
   public String welcome() {
         return "index";
   }
}

6. 파라미터 테스트

HomeController ▶

@RequestMapping("/modelTest")
public String modelTest(Model model) {
   model.addAttribute("name", "abcdefg");
   model.addAttribute("tel", "123-1234");
   return "modelTest";
}

 

▶ modeTest.jsp ▶

<html>
  <head>
     <meta charset="UTF-8">
     <title>modelTest.jsp</title>
  </head>
  <body>
     이름 : ${name} <br>
     전화번호 : ${tel} <br>
  </body>
</html>

▶ http://localhost:8888/test/modelTest


7. JDBC 의존성 주입

org.springframework.boot spring-boot-starter-jdbc 
cohttp://m.oracle.database.jdbc ojdbc8
의존성 주입 필요

pom.xml 추가 ▶

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
    <groupId>com.oracle.database.jdbc</groupId>
    <artifactId>ojdbc8</artifactId>
    <scope>runtime</scope>
</dependency>


application.properties 추가 ▶

#jdbc
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe
spring.datasource.username=fin02
spring.datasource.password=fin02

8. MyBatis

프로젝트 우클릭 ▶ Spring ▶ Add Starters ▶ Available 영역에 mybatis 검색 ▶ MyBatis Framework 체크 ▶ pom.xml 체크 ▶ Finish ▶ pom.xml 들어가면 의존성 주입 되어있음

application.properties ▶ 

#mybatis
mybatis.type-aliases-package=com.example.test.dto
mybatis.mapper-locations=/mybatis/**/*-mapper.xml
mybatis.configuration.map-underscore-to-camel-case=true


src/main/resources 안에 mybatis 폴더 추가 ▶ mybatis 폴더 안에 student 폴더 추가 ▶ student-mapper.xml 파일 생성

student-mapper.xml ▶ 

<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">

 
* 독타입 에러나면
windows ▶ preference ▶ Language Servers 더블클릭 ▶ XML 체크 해제 ▶ Apply

▶ 내용 입력

<mapper namespace="mybatis.student.student-mapper">
    <select id="listStudent" resultType="StudentDTO">
         select * from student
    </select>
</mapper>

 

▶com.example.test.mapper 패키지 만들기

@Service
public class StudentMapper {

    @Autowired
    private SqlSession sqlSession;

    public List listStudent(){
       return sqlSession.selectList("listStudent");
    }
}


▶ StudentController


9. 학생관리 예제

StudentController
package com.example.test.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.example.test.dto.StudentDTO;
import com.example.test.mapper.StudentMapper;


@Controller
public class StudentController {

    @Autowired
    private StudentMapper studentMapper;


    @RequestMapping("/list.do")
    public String list(Model model) {
        List<StudentDTO> list = studentMapper.listStudent();
        model.addAttribute("listStudent", list);
        return "list";
    }

    @GetMapping("/insert.do")
        public String insertForm(){
        return "insert";
    }

    @PostMapping("/insert.do")
        public String insert(@ModelAttribute StudentDTO dto){
        int res = studentMapper.insertStudent(dto);
        return "redirect:welcome";
    }

    @GetMapping("/delete.do")
        public String deleteForm(){
        return "delete";
    }

    @PostMapping("/delete.do")
        public String delete(@RequestParam String id){
        int res = studentMapper.deleteStudent(id);
        return "redirect:welcome";
    }

    @GetMapping("/find.do")
        public String findForm() {
        return "find";
    }

    @PostMapping("/find.do")
        public String find(Model model, @RequestParam String name){
        List<StudentDTO> list = studentMapper.findStudent(name);
        model.addAttribute("listStudent", list);
        return "list";
    }
}

 

StudentMapper
@Service
public class StudentMapper {

    @Autowired
    private SqlSession sqlSession;

    public List<StudentDTO> listStudent(){
        return sqlSession.selectList("listStudent");
    }

    public int insertStudent(StudentDTO dto) {
        return sqlSession.insert("insertStudent", dto);
    }

    public int deleteStudent(String id) {
        return sqlSession.delete("deleteStudent", id);
    }

    public List<StudentDTO> findStudent(String name){
        return sqlSession.selectList("findStudent", name);
    }

}

 

student-mapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
 
    <mapper namespace="mybatis.student.student-mapper">
       <select id="listStudent" resultType="StudentDTO">
           select * from student
        </select>

       <insert id="insertStudent" parameterType="StudentDTO">
            insert into student values(#{id}, #{name}, #{cname})
        </insert>

       <delete id="deleteStudent" parameterType="String">
            delete from student where id=#{id}
        </delete>
   
        <select id="findStudent" parameterType="String" resultType="StudentDTO">
            select * from student where name = #{name}
        </select>
    </mapper>

 

list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
    <head>
        <title>학생목록</title>
    </head>
    <body>
        <div align="center">
            <hr color="green" width="300">
            <h2>학 생 목 록 페 이 지</h2>
            <a href="index.do"> 처음으로 </a>
            <hr color="green" width="300">
            <a href="insert.do"> 학생등록페이지 바로가기</a>

            <table border="1" width="500">
                <tr bgcolor="yellow">
                    <th>아이디</th>
                    <th>학생명</th>
                    <th>학급명</th>
                </tr>
                <c:if test="${empty listStudent}">
                     <tr>
                         <td colspan="3">등록된 학생이 없습니다.</td>
                     </tr>
                </c:if>
                <c:forEach var="dto" items="${listStudent}">
                 <tr>
                  <td align="center">${dto.id}</td>
                  <td align="center">${dto.name}</td>
                  <td align="center">${dto.cname}</td>
                  </tr>
                </c:forEach>
            </table>
     </div>
     </body>
</html>

 

insert.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
     <head>
          <meta charset="UTF-8">
          <title>insertForm.jsp</title>
     </head>
     <body>
          <div align="center">
               <hr color="green" width="300">
               <h2>학 생 등 록 페 이 지</h2>
               <hr color="green" width="300">
               <form name="f1" action="insert.do" method="post">
                    <table border="1">
                         <tr>
                              <td>
                                   아이디 : <input type="text" name="id" id="mid" title="아이디"><input type="button" value="중복확인"
                                                   onclick="idCheck()"><br>
                                   학생명 : <input type="text" name="name" title="학생명"><br>
                                   학급명 : <input type="text" name="cname" title="학급명"><br>
                              <input type="submit" value="입력">
                              <input type="reset" value="다시입력">
                              </td>
                         </tr>
                   </table>
          </form>
     </div>
</html>

 

find.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>
               <div align="center">
               <hr color="green" width="300">
               <h2>학 생 찾 기 페 이 지</h2>
               <hr color="green" width="300">
               <form name="f3" action="find.do" method="post">
                    <table border="1">
                         <tr>
                              <td>
                                   학생명 : <input type="text" name="name">
                                   <input type="submit" value="찾기">
                              </td>
                          </tr>
                    </table>
               </form>
     </div>
</body>
</html>

 

delete.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
     <head>
          <meta charset="UTF-8">
          <title>delete.jsp</title>
     </head>
     <body>
          <div align="center">
               <hr color="green" width="300">
                    <h2>학 생 삭 제 페 이 지</h2>
               <hr color="green" width="300">
               <form name="f2" action="delete.do" method="post">
                    <table border="1">
                         <tr>
                              <td>
                                   아이디 : <input type="text" name="id">
                                  <input type="submit" value="삭제">
                              </td>
                         </tr>
                    </table>
               </form>
         </div>
     </body>
</html>

 

+ Recent posts