3은로그

지능웹 프로젝트 - 고양이 분양 폼 만들고 DB 연결 본문

HTML CSS JS

지능웹 프로젝트 - 고양이 분양 폼 만들고 DB 연결

3은 2022. 11. 22. 22:03
728x90

 

이 기능을 구현하기 위해 며칠 동안 잠도 잘 못자고 고민했다.

잊지 않기 위해 작성했다.

 

 

 1. addCat.jsp에서 폼으로 데이터를 입력받는다.

<form name = "form" action="processAddCat.do" class="form-horizontal" method="post" enctype="multipart/form-data">
    <div class = "mb-3">
        <label for="uploadFile" class="form-label">사진</label>
        <div class="input-group">
            <input type="file" class="form-control" name="catImage" id="uploadFile" accept="image/*">
            <%--button class="btn btn-secondary" class="input-group-text" onclick="uploadfile()">업로드</button>--%>
        </div>
    </div>
    <div class="mb-3">
        <label for="exampleFormControlInput1" class="form-label">묘종</label>
        <input name = "catType" type="text" class="form-control" id="exampleFormControlInput1" placeholder="">
    </div>
    <div class="mb-3">
        <label for="exampleFormControlInput2" class="form-label">나이</label>
        <input name = "age" type="text" class="form-control" id="exampleFormControlInput2" placeholder="">
    </div>
    <div class="mb-3">
        <label for="exampleFormControlInput3" class="form-label">성별</label>
        <input name = "gender" type="text" class="form-control" id="exampleFormControlInput3" placeholder="">
    </div>
    <div class="mb-3">
        <label for="exampleFormControlInput5" class="form-label">보호위치</label>
        <input name = "location" type="text" class="form-control" id="exampleFormControlInput5" placeholder="">
    </div>
    <div class="mb-3">
        <label for="exampleFormControlInput4" class="form-label">특이사항</label>
        <textarea name = "etc" type="text" class="form-control" id="exampleFormControlInput4" placeholder=""></textarea>
    </div>
    <div class="mb-3">
        <input class="w-100 btn btn-lg btn-secondary" type = "button" value="등록" onclick="addCat()">
    </div>
</form>
<script>
    function addCat() {
        let catImage = document.form.catImage.value;
        let catType = document.form.catType.value;
        let age = document.form.age.value;
        let gender = document.form.gender.value;
        let location = document.form.location.value;
        let etc = document.form.etc.value;
        //alert(cat_type + age + gender + location);

        if(catImage == "") {
            alert("사진을 업로드하세요");
            document.form.catType.focus();
            return;
        }
        if(catType == "") {
            alert("묘종을 입력하세요");
            document.form.catType.focus();
            return;
        }
        if(age == "") {
            alert("나이를 입력하세요");
            document.form.age.focus();
            return;
        }
        if(gender == "") {
            alert("성별을 입력하세요");
            document.form.gender.focus();
            return;
        }
        if(location == "") {
            alert("보호위치를 입력하세요");
            document.form.location.focus();
            return;
        }
        if(etc == "") {
            alert("특이사항을 입력하세요");
            document.form.location.focus();
            return;
        }

       document.form.submit();
    }
</script>

- 등록 버튼을 누르면 addCat() 함수가 실행된다.

- 폼에서 값을 각자 가져와서 유효성 검사를 한다. 

- 폼에 모든 값이 다 입력되면 submit한다.

- form action은 processAddCat.do 이다. class.properties 파일에서 processAddCat.do를 찾는다.

class.properties

- class.properties를 보면 ProcessAddCatAction으로 연결되어 있는것을 알 수 있다.

 

2. 

ProcessAddCatAction.java

public class ProcessAddCatAction implements Action {
    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    
        String filename = "";
        String realFolder = "C:\\webproject2022\\web\\img";     //절대경로
        int maxSize = 5 * 1024 * 1024;                          //최대 업로드될 파일의 크기
        String encType = "utf-8";                               //인코딩 유형

        MultipartRequest multi = new MultipartRequest(request, realFolder, maxSize, encType, new DefaultFileRenamePolicy());

        String catType = multi.getParameter("catType");
        String age = multi.getParameter("age");
        String gender = multi.getParameter("gender");
        String location = multi.getParameter("location");
        String etc = multi.getParameter("etc");

        Enumeration files = multi.getFileNames();
        String fname = (String)files.nextElement();
        String fileName = multi.getFilesystemName(fname);
        //String realFile = realFolder + "\\" + fileName;

        String text = fileName+"-/-/-"+catType+"-/-/-"+age+"-/-/-"+gender+"-/-/-"+location+"-/-/-"+etc;
        request.setAttribute("text" , text);
        return "RequestDispatcher:jsp/processAddCat.jsp";
    }
}

- MultipartRequest를 사용해서 이미지 파일을 서버에 올리고 파일 이름을 설정한다.

- 폼에서 받은 데이터들을 multi.getParameter()로 불러오고 String 변수에 "-/-/-"을 통해 이어서 하나의 String 변수로 만들어준다. (서버에 데이터를 보내고 DB에 저장하기 위함)

