728x90
300x250

[JSP] 25. jQuery와 Ajax 멀티 파일 업로드(개선), POST전송, JSON - 구성하기(2)


1부에 이어서 계속 소개하도록 하겠다.


1. [JSP] 24. jQuery와 Ajax 멀티 파일 업로드(개선), POST전송, JSON - 구성하기(1), 2020-10-03

https://yyman.tistory.com/1445



12. jQuery 다운받기


https://jquery.com/download/


사이트에 접속한다.



그림 19. jQuery 다운로드 사이트 (2020-10-03 현재 모습)


이 글에서는 "Download the uncompressed development jQuery 3.5.1"을 사용하였다.



그림 20. jQuery 다운로드 위치


1단계: 프로젝트 폴더를 찾는다.

2단계: /src/main/webapp/에 들어간다.

3단계: js폴더를 만든다.

4단계: /src/main/webapp/js/jquery-3.5.1.js를 넣어준다.




13. Controller - /board/ListJSONController.java


경로: /src/main/java/com/example/web/controller/board/ListJSONController.java


package com.example.web.controller.board;


import java.io.IOException;

import java.io.PrintWriter;

import java.util.ArrayList;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import org.json.JSONArray;

import org.json.JSONObject;


import com.example.web.controller.Controller;

import com.example.web.model.CompUsers;


public class ListJSONController implements Controller {


@Override

public void execute(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

// 1. 공통 선언

res.setCharacterEncoding("UTF-8");

        res.setContentType("application/json");

        

        // 1-1. ArrayList만 사용할 경우의 반응(방법 1)

        /*

        //  컬렉션 타입

        ArrayList<CompUsers> list = new ArrayList<CompUsers>();

        list.add(new CompUsers("user","mole", 1));

        list.add(new CompUsers("sumin", "pass", 0));

        list.add(new CompUsers("smkim", "php", 1));

      

        PrintWriter out = res.getWriter();


        // 

        JSONObject jsonList = new JSONObject();

        JSONArray itemList = new JSONArray();

        

        jsonList.put("list", list);

        

        out.println(jsonList);

        */

        

        // 1-2. ArrayList와 itemList(JSONArray) 적용

        JSONObject jsonList = new JSONObject();

        JSONArray itemList = new JSONArray();

        

        CompUsers reqUser = new CompUsers();

        

        if ( req.getParameter("username") != null) {

        reqUser.setUsername(req.getParameter("username"));

        System.out.println("참" + reqUser.getUsername());

        }

        

        if ( req.getParameter("password") != null)

        reqUser.setPassword(req.getParameter("password"));

        

        if ( req.getParameter("enanbled") != null)

        reqUser.setEnabled(Integer.valueOf( req.getParameter("enabled")) );

        

        PrintWriter out = res.getWriter();


        ArrayList<CompUsers> list = new ArrayList<CompUsers>();

        list.add(new CompUsers("user","mole", 1));

        list.add(new CompUsers("sumin", "pass", 0));

        list.add(new CompUsers("smkim", "php", 1));

        

        for (CompUsers user:list) {

       

        JSONObject node = new JSONObject();

        node.put("enabled", user.getEnabled());

        node.put("password", user.getPassword());

        node.put("username", user.getUsername());


        itemList.put(node);

        

        }

        

        jsonList.put("list", itemList);

        jsonList.put("command", "바둑이");

        

        // DTO(또는 Model) 단독으로 입력불가

        // jsonList.put("paramUser", reqUser);

        ArrayList<CompUsers> list2 = new ArrayList<CompUsers>();

        list2.add(reqUser);

        //jsonList.put("paramUser", reqUser);

        jsonList.put("paramUser", list2);

        

        out.println(jsonList);

        

        out.flush();

        out.close();


}


}



파일명: ListJSONController.java


[첨부(Attachments)]

ListJSONController.zip




14. Controller - /board/MultiUploadController.java


경로: /src/main/java/com/example/web/controller/board/MultiUploadController.java


package com.example.web.controller.board;


import java.io.IOException;

import java.io.PrintWriter;

import java.util.List;

import java.util.Map;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import com.example.web.controller.Controller;

import com.example.web.util.HttpUtil;


public class MultiUploadController implements Controller {


@Override

public void execute(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

HttpUtil.uploadFile(req, res);

/*

res.setCharacterEncoding("UTF-8");

        res.setContentType("application/json");

        

        @SuppressWarnings("unchecked")

List<Object> fileInfoList = (List<Object>) req.getAttribute("fileInfoList");

        @SuppressWarnings("unchecked")

List<String> reqInfoList = (List<String>) req.getAttribute("reqInfoList");

        

        // Model 구성해서 만들어도 무방

        HttpUtil.getFileinfoParser(fileInfoList, null);

        HttpUtil.getReqinfoParser(reqInfoList, null);

*/


res.setCharacterEncoding("UTF-8");

PrintWriter out = res.getWriter();

out.print("success");

out.flush();

out.close();

}


}



파일명: MultiUploadController.java


[첨부(Attachments)]

MultiUploadController.zip




14. View 화면 구성하기 - index.jsp (index.do 파일 시작페이지 만들기)


Index.jsp 파일을 시작페이지로 만드는 작업이다.


경로: /src/main/webapp/index.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<jsp:forward page="index.do" />


파일명: index.jsp


[첨부(Attachments)]

index.zip


FrontController.java 파일에 index.do를 command에서 식별할 수 있도록 해준다.

그리고 forward로 redirect처리하여 시작페이지로 보여지게 하는 원리이다.


-> 연계 작업: web.xml, FrontController.java 변경 작업을 해줘야 한다.



그림 21. index.jsp의 위치



15. View - /webapp/WEB-INF/views/index.jsp - 실제 시작 페이지


경로: /src/main/webapp/WEB-INF/views/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>


</body>

</html>


파일명: index.jsp


[첨부(Attachments)]

index.zip





16. Controller(Servlet) - FrontController


경로: /src/main/java/com/example/web/controller/FrontController.java


package com.example.web.controller;


import java.io.IOException;


import javax.servlet.ServletConfig;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import org.json.JSONArray;

import org.json.JSONObject;


import com.example.web.controller.board.InsertController;

import com.example.web.controller.board.ListJSONController;

import com.example.web.controller.board.MultiUploadController;

import com.example.web.util.HttpUtil;


public class FrontController extends HttpServlet {

private static final long serialVersionUID = 1L;

private String charset = null;

       

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

doAction(req, res, "GET");

}


protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

doAction(req, res, "POST");

}


protected void doAction(HttpServletRequest req, 

HttpServletResponse res,

String flag) 

throws ServletException, IOException {

ServletConfig sc = this.getServletConfig();

charset = sc.getInitParameter("charset");


req.setAttribute("charset", charset);

req.setCharacterEncoding(charset);

res.setContentType("text/html; charset=" + charset);


String uri = req.getRequestURI();

String conPath = req.getContextPath();

String command = uri.substring(conPath.length());


Controller subController = null;


// GET 전송방식만

if(command.equals("/board/write.do") &&

flag.contentEquals("GET")) {

System.out.println("write - page");

System.out.println("----------------");

HttpUtil.forward(req, res, "/WEB-INF/views/board/insert.jsp");

}

// POST 전송방식만

else if(command.equals("/board/write_result.do") && 

flag.contentEquals("POST")){


System.out.println("write - result");

System.out.println("----------------");

subController = new InsertController();

subController.execute(req, res);

}

else if(command.equals("/board/list_json.do") &&

flag.contentEquals("POST")) {

System.out.println("write - result");

System.out.println("----------------");

subController = new ListJSONController();

subController.execute(req, res);

}

else if(command.equals("/board/upload.do") &&

flag.contentEquals("POST")) {

System.out.println("multipart/form - upload");

System.out.println("----------------");

subController = new MultiUploadController();

subController.execute(req, res);

}

else if (command.equals("/index.do")){


System.out.println("index.do");

System.out.println("----------------");

HttpUtil.forward(req, res, "/WEB-INF/views/index.jsp");

}

}

}



파일명: FrontController.java


[첨부(Attachments)]

FrontController.zip





17. View - /board/insert.jsp


경로: /src/main/webapp/WEB-INF/views/board/insert.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>jQuery.post demo</title>

<script src="../js/jquery-3.5.1.js"></script>

<script>

$(document).ready(function(){


// 1. Ajax - Post 결과 출력

$( "#searchForm" ).submit(function( event ) {

 

  // Stop form from submitting normally

  event.preventDefault();

 

// Get some values from elements on the page:

  var $form = $( this ),

    term = $form.find( "input[name='s']" ).val(),

    url = $form.attr( "action" );

 

  // Send the data using post

  var posting = $.post( url, { s: term } );

 

  // Put the results in a div

  posting.done(function( data ) {

    alert( "Data Loaded: " + data );

    var content = data ;

    $( "#result1" ).html( content );

   

});

// Attach a submit handler to the form

});

// 2. Ajax 버튼(수작업 쿼리 - 보내기)

$('#check').click(function(){

    alert('특정 파라메터 보내기\n------------');

var query = {username:'한글', password:1234, enabled:1};

   

    $.ajax({

    url : "list_json.do",

    type : "POST",

    dataType : "json",

    data : jQuery.param(query),

    success : function(data) {

    $.each(data, function(key, value) { //  { logList:[{}], command:{} } 이런구조임


        //alert('성공');

    if (key == "list") {

       

    for (var i = 0; i < value.length; i++) {

       

    // alert(value[i].username);

   

    }

   

    } else if (key == "command") {

       

    $('#result2').html(value);

   

    }else if(key=="paramUser"){


// ArrayList로 받아서 처리함.

    alert(value[0].username + "/" + value.username);


// 인식 여부 (ArrayList로 안 하면, 알수없는 객체로 인식함)

/*

    for (var i = 0; i < value.length; i++) {

    alert(i + "/" + value[i].username);

    }

    */

        } // end of if

   

    });

   

    },

    error : function(msg) {

    alert("error" + msg);

    }

    });

   

});


// 4. 다중 업로드 기능

$(function(){

 

    $('#uploadBtn').on('click', function(){

        uploadFile();

    });

 

});

 

function uploadFile(){

    

    var form = $('#uploadForm')[0];

    var formData = new FormData(form);

 

    $.ajax({

        url : 'upload.do',

        type : 'POST',

        data : formData,

        contentType : false,

        processData : false,

    success : function(data) {

alert('성공');

alert(data);

    },

    error : function(msg) {

    alert("error" + msg);

    }

        

    }).done(function(data){

        callback(data);

    });

}

});

</script>

</head>

<body>

 

 <h3>Ajax - 전송</h3>

<form action="write_result.do" id="searchForm">

  <input type="text" name="s" placeholder="Search...">

  <input type="submit" value="Search">

</form>

<div id="result1"></div>


<h3>JSON 전송 확인(jQuery 미적용)</h3>

<form action="list_json.do" method="POST">

  <input type="text" name="keyword" placeholder="Search...">

  <input type="submit" value="Search">

</form>


<h3>JSON 가져오기(jQuery 적용)</h3>

<label for="userid">USER ID</label>

<input type="text" id="userid">

<button id="check">버튼 누르기</button>

<p id="result2"></p>


<h3>Ajax 기반 - 다중 업로드</h3>

