자바 개발 20일차 - JSP와 MYSQL 연동

김경빈·2023년 1월 2일
0

오늘은 MYSQL과 JSP를 연동하는법을 배웠다.

처음에는 이정도쯤이야 정말 별거 아니라고 생각이 들었는데, 내 pc의 탐캣, JAVA EE와 MYSQL.. 전부 버전이 제각각이라 삭제후 재설치.. 백업... 이것때문에 정말 시간이 많이 들었다..

오늘 대부분의 프로그램들을 전부 최신버전을 바꿔놨으니 근 몇년동안은 버전이 달라 생기는 문제는 없을거라 생각한다ㅜㅜ


먼저 MYSQL 다운후 cmd명령 프롬프트를 통해서 데이터베이스 구축을하였다.

userID와 userPassword를 구축한후....


userDTO를 만들었다!!

위의 사진처럼 getter와 setter를 만들어주었다. getter는 현재 기록된 데이터를 가져오는것이고, setter는 데이터를 기록하는것이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package user;
 
public class UserDTO {
    
String userID;
String userPassword;
public String getUserID() {
    return userID;
}
public void setUserID(String userID) {
    this.userID = userID;
}
public String getUserPassword() {
    return userPassword;
}
public void setUserPassword(String userPassword) {
    this.userPassword = userPassword;
}
 
}
 
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package util;
 
import java.sql.Connection;
import java.sql.DriverManager;
 
public class DatabaseUtil {
 