- request.setAttribute("text", text); 코드를 통해 text를 processAddCat.jsp에서 불러와서 사용할 수 있다. 

- 위 코드를 다 실행 후 processAddCat.jsp로 이동한다.

 

3.

processAddCat.jsp

<head>
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <%
       String text = (String)request.getAttribute("text");
       System.out.println("text is " + text);
    %>
</head>
<script>

    $(document).ready(function(){
        addCat();
    })
    function addCat() {
        $.ajax({
            url: "ajax.do",
            type: "POST",
            data: {
                req: "addCat",
                data: "<%=text%>",
            },
            success: function (data) {
                alert(data);
                location.href = "/";
            }
        })
    }
</script>

- ProcessAddCatAction.java에서 request.setAttribute("text", text) 한 것을

String text = (String)request.getAttribute("text");

 

위 코드로 가져와서 String 변수에 저장한다. 이제 processAddCat.jsp에서 text 사용 가능하다.

-  아래 코드를 통해 해당 jsp가 뜨면 바로 addCat() 함수를 호출한다.

$(document).ready(function(){
    addCat();
})

-  addCat() 함수는 서버로 데이터를 보내는 함수이다.

- ajax.do로 post 방식으로 data를 보내고 이것을 성공하면  아래 코드를 실행한다. 

success: function (data) {
    alert(data);
    location.href = "/";
}

- 그럼 다시 $.ajax를 설명하면

$.ajax({
    url: "ajax.do",
    type: "POST",
    data: {
        req: "addCat",
        data: "<%=text%>",
    },
    success: function (data) {
        alert(data);
        location.href = "/";
    }
})

ajax.do이니까 class.properties에서 ajax.do를 찾는다. 

data : "<%=text%>" 는 위에서 getAttribute로 받아온 값을  string으로 넘겨주는 것이다. " "를 무조건 해줘야한다.

class.properties

AjaxAction.java로 이동한다.  

- 이때 data는 String text 에 저장된 값으로 폼에 입력된 데이터를 하나로 만든것이다. 

public class AjaxAction implements Action {
    /**
     * DB를 JSP에서 JAVA로 보낼 때 사용하는 클래스입니다.
     * JSP의 ajax에서 정해준 req, data 값을 가지고 작업을 하게됩니다.
     * req는 필요한 case문을 찾아 들어가는데 사용하고
     * data는 DAO로 넘길 데이터를 의미합니다.
     * data의 경우에는 "일반적으로" JS가 여러 데이터 값을 한줄로 합쳐놓은 상태입니다.
     * 따라서 마지막으로 받는 메소드는 항상 split해줘야 하는지 고민해야 합니다.
     * */


    public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Gson gson = new Gson();
        String req = request.getParameter("req"); //JSP에서 넘겨준 req
        HttpSession session = request.getSession(); //Session에 있는 정보로 뭔가 해야할 때 사용
        String data = request.getParameter("data"); //JSP에서 넘겨준 data
        String result=null;
        System.out.println(req);
        System.out.println(data);

        switch(req) {
   /*         case "signup":
                result= UserDAO.getInstance().addUser(data);
                break;*/
            case "addCat":
                System.out.println(data);
                result= CatDAO.getInstance().addCat(data);
                break;
        }

        return result;
    }
}

-  CatDAO 함수 호출

CatDAO.getInstance().addCat(data);

 

public class CatDAO {
    public static CatDAO it;

    public static CatDAO getInstance(){
        if(it==null)
            it = new CatDAO();
        return it;
    }

    public String addCat(String data) {
        System.out.println(data + " here is CatDAO and this is text");
        String [] arr = data.split("-/-/-");    //받아온 한 줄짜리 데이터를 배열로 쪼개기
        String fileName = arr[0];
        String catType = arr[1];
        String age = arr[2];
        String gender = arr[3];
        String location = arr[4];
        String etc = arr[5];

        Connection conn = Config.getInstance().sqlLogin();
        try {
            QueryRunner queryRunner = new QueryRunner();
            queryRunner.update(conn,
                    "INSERT INTO `cat`(fileName, catType, age, gender, location, etc) " +
                            "VALUES (?,?,?,?,?,?)", fileName,catType,age,gender,location,etc);
        }
        catch (SQLException se){
            se.printStackTrace();
        }
        finally {
            DbUtils.closeQuietly(conn);
        }
        return "등록되었습니다";
    }
}

- 받아온 String을 "-/-/-"로 나눠서 배열에 하나씩 저장하고  sql문 작성하면 DB에 저장된다.

- 그 후 "등록되었습니다" 가 return 되고, AjaxAction.java에서 result에 저장된 후 다시 return 되어 ajax이 success funtion(data)에 data로 전달된다.

 - 그리고 main 페이지로 돌아가고 끝난다.

'HTML CSS JS' 카테고리의 다른 글

JS 로그인 기능  (0) 2022.11.21
웹프로젝트 기본세팅  (0) 2022.11.21