<form id="uploadForm" enctype="multipart/form-data">

<input type="hidden" name="token" value="2">

<input type="text" name="usrID" size="10">

<input type="file" name="uploadFile" multiple>

    <button type="button" id="uploadBtn">Save</button>

</form>

 

</body>

</html>


파일명: insert.jsp


[첨부(Attachments)]

insert.zip




18. View - /board/result.jsp


경로: /src/main/webapp/WEB-INF/views/board/result.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%

String text = (String)request.getParameter("s");

%>

<%= text %>


파일명: result.jsp


[첨부(Attachments)]

result.zip




19. View - /board/uploadResult.jsp


경로: /src/main/webapp/WEB-INF/views/board/uploadResult.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%@ page import="java.util.*" %>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>업로드 - 결과</title>

</head>

<body>

<h3>업로드 결과</h3>

<%


//Object name = request.getAttribute("usrID");

//Object login = request.getAttribute("login");

Object obj = request.getAttribute("reqMap");

Map<String, Object> map = null;

if(obj != null){

map = (HashMap<String, Object>)obj;

}


%>


<table style="width:700px;border:1px solid #e2e2e2;">

<tr>

<td style="width:20%;">

<%

        out.println("name : " + map.get("usrID") + "<br />");

%>

</td>

<td style="width:20%;border-left:1px solid #e2e2e2;">

<%

out.println("login : " + map.get("usrPasswd") + "<br />");

%>

</td>

</tr>

<tr>

<td>

</td>

<td>

</td>

</tr>

</table>


</body>

</html>


파일명: uploadResult.jsp


[첨부(Attachments)]

uploadResult.zip





* 맺음글(Conclusion)


jQuery, Ajax, 멀티 파일 업로드, POST 전송, JSON 구성에 대해서 살펴보았다.



* 참고 자료(References)


1. jsp json 데이터 받기, https://happy-hs.tistory.com/16, Accessed by 2020-10-03, Last Modified 2018-09-20.

2. [Java] JSP - JSON 데이터 주고 받기 - JSONParser, https://kiwinam.com/posts/11/jsp-json-parser/, Accessed by 2020-10-03, Last Modified 2017-05-03.

3. jQuery.post() | jQuery API Documentation, https://api.jquery.com/jquery.post/, Accessed by 2020-10-03, Last Modified .

4. [Servlet] JSON 문자열로 응답하기, https://noritersand.github.io/servlet/servlet-json-%EB%AC%B8%EC%9E%90%EC%97%B4%EB%A1%9C-%EC%9D%91%EB%8B%B5%ED%95%98%EA%B8%B0/, Accessed by 2020-10-03, Last Modified 2014-01-14.

5. Java File Upload Example with Servlet, JSP and Apache Commons FileUpload, https://www.codejava.net/java-ee/servlet/apache-commons-fileupload-example-with-servlet-and-jsp, Accessed by 2020-10-03, Last Modified 2019-06-25.

반응형
728x90
300x250

[JSP] 24. jQuery와 Ajax 멀티 파일 업로드(개선), POST전송, JSON - 구성하기(1)


이번에 게시할 프로젝트는 jQuery, Ajax, 파일 업로드, POST전송, JSON 구성하기라는 거창한 제목이긴 하지만, 실제로는 기능별로 분리하여 작업한 결과이다.

이 글은 기존에 게시글에서 작성한 업로드 기능에 "토큰 인증 방식", "파라메터 문자열 분석 및 분리" 등의 기능을 추가하였다.

아무래도 업로드 기능이니깐 그냥 업로드 하는 것보다는 토큰 하나 넣어주는 게 좋지 않겠냐는 생각이다.


1. [JSP] 12. Jsp/Servlet(MVC) Maven 기반의 다중 파일 업로드, 다운로드 구현(1), 2020-09-24

https://yyman.tistory.com/1414

2. [JSP] 13. Jsp/Servlet(MVC) Maven 기반의 다중 파일 업로드, 다운로드 구현(2), 2020-09-24
https://yyman.tistory.com/1415

3. [JSP] 21. Jsp/Servlet(MVC) Maven 기반의 다중 업로드, 다운로드, 삭제 구현(1), 2020-10-01

https://yyman.tistory.com/1436




그림 1. COS(Servlet)