    public static Connection getConnection() {
        try {
            String dbURL = "jdbc:mysql://localhost:3306/TUTORIAL";
            String dbID = "root";
            String dbPassword = "root";
            Class.forName("com.mysql.jdbc.Driver");
            return DriverManager.getConnection(dbURL, dbID, dbPassword);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
 
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package user;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
 
import util.DatabaseUtil;
 
public class UserDAO {
 
    public int join(String userID, String userPassword) {
        String SQL = "INSERT INTO USER VALUES (?, ?)";
        try {
            Connection conn = DatabaseUtil.getConnection();
            PreparedStatement pstmt = conn.prepareStatement(SQL);
            pstmt.setString(1, userID);
            pstmt.setString(1, userPassword);
            return pstmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }
}
 
cs

위와같이 UserDAO와 UserDTO, DatabaseUtil을 만든후...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>우리의 첫 번째 페이지</title>
</head>
<body>
JSP를 시작해보자!! 
<form action="./userJoinAction.jsp" method="post">
    <input type = "text" name="userID">
    <input type = "password" name="userPassword">
    <input type = "submit" value="회원가입">
    </form>
</body>
</html>
cs

index.jsp까지 위와 같이 작성을 하게되면

회원가입창의 기본적인 구조가 완성이 된다.
HTML로 하면 정말 금방이였는데 JSP로 작동을하니 확실히 어렵다..


이렇게 들뜬 마음으로 회원가입을 해보면?????

놀랍게도 흰 화면이 나오게 된다!!!

네이버와 구글에 열심히 검색을 해봐도 안나온다.. 하지만 어제 새벽부터 버전차이로 이미 고생을 해본결과 아마 대부분의 인강 혹은 유투브 강의는 몇년전 강의이므로 최신 커넥트 툴을 다운받으면 된다고 생각을했다.

바로 최신 mysql -connector를 다운받았다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@page import ="user.UserDTO" %>
    <%@page import ="user.UserDAO" %>
    <%@page import ="java.io.PrintWriter" %>
    <%
    request.setCharacterEncoding("UTF-8");
    String userID = null;
    String userPassword = null;
    if(request.getParameter("userID"!= null) {
        userID =(String) request.getParameter("userID");
        }
    if(request.getParameter("userPassword"!= null) {
        userPassword =(String) request.getParameter("userPassword");
        }
    if(userID == null || userPassword == null) {
        PrintWriter script = response.getWriter();
        script.println("<script>");
        script.println("alert('입력이 안 된 사항이 있습니다.');");
        script.println("history.back();");
        script.println("<script>");
        script.close();
        return;
        }
    
    UserDAO userDAO = new UserDAO();
    int result = userDAO.join(userID, userPassword);
    if (result == 1) {
    PrintWriter script = response.getWriter();
    script.println("<script>");
    script.println("alert('회원가입에 성공했습니다.');");
    script.println("location.href = 'index.jsp;");
    script.println("<script>");
    script.close();
    return;
    }
     %>
cs

앞서 만든 코드의 모든 에러를 잡아준후 실행을 시켜주게 된다면...

안뜬다!!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
1월 022023 10:20:23 오후 org.apache.catalina.startup.VersionLoggerListener log
정보: 서버 버전 이름:    Apache Tomcat/8.5.84
1월 022023 10:20:23 오후 org.apache.catalina.startup.VersionLoggerListener log
정보: Server 빌드 시각:  Nov 16 2022 13:34:24 UTC
1월 022023 10:20:23 오후 org.apache.catalina.startup.VersionLoggerListener log
정보: Server 버전 번호:  8.5.84.0
1월 022023 10:20:23 오후 org.apache.catalina.startup.VersionLoggerListener log
정보: 운영체제 이름:     Windows 10
1월 022023 10:20:23 오후 org.apache.catalina.startup.VersionLoggerListener log
정보: 운영체제 버전:     10.0
1월 022023 10:20:23 오후 org.apache.catalina.startup.VersionLoggerListener log
정보: 아키텍처:          amd64
1월 022023 10:20:23 오후 org.apache.catalina.startup.VersionLoggerListener log
정보: 자바 홈:           C:\Program Files\Eclipse Foundation\jdk-11.0.12.7-hotspot
1월 022023 10:20:23 오후 org.apache.catalina.startup.VersionLoggerListener log
정보: JVM 버전:          11.0.12+7
1월 022023 10:20:23 오후 org.apache.catalina.startup.VersionLoggerListener log
정보: JVM 벤더:          Eclipse Foundation
1월 022023 10:20:23 오후 org.apache.catalina.startup.VersionLoggerListener log
정보: CATALINA_BASE:     C:\Users\김경빈\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
1월 022023 10:20:23 오후 org.apache.catalina.startup.VersionLoggerListener log
정보: CATALINA_HOME:     C:\apache-tomcat-8.5.84
1월 022023 10:20:23 오후 org.apache.catalina.startup.VersionLoggerListener log
정보: 명령 행 아규먼트:  -Dcatalina.base=C:\Users\김경빈\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
1월 022023 10:20:23 오후 org.apache.catalina.startup.VersionLoggerListener log
정보: 명령 행 아규먼트:  -Dcatalina.home=C:\apache-tomcat-8.5.84
1월 022023 10:20:23 오후 org.apache.catalina.startup.VersionLoggerListener log
정보: 명령 행 아규먼트:  -Dwtp.deploy=C:\Users\김경빈\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
1월 022023 10:20:23 오후 org.apache.catalina.startup.VersionLoggerListener log
정보: 명령 행 아규먼트:  --add-opens=java.base/java.lang=ALL-UNNAMED
1월 022023 10:20:23 오후 org.apache.catalina.startup.VersionLoggerListener log
정보: 명령 행 아규먼트:  --add-opens=java.base/java.io=ALL-UNNAMED
1월 022023 10:20:23 오후 org.apache.catalina.startup.VersionLoggerListener log
정보: 명령 행 아규먼트:  --add-opens=java.base/java.util=ALL-UNNAMED
1월 022023 10:20:23 오후 org.apache.catalina.startup.VersionLoggerListener log
정보: 명령 행 아규먼트:  --add-opens=java.base/java.util.concurrent=ALL-UNNAMED
1월 022023 10:20:23 오후 org.apache.catalina.startup.VersionLoggerListener log
정보: 명령 행 아규먼트:  --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED
1월 022023 10:20:23 오후 org.apache.catalina.startup.VersionLoggerListener log
정보: 명령 행 아규먼트:  -Dfile.encoding=UTF-8
1월 022023 10:20:23 오후 org.apache.catalina.core.AprLifecycleListener lifecycleEvent
정보: 프로덕션 환경들에서 최적의 성능을 제공하는, APR 기반 Apache Tomcat Native 라이브러리가, 다음 java.library.path에서 발견되지 않습니다: [C:\Program Files\Eclipse Foundation\jdk-11.0.12.7-hotspot\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jdk-19/bin/server;C:/Program Files/Java/jdk-19/bin;C:\Program Files\Java\jdk-19\bin;C:\Program Files\Common Files\Oracle\Java\javapath;C:\Program Files\Eclipse Foundation\jdk-11.0.12.7-hotspot\bin;C:\Program Files (x86)\VMware\VMware Player\bin\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Java\jdk-17\bin;C:\Program Files\Git\cmd;C:\Program Files\MySQL\MySQL Server 8.0\bin;C:\Users\김경빈\AppData\Local\Microsoft\WindowsApps;C:\Program Files\Java\jdk-17\bin;C:\Users\김경빈\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\김경빈\AppData\Local\GitHubDesktop\bin;;C:\Program Files\JavaDev\eclipse-jee-2019-06-R-win32-x86_64\eclipse;;.]
1월 022023 10:20:23 오후 org.apache.coyote.AbstractProtocol init
정보: 프로토콜 핸들러 ["http-nio-8080"]을(를) 초기화합니다.
1월 022023 10:20:23 오후 org.apache.catalina.startup.Catalina load
정보: Initialization processed in 791 ms
1월 022023 10:20:23 오후 org.apache.catalina.core.StandardService startInternal
정보: 서비스 [Catalina]을(를) 시작합니다.
1월 022023 10:20:23 오후 org.apache.catalina.core.StandardEngine startInternal
정보: 서버 엔진을 시작합니다: [Apache Tomcat/8.5.84]
1월 022023 10:20:24 오후 org.apache.catalina.util.SessionIdGeneratorBase createSecureRandom
경고: [SHA1PRNG] 알고리즘을 사용하여, 세션 ID를 생성하기 위한 SecureRandom 객체를 생성하는데, [319] 밀리초가 소요됐습니다.
1월 022023 10:20:24 오후 org.apache.jasper.servlet.TldScanner scanJars
정보: 적어도 하나의 JAR가 TLD들을 찾기 위해 스캔되었으나 아무 것도 찾지 못했습니다. 스캔했으나 TLD가 없는 JAR들의 전체 목록을 보시려면, 로그 레벨을 디버그 레벨로 설정하십시오. 스캔 과정에서 불필요한 JAR들을 건너뛰면, 시스템 시작 시간과 JSP 컴파일 시간을 단축시킬 수 있습니다.
1월 022023 10:20:24 오후 org.apache.coyote.AbstractProtocol start
정보: 프로토콜 핸들러 ["http-nio-8080"]을(를) 시작합니다.
1월 022023 10:20:24 오후 org.apache.catalina.startup.Catalina start
정보: Server startup in 1709 ms
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:828)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:448)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:241)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:198)
    at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
    at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
    at util.DatabaseUtil.getConnection(DatabaseUtil.java:14)
    at user.UserDAO.join(UserDAO.java:13)
    at org.apache.jsp.userJoinAction_jsp._jspService(userJoinAction_jsp.java:141)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:765)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:465)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:383)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:331)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:765)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:177)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:543)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:698)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:367)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:639)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:885)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1688)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:829)
java.lang.NullPointerException
    at user.UserDAO.join(UserDAO.java:14)
    at org.apache.jsp.userJoinAction_jsp._jspService(userJoinAction_jsp.java:141)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:765)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:465)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:383)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:331)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:765)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:177)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:543)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:698)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:367)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:639)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:885)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1688)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:829)
cs

어디선가 에러가 난것 같은데...

비밀번호도 바꾸어보고... 코드도 바꾸어보았다!!!!

완성!!!

데이터베이스에도 잘 기록된 것을 볼수있다.

profile
매일매일 무한한 근성으로 코드를 작성합니다.

0개의 댓글