이거는 오래되서 미지원이다. (일부 인터넷 글에 따르면, 사용중이더라 이런 글들이 있는데 태스트를 해본 바로는 오류가 발생하고 안 된다.

(구체적으로 servlet 패키지에서 충돌남)


* IDE: Spring Tool-Suite 4.4 4-4.7.2. RELEASE (Eclipse)

* MVN(pom.xml)

   - javax.servlet-api 4.0.1 (https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api)

   - json - 20200518 (https://mvnrepository.com/artifact/org.json/json)

   - commons-io - 2.8.0 (https://mvnrepository.com/artifact/commons-io/commons-io)

   - commons-fileupload - 1.4 (https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload)

* Javascript: jquery-3.5.1.js


DB 자체를 제거했으며, 이해를 돕기 위해서 매우 순수한 구조로 작성되었다.


자료구조에서 LinkedList에 해당하는 자바의 ArrayList와 Map를 파일 업로드 부분에 적용하였음.



1. 결과


이번에 만들 작업에 관한 결과이다. 결과를 보고 무엇을 만들지 생각하는 방법을 터득했으면 좋겠다.



그림 1. 작업 결과



그림 2. 작업 결과 - 출력된 HTML 소스(1)



그림 3. 작업 결과 - 출력된 HTML 소스(2)



그림 4. 작업 결과(2) - ListJSONController.java



그림 5. 작업결과(3) - 파일 업로드 기능(1)



그림 6. 작업결과(4) - 파일 업로드 기능(2)



그림 6-1. JSON - 결과(1)



그림 6-2. JSON - 결과(2)



그림 6-3. JSON - 결과(3)



그림 6-4. JSON - 결과(4)




2. 프로젝트 구성도


만들어야 할 프로그램들이다. 조금 양이 많다.



그림 7. 프로젝트 구성




3. 프로젝트 생성


프로젝트 생성하는 방법에 대해서 소개하도록 하겠다.



그림 8. 프로젝트 생성하기(1)


File을 누른다.

New-> Maven Project를 클릭한다.

(1단계 중략 - Next만 눌러도 되는 부분)



그림 9. 프로젝트 생성하기(2)


webapp를 검색한다.

org.apache.maven.archetypes    |  maven-archetype-webapp  1.4을 선택한다.

Next를 누른다.



그림 10. 프로젝트 생성하기(3)


Group Id와 Artifact Id를 입력한다.

Finish를 누른다.



4. 프로젝트 속성 - Build Path, Project Factes 설정하기


자바 버전을 변경할 것이다.



그림 11. 프로젝트 선택 후의 마우스 오른쪽 버튼 메뉴


프로젝트를 선택한 후, 마우스 오른쪽 버튼으로 클릭한다.

Properties를 클릭한다.



그림 12. Java Build Path


Java Build Path를 클릭한다.

JRE System Library 버전을 14로 바꿔준다. [Edit 클릭 -> JRE -> Java SE -14]




그림 13. Project Factes


Project Factes를 클릭한다.

Java의 버전을 14로 바꿔준다.



5. pom.xml 수정하기


pom.xml 수정에 관한 것이다.


<?xml version="1.0" encoding="UTF-8"?>


<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>


  <groupId>com.webedu</groupId>

  <artifactId>exampleAjax</artifactId>

  <version>0.0.1-SNAPSHOT</version>

  <packaging>war</packaging>


  <name>exampleAjax Maven Webapp</name>

  <!-- FIXME change it to the project's website -->

  <url>http://www.example.com</url>


  <properties>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <maven.compiler.source>1.7</maven.compiler.source>

    <maven.compiler.target>1.7</maven.compiler.target>

  </properties>


  <dependencies>

    <dependency>

      <groupId>junit</groupId>

      <artifactId>junit</artifactId>

      <version>4.11</version>

      <scope>test</scope>

    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->

<dependency>

    <groupId>javax.servlet</groupId>

    <artifactId>javax.servlet-api</artifactId>

    <version>4.0.1</version>

    <scope>provided</scope>

</dependency>

<!-- https://mvnrepository.com/artifact/org.json/json -->

<dependency>

    <groupId>org.json</groupId>

    <artifactId>json</artifactId>

    <version>20200518</version>

</dependency>

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->

<dependency>

    <groupId>commons-io</groupId>

    <artifactId>commons-io</artifactId>

    <version>2.8.0</version>

</dependency>

<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->

<dependency>

    <groupId>commons-fileupload</groupId>

    <artifactId>commons-fileupload</artifactId>

    <version>1.4</version>

</dependency>

  </dependencies>


  <build>

    <finalName>exampleAjax</finalName>

    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->

      <plugins>

        <plugin>

          <artifactId>maven-clean-plugin</artifactId>

          <version>3.1.0</version>

        </plugin>

        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->

        <plugin>

          <artifactId>maven-resources-plugin</artifactId>

          <version>3.0.2</version>

        </plugin>

        <plugin>

          <artifactId>maven-compiler-plugin</artifactId>

          <version>3.8.0</version>

        </plugin>

        <plugin>

          <artifactId>maven-surefire-plugin</artifactId>

          <version>2.22.1</version>

        </plugin>

        <plugin>

          <artifactId>maven-war-plugin</artifactId>

          <version>3.2.2</version>

        </plugin>

        <plugin>

          <artifactId>maven-install-plugin</artifactId>

          <version>2.5.2</version>

        </plugin>

        <plugin>

          <artifactId>maven-deploy-plugin</artifactId>

          <version>2.8.2</version>

        </plugin>

      </plugins>

    </pluginManagement>

  </build>

</project>



파일명: pom.xml


[첨부(Attachments)]

pom.zip



6. Servlet 생성하기


서블렛 생성에 대한 것이다.



그림 14. Java Resources 폴더의 마우스 오른쪽 버튼 모습


Java Resources를 마우스 오른쪽 버튼으로 클릭한다.

New->Servlet을 클릭한다.



그림 15. Create Servlet


Java package를 입력해준다. (예: com.example.web.controller)

Class Name을 입력해준다. (예: FrontController)


Finish를 누른다.




7. Web.xml 수정하기


경로: /src/main/webapp/WEB-INF/web.xml


<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

xmlns="http://java.sun.com/xml/ns/javaee" 

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 

id="WebApp_ID" version="3.0">

  <display-name>Archetype Created Web Application</display-name>

  <welcome-file-list>

  <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>

  <servlet>

  <servlet-name>FrontController</servlet-name>

  <servlet-class>com.example.web.controller.FrontController</servlet-class>

  <init-param>

<param-name>charset</param-name>

<param-value>UTF-8</param-value>

</init-param>

  </servlet>

  <servlet-mapping>

  <servlet-name>FrontController</servlet-name>

  <url-pattern>*.do</url-pattern>

  </servlet-mapping>

</web-app>


파일명: web.xml


[첨부(Attachments)]

web.zip



8. Controller - Interface 생성하기


경로: /src/main/java/com/example/web/controller/Controller.java


package com.example.web.controller;


import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public interface Controller {


public void execute(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException;


}




파일명: Controller.java


[첨부(Attachments)]

Controller.zip



9. Controller - board/InsertController.java


경로: /src/main/java/com/example/web/controller/board/InsertController.java


package com.example.web.controller.board;


import java.io.IOException;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import com.example.web.controller.Controller;

import com.example.web.util.HttpUtil;


public class InsertController implements Controller {


@Override

public void execute(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

HttpUtil.forward(req, res, "/WEB-INF/views/board/result.jsp");


}


}


파일명: InsertController.java


[첨부(Attachments)]

InsertController.zip




10. Util - util/HttpUtil.java (업로드 개선 및 문자열 구분 처리)


토큰, 업로드 개선, 문자열 구분 처리 등을 추가적으로 담아보았다.


경로: /src/main/java/com/example/web/util/HttpUtil.java


package com.example.web.util;


import java.io.File;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;


import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class HttpUtil extends HttpServlet {


private static final long serialVersionUID = 1L;


private static String charset = null; // 문자열


    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB // 

    private static final long MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB

    private static final long MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB

 

private static String UPLOAD_FOLDER = "upload";

private static String UPLOAD_TMP_FOLDER = File.separator + "WEB-INF" + File.separator + "temp";

private static List<String> reqInfoList = null; // req 정보(MultiRequest) - 문맥 방식

private static List<Object> fileInfoList = null; // 다중 파일 지원 - 문맥 방식

private static Map<String, Object> reqInfoMap = null; // req 정보(MultiRequest) - Map 자료구조

private static Map<Integer, Map<String, Object>> fileInfoMap = null; // 다중 파일 지원 - Map 자료구조

private static boolean FILE_TOKEN_CHECK = false; // req 토큰 체크하기 

private static String FILE_AUTH_TOKEN_KEY = null; // req 인증키 추가

private static String FILE_RESTRICT_EXT = ".jpg.jpeg.bmp.png.gif.txt"; // 파일 확장자 제한

private static int reqNum = 0; // reqNum

private static int fileNum = 0; // fileNum


public static void forward(HttpServletRequest req, HttpServletResponse res,

String path) throws ServletException, IOException {


try {

RequestDispatcher dispatcher = req.getRequestDispatcher(path);

dispatcher.forward(req, res);


}catch(Exception e) {

e.printStackTrace();

}

}

public static void uploadFile(HttpServletRequest req, HttpServletResponse res) throws

ServletException, IOException {


reqInfoList = new ArrayList<String>();

fileInfoList = new ArrayList<Object>();


fileInfoMap = new HashMap<Integer, Map<String, Object>>(); 

reqInfoMap = new HashMap<>();

// 파일 인증키 인증 완료 후 업로드

List<FileItem> tmpItems = new ArrayList<FileItem>();

FILE_AUTH_TOKEN_KEY = "1";

reqNum = 1;

fileNum = 1;

    

    PrintWriter out = res.getWriter();

    //out.println("<HTML><HEAD><TITLE>Multipart Test</TITLE></HEAD><BODY>");

try {

        

        //디스크상의 프로젝트 실제 경로얻기

        //String contextRootPath = "c:" + File.separator + "upload";

String dirName = UPLOAD_FOLDER ; 

// String dirName = "upload"; 

String contextRootPath = req.getSession().getServletContext().getRealPath("/") + dirName;

        System.out.println("실제경로:" + contextRootPath);

        

        //1. 메모리나 파일로 업로드 파일 보관하는 FileItem의 Factory 설정

        DiskFileItemFactory diskFactory = new DiskFileItemFactory(); // 디스크 파일 아이템 공장

        diskFactory.setSizeThreshold(MEMORY_THRESHOLD); // 업로드시 사용할 임시 메모리

        // diskFactory.setSizeThreshold(4096); // 업로드시 사용할 임시 메모리

        diskFactory.setRepository(new File(contextRootPath + UPLOAD_TMP_FOLDER)); // 임시저장폴더

        // diskFactory.setRepository(new File(contextRootPath + UPLOAD_TMP_FOLDER)); // 임시저장폴더

        

        //2. 업로드 요청을 처리하는 ServletFileUpload생성

        ServletFileUpload upload = new ServletFileUpload(diskFactory);

        // upload.setSizeMax(3 * 1024 * 1024); //3MB : 전체 최대 업로드 파일 크기

        upload.setSizeMax(MAX_REQUEST_SIZE);

        

        // sets maximum size of upload file(파일 단위 업로드 크기)

        upload.setFileSizeMax(MAX_FILE_SIZE);

        

        //3. 업로드 요청파싱해서 FileItem 목록구함​​

        List<FileItem> items = upload.parseRequest(req); 

        Iterator<FileItem> iter = items.iterator(); //반복자(Iterator)로 받기​            

        while(iter.hasNext()) { //반목문으로 처리​    

            FileItem item = (FileItem) iter.next(); //아이템 얻기

             //4. FileItem이 폼 입력 항목인지 여부에 따라 알맞은 처리

            

            if(item.isFormField()){ 

            //파일이 아닌경우

                processFormField(out, item);

                

            } else {

            //파일인 경우

            // System.out.println("오류:" + item.getName());

           

            // 버그 개선 item 이름값 비어있을 때

            if ( item.getName() != "") {

            tmpItems.add(item);

            // processUploadFile(out, item, contextRootPath);

            }

            // System.out.println("오류2:");

            }

        }

        

        // 파일 토큰 확인될 경우

        if ( FILE_TOKEN_CHECK ) {

       

        // 파일 업로드 처리

        for (FileItem readyItem: tmpItems)

        {

        processUploadFile(out, readyItem, contextRootPath);

        }

       

        }

        

        

        

    } catch(Exception e) {

        e.printStackTrace(out);

    }

//out.println( "usrID(Map): " + reqMap.get("usrID") );

//out.println( "usrPasswd(Map):" + reqMap.get("usrPasswd") );

    

    // out.println("</BODY></HTML>");

// req.setAttribute("usrID", reqMap.get("usrID"));

// req.setAttribute("login", 1);//Object Type으로 넘어감

    req.setAttribute("reqInfoMap", reqInfoMap);

    req.setAttribute("fileInfoMap", fileInfoMap);

    req.setAttribute("reqInfoList", reqInfoList);

    req.setAttribute("fileInfoList", fileInfoList);

    

// System.out.println("오류3:" + reqMap.get("usrID"));

    

}

//업로드한 정보가 파일인경우 처리

private static void processUploadFile(PrintWriter out, FileItem item, String contextRootPath)

throws Exception {

Map<String, Object> fileMapNode = new HashMap<String, Object>();

List<String> fileListNode = new ArrayList<String>();

boolean resultUpload = false;

String dirName = UPLOAD_FOLDER ; 

String name = item.getFieldName(); // 파일의 필드 이름 얻기

String fileName = item.getName(); // 파일명 얻기

// 임시 - 실제 원본 이름 추출

File originalFile = new File(fileName);

String originalFileName = originalFile.getName();

System.out.println("임시:" + originalFileName );

String contentType = item.getContentType(); // 컨텐츠 타입 얻기

long fileSize = item.getSize(); // 파일의 크기 얻기

// 업로드 파일명을 현재시간으로 변경후 저장

String fileExt = fileName.substring(fileName.lastIndexOf("."));

String uploadedFileName = System.currentTimeMillis() + ""; 

System.out.println(fileExt);

System.out.println(uploadedFileName);

// 저장할 절대 경로로 파일 객체 생성

String realUploadFile = File.separator + dirName + File.separator + uploadedFileName;

System.out.println("실제 저장직전폴더:" + contextRootPath + realUploadFile);

File uploadedFile = new File(contextRootPath + realUploadFile);

if ( FILE_RESTRICT_EXT.contains(fileExt.toLowerCase()) ) {

item.write(uploadedFile); // 파일 저장

resultUpload = true; // 파일 업로드 완료

}

//========== 뷰단에 출력 =========//

//out.println("<P>");

//out.println("파라미터 이름:" + name + "<BR>");

//out.println("파일 이름:" + fileName + "<BR>");

//out.println("콘텐츠 타입:" + contentType + "<BR>");

//out.println("파일 사이즈:" + fileSize + "<BR>");

//확장자가 이미지인겨우 이미지 출력

/*

if(".jpg.jpeg.bmp.png.gif".contains(fileExt.toLowerCase())) {

out.println("<IMG SRC='upload/" 

+ uploadedFileName 

+ "' width='300'><BR>");

}

*/

// out.println("</P>");

// out.println("<HR>");

// out.println("실제저장경로 : "+uploadedFile.getPath()+"<BR>");

// out.println("<HR>");

// 파일 전송이 완료되었을 때

if ( resultUpload == true ) {

// 파일 정보(Map 자료구조 방식)

fileMapNode.put("name", name);

fileMapNode.put("fileName", originalFileName);

fileMapNode.put("contentType", contentType);

fileMapNode.put("fileSize", fileSize);

fileMapNode.put("fileExt", fileExt);

fileMapNode.put("uploadedFileName", uploadedFileName);

fileMapNode.put("realName", uploadedFile.getName());

fileMapNode.put("realPath", uploadedFile.getPath());

// 파일 정보(문자열 구분 방식)

fileListNode.add( "id:" + fileNum + ",name:name,value:" + name + "/" );

fileListNode.add( "id:" + fileNum + ",name:filename,value:" + originalFileName + "/" );

fileListNode.add( "id:" + fileNum + ",name:contentType,value:" + contentType + "/" );

fileListNode.add( "id:" + fileNum + ",name:fileSize,value:" + fileSize + "/" );

fileListNode.add( "id:" + fileNum + ",name:fileExt,value:" + fileExt + "/" );

fileListNode.add( "id:" + fileNum + ",name:uploadedFileName,value:" + uploadedFileName + "/" );

fileListNode.add( "id:" + fileNum + ",name:realName,value:" + uploadedFile.getName() + "/" );

fileListNode.add( "id:" + fileNum + ",name:realPath,value:" + uploadedFile.getPath() + "/" );

fileInfoList.add(fileListNode);

fileNum++;

}

}

private static void processFormField(PrintWriter out, FileItem item) 

throws Exception{

String name = item.getFieldName(); //필드명 얻기

Object value = item.getString("UTF-8"); //UTF-8형식으로 필드에 대한 값읽기

//out.println(name + ":" + value + "<BR>"); //출력

// 파일 토큰 인증 여부

if ( name.contentEquals("token")

&& value.equals(FILE_AUTH_TOKEN_KEY) ) {

System.out.println("참 - 인증");

FILE_TOKEN_CHECK = true;

}

// Map 자료구조 저장

reqInfoMap.put(name, value);

// 문자열 구문 저장 - 문자열 검색원리 적용 (검색 기법 적용)

reqInfoList.add( "id:" + reqNum + ",name:" + name + ",value:" + value + "/" );

reqNum++;

}

// FileInfoList 내용 - 문맥 문석기(임시)

public static void getFileinfoParser(List<Object> fileParser, String tarName) {

// 분석 시작

if ( fileParser != null ) {

for ( Object fileNode : fileParser ) {

@SuppressWarnings("unchecked")

List<String> sep = (List<String>) fileNode;

// 문자열 분석 반환 받기 (id = 0, name = 1, value = 2)

Object result = getFileAttrAnal(sep, tarName);

}

}

}


// FileInfoList 내용 - 문자열 구분

private static Object getFileAttrAnal(List<String> fileNode, String tarName) {

int pId = -1;

String pName = null;

Object pValue = null;

String trashTxt = null;

if ( fileNode != null) {

for ( String usrTxt : fileNode  ) {

trashTxt = usrTxt.substring(usrTxt.indexOf("id:") + 3, usrTxt.indexOf(",name") );

pId = Integer.valueOf(trashTxt);

// System.out.print("ID:" + pId);


trashTxt = usrTxt.substring(usrTxt.indexOf("name:") + 5, usrTxt.indexOf(",value") );

pName = trashTxt;

// System.out.print(",name:" + pName);

trashTxt = usrTxt.substring(usrTxt.indexOf("value:") + 6, usrTxt.indexOf("/") );

pValue = trashTxt;

// System.out.println(",value:" + pValue);

}

}

return null;

}


// ReqInfoList 내용 - 문맥 문석기(임시)

public static Object getReqinfoParser(List<String> reqNode, String tarName) {

int pId;

String pName ;

Object pValue ;

String trashTxt;

if ( reqNode != null) {

for ( String usrTxt : reqNode  ) {

trashTxt = usrTxt.substring(usrTxt.indexOf("id:") + 3, usrTxt.indexOf(",name") );

pId = Integer.valueOf(trashTxt);

System.out.print("ID:" + pId);


trashTxt = usrTxt.substring(usrTxt.indexOf("name:") + 5, usrTxt.indexOf(",value") );

pName = trashTxt;

System.out.print(",name:" + pName);

trashTxt = usrTxt.substring(usrTxt.indexOf("value:") + 6, usrTxt.indexOf("/") );

pValue = trashTxt;

System.out.println(",value:" + pValue);

}

}

return null;

}

}


파일명: HttpUtil.java


[첨부(Attachments)]

HttpUtil.zip




11. Model - CompUsers.java


모델은 DB의 테이블 설계를 생각해서 하는 것이 좋다고 본다. (꼭 그렇다는 건 아님.)


아래의 그림 16, 그림 17, 그림 18은 결국은 같은 Table에 대한 것이다.

하나를 바라보는 것이 다양할 수 있다는 이야기를 하는 것이다.



그림 16. Oracle SQL Developer - COMP_USERS (Tables)



그림 17. Oracle SQL Developer - COMP_USERS (Tables)



그림 18. Oracle SQL Developer - COMP_USERS (Tables)


비고: 이 글에서는 DB 설계는 하지 않았음.



경로: /src/main/java/com/example/web/model/CompUsers.java


package com.example.web.model;


public class CompUsers {


private String username;

private String password;

private int enabled;

public CompUsers(String username, String password, int enabled) {

this.username = username;

this.password = password;

this.enabled = enabled;

}


public CompUsers() {

}


public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public int getEnabled() {

return enabled;

}

public void setEnabled(int enabled) {

this.enabled = enabled;

}

}



파일명: CompUsers.java


[첨부(Attachments)]

CompUsers.zip



* 2부에서는 Jquery 다운받기, JSON, MultiUploadController, View 화면, Index 페이지 구성에 대해서 소개하겠다.


1. [JSP] 25. jQuery와 Ajax 멀티 파일 업로드(개선), POST전송, JSON - 구성하기(2), 2020-10-03

https://yyman.tistory.com/1446


반응형
728x90
300x250

[JSP] 23(번외). JSP/Servlet - MVC2 index.do 시작페이지 만들기 (FrontController, Command패턴)



index.html이나 index.jsp 페이지처럼 시작페이지를 index.do로 할 수 없는지에 대한 글이다.




1. /src/main/webapp/index.jsp - 수정하기


<jsp:forward page="index.do" />를 넣어준다.



그림 1. index.jsp 수정하기


<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<jsp:forward page="index.do" />


파일명: index.jsp



2. web.xml - 수정하기


web,xml에 <welcome-file-list><welcome-file>을 만들어준다.



그림 2. web.xml 수정하기


<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

xmlns="http://java.sun.com/xml/ns/javaee" 

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 

id="WebApp_ID" version="3.0">

  <display-name>Archetype Created Web Application</display-name>

  <welcome-file-list>

  <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>

  <servlet>

  <servlet-name>FrontController</servlet-name>

  <servlet-class>com.example.web.controller.FrontController</servlet-class>

  <init-param>

<param-name>charset</param-name>

<param-value>UTF-8</param-value>

</init-param>

  </servlet>

  <servlet-mapping>

  <servlet-name>FrontController</servlet-name>

  <url-pattern>*.do</url-pattern>

  </servlet-mapping>

</web-app>


파일명: web.xml


[첨부(Attachments)]

web.zip




3. FrontController.java - 수정하기


서블릿으로 작성한 FrontController.java를 수정해준다.



그림 3. FrontController.java


아래의 소스 코드는 HttpUtil.java에 관한 코드이다.


package com.example.web.util;


import java.io.IOException;


import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class HttpUtil extends HttpServlet {


private static final long serialVersionUID = 1L;


private static String charset = null;


public static void forward(HttpServletRequest req, HttpServletResponse res,

String path) throws ServletException, IOException {


try {

RequestDispatcher dispatcher = req.getRequestDispatcher(path);

dispatcher.forward(req, res);


}catch(Exception e) {

e.printStackTrace();

}

}

}


파일명: HttpUtil.java


[첨부(Attachments)]

HttpUtil.zip





* 맺음글(Conclusion)


간단한 형태로 시작페이지를 지정하는 방법에 대해서 소개하였다.

반응형
728x90
300x250

[JSP] 22. JSP/Servlet MVC2 - jQuery기반의 Ajax POST 전송 및 MVC패턴 Action 식별자


jQuery를 활용하는 방법에 대해서 소개하려고 한다.

그림 일기 수준으로 매우 편안한 마음으로 입문할 수 있는 학습 기반을 제공해주려고 한다.

심도적인 부분은 전문서적 등도 찾아보기도 하고, 검색도 많이 해보시면 좋을 듯 싶다. (변화가 워낙 빠른 분야인 만큼)



1. 결과


동적인 부분인 관계로 영상으로 올려주도록 하겠다.



영상 1. 출력 결과


jQuery가 어떤 결과물을 만들어 내는 도구인지 이해가 되었으면 하는 바램이다.

원래는 jQuery가 먼저 나온 것이 아니고, Javascript가 먼저이다.


그리고 2006년도에 약 Ajax라는 규격이 나왔는데, Javascript 파일 형태로 ajax 파일을 배포하여 동적인 처리에 대해서 접근하게 되었다.


그리고 조금 시간이 지나서 jQuery라는 게 나왔는데, 분명한 건 이건 표준은 아니다.

다만, 편하게 사용하도록 도와주는 오픈소스 진형의 library이다.




2. 프로젝트 생성하기


이러한 저차원 수준으로 작성한 이유는 프로그래밍에 겁먹지 말라는 것이다.



그림 1. 프로젝트 생성하기


File -> New -> Maven Project를 클릭한다.



그림 2. 프로젝트 생성하기


org.apache.maven.archetypes | maven-archetype-webapp를 선택한다.

Next를 클릭한다.


검색 키워드로 검색할 때, "webapp"로 하면, 조금 찾는데 시간이 절약될 수 있다.

다만, HDD 사용자는 조금 버벅될 가능성이 있다. (검색 기능이 매우 느림.)




그림 3. 프로젝트 생성하기


GroupId, Artifact Id를 적당히 입력한 후 Finish를 누른다.



3. Pom.xml - 설정하기


http://mvnrepository.com에 들어가서 "servlet"을 검색해서 최신 버전으로 해준다.

Maven Project를 아끼고 있는 이유는 정말 사용하기가 편리하다.


셋팅하는데, /src/main/webapp/WEB-INF/lib인가 폴더에 넣고, 프로젝트 속성에 들어가서 BuildPath 클릭하고 Add External Library 등록하고 

확인 몇 번하고 복잡했는데, Maven을 알게 되면서 많이 좋아진 것 같다.



그림 4. pom.xml


<?xml version="1.0" encoding="UTF-8"?>


<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>


  <groupId>com.webedu</groupId>

  <artifactId>exampleAjax</artifactId>

  <version>0.0.1-SNAPSHOT</version>

  <packaging>war</packaging>


  <name>exampleAjax Maven Webapp</name>

  <!-- FIXME change it to the project's website -->

  <url>http://www.example.com</url>


  <properties>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <maven.compiler.source>1.7</maven.compiler.source>

    <maven.compiler.target>1.7</maven.compiler.target>

  </properties>


  <dependencies>

    <dependency>

      <groupId>junit</groupId>

      <artifactId>junit</artifactId>

      <version>4.11</version>

      <scope>test</scope>

    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->

<dependency>

    <groupId>javax.servlet</groupId>

    <artifactId>javax.servlet-api</artifactId>

    <version>4.0.1</version>

    <scope>provided</scope>

</dependency>

  </dependencies>


  <build>

    <finalName>exampleAjax</finalName>

    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->

      <plugins>

        <plugin>

          <artifactId>maven-clean-plugin</artifactId>

          <version>3.1.0</version>

        </plugin>

        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->

        <plugin>

          <artifactId>maven-resources-plugin</artifactId>

          <version>3.0.2</version>

        </plugin>

        <plugin>

          <artifactId>maven-compiler-plugin</artifactId>

          <version>3.8.0</version>

        </plugin>

        <plugin>

          <artifactId>maven-surefire-plugin</artifactId>

          <version>2.22.1</version>

        </plugin>

        <plugin>

          <artifactId>maven-war-plugin</artifactId>

          <version>3.2.2</version>

        </plugin>

        <plugin>

          <artifactId>maven-install-plugin</artifactId>

          <version>2.5.2</version>

        </plugin>

        <plugin>

          <artifactId>maven-deploy-plugin</artifactId>

          <version>2.8.2</version>

        </plugin>

      </plugins>

    </pluginManagement>

  </build>

</project>



파일명: pom.xml


[첨부(Attachments)]

pom.zip




4. Project Factes와 Build Path - 자바 버전 바꿔주기


자바 버전을 변경해줘야 한다. Maven Project 초기 셋팅이 현재 1.6으로 잡혀서 생성되기 때문이다.



그림 5. 프로젝트의 오른쪽 메뉴 모습


프로젝트를 선택한 후, 마우스 오른쪽 버튼을 클릭한다.

Properties를 클릭한다.



그림 6. Build-Path


JRE System Library [JavaSE-14]로 바꿔준다.

Edit 버튼을 누르면 바꿀 수 있다.



그림 7. Project Factes


Java의 버전을 14로 바꿔준다.




5. jQuery 사이트 - 접속하기


인터넷 웹 브라우저를 켠다.


그림 8. 윈도우 10 - 엣지 클릭하기


웹 브라우저 아이콘을 못 찾는 경우에는 그림처럼 생긴 거 클릭하면 된다. 

(그 옆에도 비슷하게 생긴 e자 아이콘을 클릭해도 무방하다.)



그림 11. jQuery 웹 사이트 접속하기


https://jquery.com/download


링크를 웹 주소창에 입력해서 접속한다.

또는 클릭해도 무방하다.


표기해놓은 것 5개 중 하나만 잘 다운로드 받으면 된다.




그림 12. jQuery 다운받기


문서 클릭\workspace-spring-tool-suite-4-4.7.2.RELEASE\{프로젝트명}\src\main\webapp\js에 저장해준다.

js폴더가 없으니깐 하나 만들어준다.

js폴더 안에 저장해준다.



영상 2. jQuery 다운로드 받는 모습



6. jQuery - ajaxPost - API 접속하기


https://api.jquery.com/jquery.post/


사이트에 접속해준다.



그림 13. jQuery 예제


이렇게 생긴 HTML태그를 복사하여 Eclipse에 옮겨갈 것이다.

참고로 이 코드가 완벽한 코드는 절대 아니다. (태스트 해 봤음.)




그림 14. index.jsp 파일에 복사 붙여넣기 해주기


그림 14와는 다르게 태스트를 완료한 코드는 아래에 있으니 참고하면 되겠다.

WEB-INF내에 views폴더 생성해준다.

그리고 index.jsp 파일을 views 폴더 안으로 이동해준다.



영상 3. views 폴더 생성 방법 및 파일 이동 시키기



그림 15. 이동을 완료한 모습 - views 폴더 내용


<!doctype html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>jQuery.post demo</title>

<script src="js/jquery-3.5.1.js"></script>


</head>

<body>

 

<form action="board/insert.do" id="searchForm">

  <input type="text" name="s" placeholder="Search...">

  <input type="submit" value="Search">

</form>

<div id="result"></div>


<script type="text/javascript">

// Attach a submit handler to the form

$( "#searchForm" ).submit(function( event ) {

 

  // Stop form from submitting normally

  event.preventDefault();

 

// Get some values from elements on the page:

  var $form = $( this ),

    term = $form.find( "input[name='s']" ).val(),

    url = $form.attr( "action" );

 

  // Send the data using post

  var posting = $.post( url, { s: term } );

 

  // Put the results in a div

  posting.done(function( data ) {

    alert( "Data Loaded: " + data );

    var content = data ;

    $( "#result" ).html( content );

   

  });

 

});


</script>

<!-- the result of the search will be rendered inside this div --> 

 

</body>

</html>


파일명: index.jsp


[첨부(Attachments)]

index.zip




7. Servlet 작성하기


MVC2 패턴을 만들거니깐 서블렛을 잘 따라 해야 한다.



그림 16. Java Resources 폴더 - 마우스 오른쪽 버튼 메뉴 모습


Java Resources 폴더를 선택한 후, 마우스 오른쪽 버튼으로 클릭한다.

New-> Servlet을 클릭한다.



그림 17. Servlet 생성 작업창 - 모습 (Create Servlet)


Java Package명을 입력한다. (예: com.example.web.controller)

Class Name명을 입력한다. (예: FrontController)


Finish를 누른다.



8. web.xml 파일 - 수정작업하기


경로 위치: /src/main/webapp/WEB-INF/web.xml


문자열하고, FrontController의 *.do로 변경 작업을 해주면 된다.



그림 18. web.xml - 수정작업하기


<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

xmlns="http://java.sun.com/xml/ns/javaee" 

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 

id="WebApp_ID" version="3.0">

  <display-name>Archetype Created Web Application</display-name>

  <servlet>

  <servlet-name>FrontController</servlet-name>

  <servlet-class>com.example.web.controller.FrontController</servlet-class>

  <init-param>

<param-name>charset</param-name>

<param-value>UTF-8</param-value>

</init-param>

  </servlet>

  <servlet-mapping>

  <servlet-name>FrontController</servlet-name>

  <url-pattern>*.do</url-pattern>

  </servlet-mapping>

</web-app>



파일명: web.xml


[첨부(Attachments)]

web.zip




9. Class 만들기 - HttpUtil


HttpUtil 클래스를 만들어주려고 한다.



그림 19. Java Resources의 오른쪽 버튼 메뉴 모습


Java Resources를 마우스 오른쪽 버튼으로 클릭한다.

New->Class를 클릭한다.



그림 20. 클래스 생성 마법사 모습


Package명은 com.example.web.util

Name은 HttpUtil로 한다.


Finish를 누른다.





그림 21. 코드를 입력한 모습 - HttpUtil.java


package com.example.web.util;


import java.io.IOException;


import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class HttpUtil extends HttpServlet {


private static final long serialVersionUID = 1L;


private static String charset = null;


public static void forward(HttpServletRequest req, HttpServletResponse res,

String path) throws ServletException, IOException {


try {

RequestDispatcher dispatcher = req.getRequestDispatcher(path);

dispatcher.forward(req, res);


}catch(Exception e) {

e.printStackTrace();

}

}

}


파일명: HttpUtil.java


[첨부(Attachments)]

HttpUtil.zip



10. Controller - Interface 만들기


Controller 인터페이스를 하나 만들 것이다.



그림 22. Controller.java


package com.example.web.controller;


import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public interface Controller {


public void execute(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException;


}




파일명: Controller.java


[첨부(Attachments)]

Controller.zip



11. InsertController.java - Class


앞서 만든 Interface(Controller)로 InsertController.java를 작성할 것이다.



그림 23. InsertController.java


Package 명은 com.example.web.board라고 입력한다.

Name명은 InsertController라고 입력한다.


Interfaces의 Add버튼을 누른다.



그림 24. Implemented Interfaces.......


Controller를 입력한 후 작성한 Controller 인터페이스를 선탁한다.

OK를 누른다.

Finish를 누른다.


package com.example.web.controller.board;


import java.io.IOException;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import com.example.web.controller.Controller;

import com.example.web.util.HttpUtil;


public class InsertController implements Controller {


@Override

public void execute(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

HttpUtil.forward(req, res, "/WEB-INF/views/board/insert.jsp");


}


}



파일명: InsertController.java


[첨부(Attachments)]

InsertController.zip



13. FrontController - 코드 작성하기 (수정)


코드를 자세히 보면, flag가 추가되었다.

doAction에서 POST, GET 등을 인식할 수 있게 되었다.


package com.example.web.controller;


import java.io.IOException;


import javax.servlet.ServletConfig;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import com.example.web.controller.board.InsertController;

import com.example.web.util.HttpUtil;


public class FrontController extends HttpServlet {

private static final long serialVersionUID = 1L;

private String charset = null;

       

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

doAction(req, res, "GET");

}


protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

       doAction(req, res, "POST");

}


protected void doAction(HttpServletRequest req, 

HttpServletResponse res,

String flag) 

throws ServletException, IOException {

ServletConfig sc = this.getServletConfig();

charset = sc.getInitParameter("charset");


req.setAttribute("charset", charset);

req.setCharacterEncoding(charset);

res.setContentType("text/html; charset=" + charset);


String uri = req.getRequestURI();

String conPath = req.getContextPath();

String command = uri.substring(conPath.length());


Controller subController = null;


// POST 전송방식만

if(command.equals("/board/insert.do") && 

flag.contentEquals("POST")){


System.out.println("insert");

System.out.println("----------------");

subController = new InsertController();

subController.execute(req, res);

}else if (command.equals("/index.do")){

HttpUtil.forward(req, res, "/WEB-INF/views/index.jsp");

}

}

}



파일명: FrontController.java


[첨부(Attachments)]

FrontController.zip



14. View - webapp/WEB-INF/views/board/insert.jsp


POST처리 후에 출력할 페이지를 작성하도록 하겠다.

PrintWriter out으로 해도 무방하지만, MVC패턴을 적용했으니 뷰 파일에서 작성하겠다.


<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%

String text = (String)request.getParameter("s");

%>

<%= text %>


파일명: insert.jsp


[첨부(Attachments)]

insert.zip



* 맺음글(Conclusion)


jQuery를 통해서 ajax 전송에 대해서 간단한 형태로 살펴보았다.

반응형
728x90
300x250

[Spring-F.] 29. MyBatis 3.5, Spring Framework 5.4, Oracle 19g - 방법5(SqlMap Spring전용)


소스 코드 위주로 소개하겠다.


[실험 결과]

1. [Spring-Framework] Spring Framework 5.4, MyBatis 3.5 연동 방법 - 실험 결과, 2020-10-02

   - https://yyman.tistory.com/1437


[이전 게시글]

1. [Spring-F.] 28. MyBatis 3.5, Spring Framework 5.4, Oracle 19g - 방법4(SqlMap Spring전용)

   - https://yyman.tistory.com/1441



41. 결과


XML 방식의 XML Mapping으로 구성하여 동작한 결과이다.



그림 25. 결과 5번



그림 26. 프로젝트 구성도



42. web.xml - 기본값


web.xml 파일은 변경하지 않았다.


<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"

version="3.1">


<!-- 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/spring/appServlet/servlet-context.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>





43. com.example.spbatis.db - SqlMapSessionFactory.java


package com.example.spbatis.db;



import java.io.IOException;

import java.io.InputStream;

import java.sql.SQLException;


import javax.sql.DataSource;


import org.apache.ibatis.io.Resources;

import org.apache.ibatis.mapping.Environment;

import org.apache.ibatis.session.Configuration;

import org.apache.ibatis.session.SqlSessionFactory;

import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import org.apache.ibatis.transaction.TransactionFactory;

import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import org.mybatis.spring.SqlSessionFactoryBean;

import org.springframework.core.io.support.PathMatchingResourcePatternResolver;


import com.example.spbatis.model.CompUsers;


import oracle.jdbc.pool.OracleDataSource;


public class SqlMapSessionFactory {


private static SqlMapSessionFactory factory = new SqlMapSessionFactory();

private final static String driverName = "oracle.jdbc.driver.OracleDriver";

private final static String dbUrl = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";

private final static String userName = "사용자계정명";

private final static String userPassword = "비밀번호";

public static SqlSessionFactory ssf;


public static SqlMapSessionFactory getInstance() {

return factory;

}

private SqlMapSessionFactory () {    }

static {

/* 방법1

DataSource dataSource = getOracleDataSource();

TransactionFactory transactionFactory = new JdbcTransactionFactory();

Environment environment = new Environment("development", transactionFactory, dataSource);

Configuration configuration = new Configuration(environment);

configuration.addMapper(CompUsersMapper.class);

ssf = new SqlSessionFactoryBuilder().build(configuration);

*/

}

    

    public static SqlSessionFactory getSqlSessionFactory(){

   


/* 방법2: 공식 메뉴얼 참고 */

DataSource dataSource = getOracleDataSource();


SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); // Spring Framework만 지원

factoryBean.setDataSource(dataSource);

try {

//쿼리가 정의된 xml 파일들의 위치 지정

        factoryBean.setMapperLocations(

                new PathMatchingResourcePatternResolver().getResources("com/example/spbatis/mapper/*.xml")

        );

    

ssf = factoryBean.getObject();

// 클래스 등록

// ssf.getConfiguration().addMapper(CompUsersMapper.class);

} catch (Exception e) {

e.printStackTrace();

}

   

    // 방법 1, 방법 2 공통

        return ssf;

    }

    

    /*

* Description: 순정 오라클 데이터소스

*/

    private static DataSource getOracleDataSource(){


    OracleDataSource oracleDS = null;


    try {

            oracleDS = new OracleDataSource();

            oracleDS.setURL(dbUrl);

            oracleDS.setUser(userName);

            oracleDS.setPassword(userPassword);


        } catch (SQLException e) {

            e.printStackTrace();

        }


        return oracleDS;


    }

    

}



파일명: SqlMapSessionFactory.java


[첨부(Attachments)]

SqlMapSessionFactory.zip




44. com.example.spbatis.mapper - CompUsersMapper.xml


<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper

  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">


<mapper namespace="com.example.spbatis.mapper">


<select id="allCompUsers" resultType="com.example.spbatis.model.CompUsers">

select * from comp_users

</select>

<!-- 

<select id="allAddress" resultType="com.edu.db.AddressDto">

select * from addressbook

</select>

<select id="selectAddress" parameterType="Integer" resultType="com.edu.db.AddressDto">

select NUM, NAME, ADDRESS, BIRTHDATE

from addressbook

  where num=#{num}

</select>

<insert id="insertAddress" parameterType="com.edu.db.AddressDto">

insert into

addressbook(NAME, ADDRESS, BIRTHDATE)

values

(#{name},#{address},#{birthdate})

</insert>

<delete id="deleteAddress" parameterType="Integer">

DELETE FROM AddressBook

WHERE NUM = #{num}

</delete>

<update id="updateAddress" parameterType="com.edu.db.AddressDto" >

update addressbook

set birthdate = #{birthdate}, name = #{name}, address =#{address}

where num = #{num}

</update>

 -->

</mapper>


파일명: CompUsersMapper.xml


[첨부(Attachments)]

CompUsersMapper.zip





45. com.example.spbatis.dao - CompUsersDao.java


package com.example.spbatis.dao;


import java.util.List;


import org.apache.ibatis.session.SqlSession;

import org.apache.ibatis.session.SqlSessionFactory;


import com.example.spbatis.db.SqlMapSessionFactory;

import com.example.spbatis.model.CompUsers;



public class CompUsersDao {


    SqlSessionFactory factory = SqlMapSessionFactory.getSqlSessionFactory();

    

    public CompUsersDao() {

        

    }

    

    // SQL 세션 열기

    public List<CompUsers> selectAddress() {


    List<CompUsers> user = null;

try (SqlSession session = factory.openSession()) {

 

user = session.selectList("com.example.spbatis.mapper.allCompUsers");

session.close();

// System.out.println("계정명:" + user.getUsername());


}

return user;


    }

    

}



파일명: CompUsersDao.java


[첨부(Attachments)]

CompUsersDao.zip





46. com.example.spbatis.service - CompUsersService.java


package com.example.spbatis.service;


import java.util.List;


import com.example.spbatis.dao.CompUsersDao;

import com.example.spbatis.model.CompUsers;


public class CompUsersService {


private CompUsersDao dao = null;

public CompUsersService() {

dao = new CompUsersDao();

}

public List<CompUsers> getAllCompUsers() {

return dao.selectAddress();

}

 

}



파일명: CompUsersService.java


[첨부(Attachments)]

CompUsersService.zip




47. com.example.spbatis - HomeController.java


package com.example.spbatis;


import java.text.DateFormat;

import java.util.Date;

import java.util.Locale;


import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

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

import org.springframework.web.bind.annotation.RequestMethod;


import com.example.spbatis.service.CompUsersService;


/**

 * Handles requests for the application home page.

 */

@Controller

public class HomeController {

private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

private CompUsersService compUserService;

@RequestMapping(value = "/", method = RequestMethod.GET)

public String home(Locale locale, Model model) {

logger.info("Welcome home5 - Java(XML Mappers)! The client locale is {}.", locale);

Date date = new Date();

DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

String formattedDate = dateFormat.format(date);

compUserService = new CompUsersService();

model.addAttribute("serverTime", formattedDate );

model.addAttribute("list", compUserService.getAllCompUsers()) ;

return "home";

}

}



파일명: HomeController.java


[첨부(Attachments)]

HomeController.zip





48. view - home.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>

<%@ page session="false" %>


<html>

<head>

<title>Home</title>

</head>

<body>

<h1>

Hello world!  

</h1>


<P>  The time on the server is ${serverTime}. </P>

<h3>SqlMapSessionFactory 방식(Java - XML Mapper - Spring 전용 버전)</h3>

<c:forEach items="${list }" var="val" >

    ${val.username} / 

    ${val.password} /

    ${val.enabled }<br>

</c:forEach>

<c:if test="${empty list }">

    ${"데이터가 존재하지않아요."}

</c:if>


</body>

</html>



파일명: home.jsp


[첨부(Attachments)]

home.zip



* 맺음글(Conclusion)


조금 작성하는데 힘이 들었지만. MyBatis 하나 셋팅에는 다양한 방법이 지원된다는 것을 알 수 있었다.



* 참고 자료(References)


1. mybatis-spring - 마이바티스 스프링 연동모듈 | 시작하기, https://mybatis.org/spring/ko/getting-started.html, Accessed by 2020-10-02, Last Modified 2020-06-05.

   [비고] - 공식 사이트이다. (이 메뉴얼만 가지고는 다 안 될 수도 있다.)


2. 스프링프레임워크 Java config로 MyBatis 사용하기, https://offbyone.tistory.com/381, Accessed by 2020-10-02, Last Modified 2019-03-17.


3. [mybatis] 다중 Database Setting, https://wfreud.tistory.com/310, Accessed by 2020-10-02, Last Modified 2019-03-21.


4. maven프로젝트 src/main/resource경로의 파일 읽기, https://blog.naver.com/down83/50092131189, Accessed by 2020-10-02, Last Modified 2010-07-13.


5. MyBatis List와 Map으로 데이터 불러오기, https://smujihoon.tistory.com/112, Accessed by 2020-10-02, Last Modified 2019-02-11.


5. [Mybatis] root-context.xml 자료(Oracle), https://datamod.tistory.com/81, Accessed by 2020-10-02, Last Modified 2018-05-20.


6. 7. 공용 클래스 작성 - commonDAo, https://tapasnote.tistory.com/21?category=697717, Accessed by 2020-10-02, Last Modified 2017-04-12.


7. DatsSource, 커넥션 풀을 이용한 DB 연결, https://m.blog.naver.com/PostView.nhn?blogId=2hyoin&logNo=220647895962, Accessed by 2020-10-02, Last Modified 2016-03-07.


8. MyBatis tutorial - Introductory MyBatis tutorial, http://zetcode.com/db/mybatis/, Accessed by 2020-10-02, Last Modified 2020-07-06.

   [영어 사이트]


반응형
728x90
300x250

[Spring-F.] 28. MyBatis 3.5, Spring Framework 5.4, Oracle 19g - 방법4(SqlMap Spring전용)


소스 코드 위주로 소개하도록 하겠다.


[실험 결과]

1. [Spring-Framework] Spring Framework 5.4, MyBatis 3.5 연동 방법 - 실험 결과, 2020-10-02

   - https://yyman.tistory.com/1437


[이전 게시글]

1. [Spring-F.] 27. MyBatis 3.5, Spring Framework 5.4, Oracle 19g - 방법3(SqlMap-XML-Class)     // 결과: 지원, 2020-10-02

    - https://yyman.tistory.com/1440



33. 결과


작업한 내용을 출력한 결과는 다음과 같다.



그림 23. 결과 모습(Java 방식) - XML Mapper - Spring Beans 객체 방식 적용 (Spring 전용)



그림 24. 프로젝트 구성도




34. web.xml (기본값) - 변동없음


<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"

version="3.1">


<!-- 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/spring/appServlet/servlet-context.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>





35. com.example.spbatis.db - SqlMapSessionFactory.java


package com.example.spbatis.db;



import java.io.IOException;

import java.io.InputStream;

import java.sql.SQLException;


import javax.sql.DataSource;


import org.apache.ibatis.io.Resources;

import org.apache.ibatis.mapping.Environment;

import org.apache.ibatis.session.Configuration;

import org.apache.ibatis.session.SqlSessionFactory;

import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import org.apache.ibatis.transaction.TransactionFactory;

import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import org.mybatis.spring.SqlSessionFactoryBean;

import org.springframework.core.io.support.PathMatchingResourcePatternResolver;


import com.example.spbatis.mapper.CompUsersMapper;

import com.example.spbatis.model.CompUsers;


import oracle.jdbc.pool.OracleDataSource;


public class SqlMapSessionFactory {


private static SqlMapSessionFactory factory = new SqlMapSessionFactory();

private final static String driverName = "oracle.jdbc.driver.OracleDriver";

private final static String dbUrl = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";

private final static String userName = "사용자계정";

private final static String userPassword = "비밀번호";

public static SqlSessionFactory ssf;


public static SqlMapSessionFactory getInstance() {

return factory;

}

private SqlMapSessionFactory () {    }

static {

/* 방법1

DataSource dataSource = getOracleDataSource();

TransactionFactory transactionFactory = new JdbcTransactionFactory();

Environment environment = new Environment("development", transactionFactory, dataSource);

Configuration configuration = new Configuration(environment);

configuration.addMapper(CompUsersMapper.class);

ssf = new SqlSessionFactoryBuilder().build(configuration);

*/

}

    

    public static SqlSessionFactory getSqlSessionFactory(){

   


/* 방법2: 공식 메뉴얼 참고 */

DataSource dataSource = getOracleDataSource();


SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); // Spring Framework만 지원

factoryBean.setDataSource(dataSource);

try {

//쿼리가 정의된 xml 파일들의 위치 지정

/*

        factoryBean.setMapperLocations(

                new PathMatchingResourcePatternResolver().getResources("com/example/spbatis/mapper/*.xml")

        );

        */

    

ssf = factoryBean.getObject();

// 클래스 등록

ssf.getConfiguration().addMapper(CompUsersMapper.class);

} catch (Exception e) {

e.printStackTrace();

}

   

    // 방법 1, 방법 2 공통

        return ssf;

    }

    

    /*

* Description: 순정 오라클 데이터소스

*/

    private static DataSource getOracleDataSource(){


    OracleDataSource oracleDS = null;


    try {

            oracleDS = new OracleDataSource();

            oracleDS.setURL(dbUrl);

            oracleDS.setUser(userName);

            oracleDS.setPassword(userPassword);


        } catch (SQLException e) {

            e.printStackTrace();

        }


        return oracleDS;


    }

    

}



파일명: SqlSessionFactory.java


[첨부(Attachments)]

SqlMapSessionFactory.zip





36. com.example.spbatis.mapper - CompUsersMapper.java


package com.example.spbatis.mapper;


import java.util.List;


import org.apache.ibatis.annotations.Mapper;

import org.apache.ibatis.annotations.Select;


import com.example.spbatis.model.CompUsers;


@Mapper

public interface CompUsersMapper {

@Select("SELECT * FROM comp_users")

List<CompUsers> selectAll();

}


파일명: CompUsersMapper.java


[첨부(Attachments)]

CompUsersMapper.zip





37. com.example.spbatis.dao - CompUsersDao.java


package com.example.spbatis.dao;


import java.util.List;


import org.apache.ibatis.session.SqlSession;

import org.apache.ibatis.session.SqlSessionFactory;

import org.springframework.beans.factory.annotation.Autowired;


import com.example.spbatis.db.SqlMapSessionFactory;

import com.example.spbatis.mapper.CompUsersMapper;

import com.example.spbatis.model.CompUsers;



public class CompUsersDao {


    SqlSessionFactory factory = SqlMapSessionFactory.getSqlSessionFactory();

    

    public CompUsersDao() {

        

    }

    

    // SQL 세션 열기

    public List<CompUsers> selectAddress() {


    List<CompUsers> user = null;

try (SqlSession session = factory.openSession()) {

CompUsersMapper mapper = session.getMapper(CompUsersMapper.class);

user = mapper.selectAll();

// System.out.println("계정명:" + user.getUsername());


}

return user;


    }

    

}



파일명: CompUsersDao.java


[첨부(Attachments)]

CompUsersDao.zip





38. com.example.spbatis.service - CompUsersService.java


package com.example.spbatis.service;


import java.util.List;


import com.example.spbatis.dao.CompUsersDao;

import com.example.spbatis.model.CompUsers;


public class CompUsersService {


private CompUsersDao dao = null;

public CompUsersService() {

dao = new CompUsersDao();

}

public List<CompUsers> getAllCompUsers() {

return dao.selectAddress();

}

 

}



파일명: CompUsersService.java


[첨부(Attachments)]

CompUsersService.zip





39. com.example.spbatis - HomeController.java


package com.example.spbatis;


import java.text.DateFormat;

import java.util.Date;

import java.util.Locale;


import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

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

import org.springframework.web.bind.annotation.RequestMethod;


import com.example.spbatis.service.CompUsersService;


/**

 * Handles requests for the application home page.

 */

@Controller

public class HomeController {

private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

private CompUsersService compUserService;

@RequestMapping(value = "/", method = RequestMethod.GET)

public String home(Locale locale, Model model) {

logger.info("Welcome home4(Class Mappers) - Java! The client locale is {}.", locale);

Date date = new Date();

DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

String formattedDate = dateFormat.format(date);

compUserService = new CompUsersService();

model.addAttribute("serverTime", formattedDate );

model.addAttribute("list", compUserService.getAllCompUsers()) ;

return "home";

}

}



파일명: HomeController.java


[첨부(Attachments)]

HomeController.zip



40. View - Home.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>

<%@ page session="false" %>


<html>

<head>

<title>Home</title>

</head>

<body>

<h1>

Hello world!  

</h1>


<P>  The time on the server is ${serverTime}. </P>

<h3>SqlMapSessionFactory 방식(Java - Mapper - Spring 전용 버전)</h3>

<c:forEach items="${list }" var="val" >

    ${val.username} / 

    ${val.password} /

    ${val.enabled }<br>

</c:forEach>

<c:if test="${empty list }">

    ${"데이터가 존재하지않아요."}

</c:if>


</body>

</html>



파일명: home.jsp


[첨부(Attachments)]

home.zip




* 5부에서 만나요.


1. [Spring-F.] 29. MyBatis 3.5, Spring Framework 5.4, Oracle 19g - 방법5(SqlMap Spring전용)  // 결과: 지원, 2020-10-02

    - https://yyman.tistory.com/1442



반응형
728x90
300x250

[Spring-F.] 25. MyBatis 3.5, Spring Framework 5.4, Oracle 19g - 방법1(web.xml-Beans)


MyBatis 3.5 - 연동 방법에 관한 글을 시작하겠다.


1. [Spring-Framework] Spring Framework 5.4, MyBatis 3.5 연동 방법 - 실험 결과, 2020-10-02

https://yyman.tistory.com/1437


소스코드를 위주로 소개하겠다.


동작되지 않은 소스이지만, 분석해보고 싶은 사람들을 위해서 소스코드를 공개하도록 하겠다.



7. 방법 1 - 출력 결과


결과는 동작하지 않았다.



그림 14. 결과 (방법1) - 미지원



8. 프로젝트 구성


프로젝트는 아래처럼 구성하였다.




그림 15, 그림 16. 프로젝트 구성 모습



9. web.xml 


<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"

version="3.1">


<!-- 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

/WEB-INF/spring/mybatis-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/spring/appServlet/servlet-context.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>



파일명: web.xml


[첨부(Attachments)]

web.zip





10. mybatis-context.xml (없는 파일 - 생성해줘야 함)


셋팅 파일의 경로에 관한 것이다. /src/main/java/webapp/WEB-INF/spring 폴더 내에 만들어줘야 한다.



그림 17. mybatis-context.xml의 위치



<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:aop="http://www.springframework.org/schema/aop"

xmlns:tx="http://www.springframework.org/schema/tx"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:p="http://www.springframework.org/schema/p"

xmlns:jdbc="http://www.springframework.org/schema/jdbc"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!-- 현재는 빈(Bean) 등록 방식 미지원함(2020-10-02 / Spring Framework 5 이상) -->

<!-- org.apache.ibatis.datasource.pooled.PooledDataSource -->

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>

<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"/>

<property name="username" value="사용자계정"/>

<property name="password" value="비밀번호"/>

</bean>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

<property name="dataSource" ref="dataSource" />

<property name="configLocation" value="/WEB-INF/mybatis-config.xml"/>

<property name="mapperLocations" value="classpath:com/example/spbatis/mapper/*.xml" />

    </bean>

<!-- 

<property name="mapperLocations" value="classpath:com/think/mapper/**/*.xml" />

        <property name="mapperLocations" value="/WEB-INF/mybatis/mapper/*.xml" />

-->

<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">

<constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>

</bean>

</beans> 


파일명: mybatis-context.xml


[첨부(Attachments)]

mybatis-context.zip




10. mybatis-config.xml (없는 파일 - 생성해줘야 함)


mybatis-config.xml의 위치이다.

/src/main/webapp에 생성해주면 된다.



그림 18. mybatis-config.xml 위치


<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "HTTP://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

<settings>

<setting name="cacheEnabled" value="false" />

<setting name="useGeneratedKeys" value="true" />

<setting name="defaultExecutorType" value="REUSE" />

</settings>


<!-- 별명 -->

    <typeAliases>

         <typeAlias alias="hashMap" type="java.util.HashMap" />

         <typeAlias alias="map" type="java.util.Map" />

    </typeAliases>


<!--

<mappers>

<mapper resource="mybatis/mapper/tempMapper.xml" />

</mappers>

<mappers>

<mapper resource="mybatis/mapper/bbsMapper.xml" />

</mappers>

-->

</configuration>



파일명: mybatis-config.xml


[첨부(Attachments)]

mybatis-config.xml





11. view - home.jsp


경로: /src/main/webapp/WEB-INF/views/home.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>

<%@ page session="false" %>


<html>

<head>

<title>Home</title>

</head>

<body>

<h1>

Hello world!  

</h1>


<P>  The time on the server is ${serverTime}. </P>

<h3>Beans 방식(XML)</h3>

<c:forEach items="${list }" var="val" >

    ${val.username} / 

    ${val.password} /

    ${val.enabled }<br>

</c:forEach>

<c:if test="${empty list }">

    ${"데이터가 존재하지않아요."}

</c:if>


<h3>XML - web.xml 설정방식</h3>

<c:forEach items="${list2 }" var="val" >

    ${val.username} / 

    ${val.password} /

    ${val.enabled }<br>

</c:forEach>

<c:if test="${empty list2 }">

    ${"데이터가 존재하지않아요."}

</c:if>


</body>

</html>



파일명: home.jsp


[첨부(Attachments)]

home.zip



11. Controller - HomeController.java


패키지 경로: com.example.spbatis;


package com.example.spbatis;


import java.text.DateFormat;

import java.util.Date;

import java.util.Locale;


import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

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

import org.springframework.web.bind.annotation.RequestMethod;


import com.example.spbatis.service.CompUsersService;


/**

 * Handles requests for the application home page.

 */

@Controller

public class HomeController {

private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

private CompUsersService compUserService;

@RequestMapping(value = "/", method = RequestMethod.GET)

public String home(Locale locale, Model model) {

logger.info("Welcome home! The client locale is {}.", locale);

Date date = new Date();

DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

String formattedDate = dateFormat.format(date);

compUserService = new CompUsersService();

model.addAttribute("serverTime", formattedDate );

model.addAttribute("list2", compUserService.getAllCompUsers()) ;

return "home";

}

}



파일명: HomeController.java


[첨부(Attachments)]

HomeController.zip



12. Service - CompUsersService.java


패키지 경로: com.example.spbatis.service


package com.example.spbatis.service;


import java.util.List;


import com.example.spbatis.dao.CompUsersDao;

import com.example.spbatis.model.CompUsers;


public class CompUsersService {


CompUsersDao dao = new CompUsersDao();

public List<CompUsers> getAllCompUsers() {

return dao.selectAddress();

}

 

}



파일명: CompUsersService.java


[첨부(Attachments)]

CompUsersService.zip




13. DAO - CompUsersDao.java


패키지 경로: com.example.spbatis.dao


package com.example.spbatis.dao;


import java.util.List;


import org.apache.ibatis.session.SqlSession;

import org.apache.ibatis.session.SqlSessionFactory;

import org.mybatis.spring.SqlSessionTemplate;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;


import com.example.spbatis.model.CompUsers;


@Component

public class CompUsersDao {

/* 동작 안함1

    @Autowired

    private SqlSessionFactory sqlSessionFactory;

*/

/* 동작 안함2 */

@Autowired

private SqlSession sqlSession;

/* */

    public CompUsersDao() {

   

    }

    

    // SQL 세션 열기

    public List<CompUsers> selectAddress() {

   

    /* 동작 안함2 */

    return sqlSession.selectList("com.example.spbatis.mapper.allCompUsers");

   

   

    /* 동작 안함1

    SqlSession session = sqlSessionFactory.openSession();

    try 

    {

    return session.selectList("com.example.spbatis.mapper.allCompUsers");

    }

    finally

    {

        session.close();

    }

    */

    // return null;


    }

    

}



파일명: CompUsersDao.java


[첨부(Attachments)]

CompUsersDao.zip




14. Mapper - CompUsersMapper.xml


<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper

  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">


<mapper namespace="com.example.spbatis.mapper">


<select id="allCompUsers" resultType="com.example.spbatis.model.CompUsers">

select * from comp_users

</select>

<!-- 

<select id="allAddress" resultType="com.edu.db.AddressDto">

select * from addressbook

</select>

<select id="selectAddress" parameterType="Integer" resultType="com.edu.db.AddressDto">

select NUM, NAME, ADDRESS, BIRTHDATE

from addressbook

  where num=#{num}

</select>

<insert id="insertAddress" parameterType="com.edu.db.AddressDto">

insert into

addressbook(NAME, ADDRESS, BIRTHDATE)

values

(#{name},#{address},#{birthdate})

</insert>

<delete id="deleteAddress" parameterType="Integer">

DELETE FROM AddressBook

WHERE NUM = #{num}

</delete>

<update id="updateAddress" parameterType="com.edu.db.AddressDto" >

update addressbook

set birthdate = #{birthdate}, name = #{name}, address =#{address}

where num = #{num}

</update>

 -->

</mapper>


파일명: CompUsersMapper.java


[첨부(Attachments)]

CompUsersMapper.zip




* 방법2 - 실험 결과 보기


2. [Spring-F.] 26. MyBatis 3.5, Spring Framework 5.4, Oracle 19g - 방법2(SqlMap-XML-XML 맵핑)     // 결과: 지원, 2020-10-02

   - https://yyman.tistory.com/1439


반응형
728x90
300x250

[Spring-Framework] Spring Framework 5.4, MyBatis 3.5 연동 방법 - 실험 결과


아마 이런 실험을 시도한 인터넷 글은 최초가 되지 않을까 싶다.

현재에 떠돌아 다니는 정보들을 충분한 시간을 가지고 실험한 결과이다.


필자가 구독자들에게 한 가지 약속한다면, 검증을 확실히 완료하고 작성한 글이다.

이 글을 어떻게 전달해야 할지 고민을 충분히 하고 작성하게 되었다.


@Autowired 방식과 @Beans 방식을 사용하는 유저가 있다면, 사용하지 않아야 한다.



1. 결과


엄격한 태스트를 거쳐서 완료한 결과이다. 개발 환경을 구축하는데 있어서 삽질을 하지 않았으면 하는 바람이다.



그림 1. 실험 결과


[첨부(Attachments)]

MyBatis-Complete-summary.zip




2. 5가지 방법 - 정리


정리가 완료되는데로 공개하도록 하겠다.


1. [Spring-F.] 25. MyBatis 3.5, Spring Framework 5.4, Oracle 19g - 방법1(web.xml-Beans)            // 결과: 미지원, 2020-10-02

   - https://yyman.tistory.com/1438

2. [Spring-F.] 26. MyBatis 3.5, Spring Framework 5.4, Oracle 19g - 방법2(SqlMap-XML-XML 맵핑)   // 결과: 지원, 2020-10-02

   - https://yyman.tistory.com/1439

3. [Spring-F.] 27. MyBatis 3.5, Spring Framework 5.4, Oracle 19g - 방법3(SqlMap-XML-Class)    // 결과: 지원, 2020-10-02

   - https://yyman.tistory.com/1440

4. [Spring-F.] 28. MyBatis 3.5, Spring Framework 5.4, Oracle 19g - 방법4(SqlMap Spring전용)   // 결과: 지원, 2020-10-02

   - https://yyman.tistory.com/1441

5. [Spring-F.] 29. MyBatis 3.5, Spring Framework 5.4, Oracle 19g - 방법5(SqlMap Spring전용)  // 결과: 지원, 2020-10-02

   - https://yyman.tistory.com/1442


= (기타: 표준 지원에 대한 4, 5번 소스코드도 주석으로 포함 처리함.)




3. 실험 조건


실험 조건은 다음과 같다.


* IDE: Spring Tool-Suites 4-4.7.2 (Releases)

* Library:

- Spring-Framework 5.2.9.RELEASE (2020-09-15)

javax.servlet-api 4.0.1 (2018-04-20)

   - https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api/4.0.1

- mybatis-spring (2020-06-05) // Spring Framework만 사용가능함.

   - https://mvnrepository.com/artifact/org.mybatis/mybatis-spring/2.0.5

- mybatis 3.5.5 (2020-06-04)

   - https://mvnrepository.com/artifact/org.mybatis/mybatis/3.5.5

- Spring JDBC 

   - https://mvnrepository.com/artifact/org.springframework/spring-jdbc/5.2.9.RELEASE

- ojdbc8 (ojdbc8)

- mariadb-java-client 2.7.0 (2020-09-24)

   - https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client/2.7.0

- mysql-connector-java 8.0.21 (2020-07-12)


* DB:

- Oracle Databases 19g




4. 실험 결과 - 동작 영상


입증하기 위해서 영상을 준비하였다.



영상 1. Spring Framework 5.4, Oracle 19g, Mybatis 3.5 연동하기



영상 2. Spring Framework 5.4, Oracle 19g, Mybatis 3.5 연동하기(실험 1 - 영상 [예])


이런 형태로 프로젝트를 구성한 것이다.



5. 공통 - 프로젝트 생성 방법


5가지 방법에 관한 프로젝트 생성에 관한 것이다.

1~5번의 셋팅은 Build Path, Project Factes, POM.xml은 동일하다.



그림 1. 프로젝트 생성하기(1)


File->New->Spring Legacy Project를 클릭한다.



그림 2. 프로젝트 생성하기(2)


Spring MVC Project를 선택한다.

Next를 클릭한다.



그림 3. 프로젝트 생성하기(3)


top-level package 경로를 입력한 후 Finish를 누른다.



5-1. Build-Path, Project Factes 설정하기


자바 버전을 변경해줄 것이다.

초기 Spring Legacy Project로 Spring MVC Project를 생성하면, 1.6 버전으로 셋팅되어 생성될 것이다.

이러한 것을 변경해줄 것이다.



그림 4. 프로젝트 속성 들어가기


프로젝트를 선택한 후 마우스 오른쪽 버튼을 클릭한다.

Properties를 클릭한다.




그림 5. Build-path 버전 바꾸기


Java-Build Path를 클릭한다.

JRE System Library을 선택한다.

Edit 클릭하고 변경하면 된다.

(JRE -> JavaSE 14로 변경할 것)

Apply를 누른다.



그림 6. Project - Factes 설정하기


Project Factes를 클릭한다.

Java 버전을 14로 변경해준다.


Apply를 누른다.



5-2. Pom.xml 설정하기


pom.xml 설정에 관한 것이다.



그림 7. pom.xml 설정하기(1)


<org.springframework-version>을 5.2.9.RELEASE로 변경하였다.



그림 8. pom.xml 설정하기(2)


javax.servlet-api 버전을 4.0.1로 변경하였다.




그림 9. pom.xml 설정하기(3)


mybatis-spring, mybatis를 추가하였다.




그림 10. pom.xml - 오라클이 설치된 경우에만 따라하기(1)


pom.xml을 마우스 오른쪽 버튼으로 클릭한다.

Maven->Add Dependency를 클릭한다.




그림 11. pom.xml - 오라클이 설치된 경우에만 따라하기(2)


oracle이라고 검색한다.

com.oracle.database.jdbc | ojdbc8을 선택한다.

OK를 누른다.




그림 12. pom.xml - mariadb, mysql-connector 추가하기


추가로 몇 개의 DB 드라이버(MariaDB, MySQL-Connector)를 부착시켰다. 


<?xml version="1.0" encoding="UTF-8"?>

<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/maven-v4_0_0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>

<artifactId>spbatis</artifactId>

<name>Spring-MVC-mybatis</name>

<packaging>war</packaging>

<version>1.0.0-BUILD-SNAPSHOT</version>

<properties>

<java-version>1.6</java-version>

<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>

<!-- 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>

<!-- AspectJ -->

<dependency>

<groupId>org.aspectj</groupId>

<artifactId>aspectjrt</artifactId>

<version>${org.aspectj-version}</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>


<!-- @Inject -->

<dependency>

<groupId>javax.inject</groupId>

<artifactId>javax.inject</artifactId>

<version>1</version>

</dependency>

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->

<dependency>

    <groupId>javax.servlet</groupId>

    <artifactId>javax.servlet-api</artifactId>

    <version>4.0.1</version>

    <scope>provided</scope>

</dependency>


<dependency>

<groupId>javax.servlet.jsp</groupId>

<artifactId>jsp-api</artifactId>

<version>2.1</version>

<scope>provided</scope>

</dependency>

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>jstl</artifactId>

<version>1.2</version>

</dependency>

<!-- Test -->

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>4.7</version>

<scope>test</scope>

</dependency>

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->

<dependency>

    <groupId>org.mybatis</groupId>

    <artifactId>mybatis-spring</artifactId>

    <version>2.0.5</version>

</dependency>

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->

<dependency>

    <groupId>org.mybatis</groupId>

    <artifactId>mybatis</artifactId>

    <version>3.5.5</version>

</dependency>

<!-- 스프링에서 JDBC 를 사용하기 위한 라이브러리 입니다. -->

<dependency>

   <groupId>org.springframework</groupId>

   <artifactId>spring-jdbc</artifactId>

   <version>${org.springframework-version}</version>

</dependency>


<dependency>

<groupId>com.oracle.database.jdbc</groupId>

<artifactId>ojdbc8</artifactId>

<version>19.7.0.0</version>

</dependency>

<!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client -->

<dependency>

    <groupId>org.mariadb.jdbc</groupId>

    <artifactId>mariadb-java-client</artifactId>

    <version>2.7.0</version>

</dependency>

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->

<dependency>

    <groupId>mysql</groupId>

    <artifactId>mysql-connector-java</artifactId>

    <version>8.0.21</version>

</dependency>

</dependencies>

    <build>

        <plugins>

            <plugin>

                <artifactId>maven-eclipse-plugin</artifactId>

                <version>2.9</version>

                <configuration>

                    <additionalProjectnatures>

                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>

                    </additionalProjectnatures>

                    <additionalBuildcommands>

                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>

                    </additionalBuildcommands>

                    <downloadSources>true</downloadSources>

                    <downloadJavadocs>true</downloadJavadocs>

                </configuration>

            </plugin>

            <plugin>

                <groupId>org.apache.maven.plugins</groupId>

                <artifactId>maven-compiler-plugin</artifactId>

                <version>2.5.1</version>

                <configuration>

                    <source>1.6</source>

                    <target>1.6</target>

                    <compilerArgument>-Xlint:all</compilerArgument>

                    <showWarnings>true</showWarnings>

                    <showDeprecation>true</showDeprecation>

                </configuration>

            </plugin>

            <plugin>

                <groupId>org.codehaus.mojo</groupId>

                <artifactId>exec-maven-plugin</artifactId>

                <version>1.2.1</version>

                <configuration>

                    <mainClass>org.test.int1.Main</mainClass>

                </configuration>

            </plugin>

        </plugins>

    </build>

</project>



파일명: pom.xml


[첨부(Attachments)]

pom.zip



6. DB - Table 설계


Spring Security에서 사용자 계정의 테이블 설계를 사용하였다.



그림 13. 테이블 모습


CREATE TABLE comp_users (

username VARCHAR(50) NOT NULL,

password VARCHAR(300) NOT NULL,

enabled INT NOT NULL,

PRIMARY KEY (username)

);


-- 계정

INSERT INTO comp_users (username, password, enabled) VALUES ('user', '$2a$10$x04djNV2e9rpcPPRyXoLk.rMm6iZe2/vYdzpqHQcLeNSYdt7kc30O', 1);

INSERT INTO comp_users (username, password, enabled) VALUES ('admin', '$2a$10$QUddY3O/6ZgkYCR6MFlv9.nqA501Fm0cc/ZxQHX5pwb1o0CYCTiIS', 1);


파일명: Comp_users.sql


[첨부(Attachments)]

comp_user.zip





6-1. Model - CompUsers.java


공통으로 1~5 프로젝트에서 사용되는 부분이다.


package com.example.spbatis.model;


public class CompUsers {

private String username;

private String password;

private int enabled;

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public int getEnabled() {

return enabled;

}

public void setEnabled(int enabled) {

this.enabled = enabled;

}


}



파일명: CompUsers.java


[첨부(Attachments)]

CompUsers.zip




* 맺음글(Conclusion)


1~5개의 글을 추가로 살펴보면 되겠다.

반응형

+ Recent posts