안경잡이개발자

728x90
반응형

  이번 시간에는 JSP 강의평가(Lecture Evaluation) 웹 사이트 개발하기의 여덟 번째 시간입니다. 지난 시간에는 로그인 및 로그아웃 기능을 구현했습니다. 이제 로그인 이후에 사용자들이 강의 평가 글을 등록하는 기능을 작성해보도록 하겠습니다. 또한 특정한 게시글 등에 대해서 신고를 하는 기능 또한 구현을 하려고 합니다. 바로 시작을 해보도록 합시다.



  위와 같이 두 개의 JSP 페이지를 추가합니다. 하나는 reportAction.jsp이고, 다른 하나는 evaluationRegisterAction.jsp입니다. 그리고 evaluation 패키지를 생성합니다. 이후에 해당 패키지 안에 EvaluationDTO.java, EvaluationDAO.java를 작성해주시면 됩니다.


  ▶ EvaluationDTO.java: 하나의 강의 평가 정보를 담고 있는 데이터베이스 트랜잭션 객체 역할을 담당합니다.


package evaluation;


public class EvaluationDTO {


int evaluationID;

String userID;

String lectureName;

String professorName;

int lectureYear;

String semesterDivide;

String lectureDivide;

String evaluationTitle;

String evaluationContent;

String totalScore;

String creditScore;

String comfortableScore;

String lectureScore;

int likeCount;

public int getEvaluationID() {

return evaluationID;

}

public void setEvaluationID(int evaluationID) {

this.evaluationID = evaluationID;

}

public String getUserID() {

return userID;

}

public void setUserID(String userID) {

this.userID = userID;

}

public String getLectureName() {

return lectureName;

}

public void setLectureName(String lectureName) {

this.lectureName = lectureName;

}

public String getProfessorName() {

return professorName;

}

public void setProfessorName(String professorName) {

this.professorName = professorName;

}

public int getLectureYear() {

return lectureYear;

}

public void setLectureYear(int lectureYear) {

this.lectureYear = lectureYear;

}

public String getSemesterDivide() {

return semesterDivide;

}

public void setSemesterDivide(String semesterDivide) {

this.semesterDivide = semesterDivide;

}

public String getLectureDivide() {

return lectureDivide;

}

public void setLectureDivide(String lectureDivide) {

this.lectureDivide = lectureDivide;

}

public String getEvaluationTitle() {

return evaluationTitle;

}

public void setEvaluationTitle(String evaluationTitle) {

this.evaluationTitle = evaluationTitle;

}

public String getEvaluationContent() {

return evaluationContent;

}

public void setEvaluationContent(String evaluationContent) {

this.evaluationContent = evaluationContent;

}

public String getTotalScore() {

return totalScore;

}

public void setTotalScore(String totalScore) {

this.totalScore = totalScore;

}

public String getCreditScore() {

return creditScore;

}

public void setCreditScore(String creditScore) {

this.creditScore = creditScore;

}

public String getComfortableScore() {

return comfortableScore;

}

public void setComfortableScore(String comfortableScore) {

this.comfortableScore = comfortableScore;

}

public String getLectureScore() {

return lectureScore;

}

public void setLectureScore(String lectureScore) {

this.lectureScore = lectureScore;

}

public int getLikeCount() {

return likeCount;

}

public void setLikeCount(int likeCount) {

this.likeCount = likeCount;

}

public EvaluationDTO(int evaluationID, String userID, String lectureName, String professorName, int lectureYear,

String semesterDivide, String lectureDivide, String evaluationTitle, String evaluationContent,

String totalScore, String creditScore, String comfortableScore, String lectureScore, int likeCount) {

super();

this.evaluationID = evaluationID;

this.userID = userID;

this.lectureName = lectureName;

this.professorName = professorName;

this.lectureYear = lectureYear;

this.semesterDivide = semesterDivide;

this.lectureDivide = lectureDivide;

this.evaluationTitle = evaluationTitle;

this.evaluationContent = evaluationContent;

this.totalScore = totalScore;

this.creditScore = creditScore;

this.comfortableScore = comfortableScore;

this.lectureScore = lectureScore;

this.likeCount = likeCount;

}

}


  ▶ EvaluationDAO.java: 강의 평가와 관련된 데이터베이스 접근을 가능하게 해주는 객체입니다.


package evaluation;


import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;


public class EvaluationDAO {


private Connection conn;

private ResultSet rs;


public EvaluationDAO() {

try {

String dbURL = "jdbc:mysql://localhost:3306/LectureEvaluation";

String dbID = "데이터베이스 아이디";

String dbPassword = "데이터베이스 비밀번호";

Class.forName("com.mysql.jdbc.Driver");

conn = DriverManager.getConnection(dbURL, dbID, dbPassword);

} catch (Exception e) {

e.printStackTrace();

}

}

public int write(EvaluationDTO evaluationDTO) {

PreparedStatement pstmt = null;

try {

String SQL = "INSERT INTO EVALUATION VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0);";

pstmt = conn.prepareStatement(SQL);

pstmt.setString(1, evaluationDTO.getUserID());

pstmt.setString(2, evaluationDTO.getLectureName());

pstmt.setString(3, evaluationDTO.getProfessorName());

pstmt.setInt(4, evaluationDTO.getLectureYear());

pstmt.setString(5, evaluationDTO.getSemesterDivide());

pstmt.setString(6, evaluationDTO.getLectureDivide());

pstmt.setString(7, evaluationDTO.getEvaluationTitle());

pstmt.setString(8, evaluationDTO.getEvaluationContent());

pstmt.setString(9, evaluationDTO.getTotalScore());

pstmt.setString(10, evaluationDTO.getCreditScore());

pstmt.setString(11, evaluationDTO.getComfortableScore());

pstmt.setString(12, evaluationDTO.getLectureScore());

return pstmt.executeUpdate();

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

if(pstmt != null) pstmt.close();

if(conn != null) conn.close();

} catch (Exception e) {

e.printStackTrace();

}

}

return -1;

}

}


  ▶ reportAction.jsp: 사용자가 신고서를 작성하면, 관리자의 메일로 그 신고 내용을 받습니다.


<%@page import="javax.mail.Transport"%>

<%@page import="javax.mail.Message"%>

<%@page import="javax.mail.Address"%>

<%@page import="javax.mail.internet.InternetAddress"%>

<%@page import="javax.mail.internet.MimeMessage"%>

<%@page import="javax.mail.Session"%>

<%@page import="javax.mail.Authenticator"%>

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

<%@page import="java.io.PrintWriter"%>

<%@page import="user.UserDAO"%>

<%@page import="util.SHA256"%>

<%@page import="util.Gmail"%>

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

<%

String userID = null;

if(session.getAttribute("userID") != null) {

userID = (String) session.getAttribute("userID");

}

if(userID == null) {

PrintWriter script = response.getWriter();

script.println("<script>");

script.println("alert('로그인을 해주세요.');");

script.println("location.href = 'userLogin.jsp'");

script.println("</script>");

script.close();

return;

}

request.setCharacterEncoding("UTF-8");

String reportTitle = null;

String reportContent = null;

if(request.getParameter("reportTitle") != null) {

reportTitle = (String) request.getParameter("reportTitle");

}

if(request.getParameter("reportContent") != null) {

reportContent = (String) request.getParameter("reportContent");

}

if (reportTitle == null || reportContent == null) {

PrintWriter script = response.getWriter();

script.println("<script>");

script.println("alert('입력이 안 된 사항이 있습니다.');");

script.println("history.back();");

script.println("</script>");

script.close();

return;

}

// 사용자에게 보낼 메시지를 기입합니다.

String host = "http://localhost:8080/Lecture_Evaluation/";

String from = "구글 계정 아이디";

String to = "관리자/개발자의 이메일 주소";

String subject = "강의평가 사이트에서 접수된 신고 메일입니다.";

String content = "신고자: " + userID + "<br>제목: " + reportTitle + "<br>내용: " + reportContent;

// SMTP에 접속하기 위한 정보를 기입합니다.

Properties p = new Properties();

p.put("mail.smtp.user", from);

p.put("mail.smtp.host", "smtp.googlemail.com");

p.put("mail.smtp.port", "465");

p.put("mail.smtp.starttls.enable", "true");

p.put("mail.smtp.auth", "true");

p.put("mail.smtp.debug", "true");

p.put("mail.smtp.socketFactory.port", "465");

p.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

p.put("mail.smtp.socketFactory.fallback", "false");

 

try{

    Authenticator auth = new Gmail();

    Session ses = Session.getInstance(p, auth);

    ses.setDebug(true);

    MimeMessage msg = new MimeMessage(ses); 

    msg.setSubject(subject);

    Address fromAddr = new InternetAddress(from);

    msg.setFrom(fromAddr);

    Address toAddr = new InternetAddress(to);

    msg.addRecipient(Message.RecipientType.TO, toAddr);

    msg.setContent(content, "text/html;charset=UTF-8");

    Transport.send(msg);

} catch(Exception e){

    e.printStackTrace();

PrintWriter script = response.getWriter();

script.println("<script>");

script.println("alert('오류가 발생했습니다.');");

script.println("history.back();");

script.println("</script>");

script.close();

    return;

}

PrintWriter script = response.getWriter();

script.println("<script>");

script.println("alert('정상적으로 신고되었습니다.');");

script.println("history.back();");

script.println("</script>");

script.close();

    return;

%>


  ▶ evaluationRegisterAction.jsp: 사용자가 평가를 등록하게 되면, 그 평가 등록을 처리합니다.


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

<%@ page import="evaluation.EvaluationDTO"%>

<%@ page import="evaluation.EvaluationDAO"%>

<%@ page import="java.io.PrintWriter"%>

<%

request.setCharacterEncoding("UTF-8");


String userID = null;

if(session.getAttribute("userID") != null) {

userID = (String) session.getAttribute("userID");

}

if(userID == null) {

PrintWriter script = response.getWriter();

script.println("<script>");

script.println("alert('로그인을 해주세요.');");

script.println("location.href = 'userLogin.jsp'");

script.println("</script>");

script.close();

return;

}

request.setCharacterEncoding("UTF-8");

String lectureName = null;

String professorName = null;

int lectureYear = 0;

String semesterDivide = null;

String lectureDivide = null;

String evaluationTitle = null;

String evaluationContent = null;

String totalScore = null;

String creditScore = null;

String comfortableScore = null;

String lectureScore = null;

if(request.getParameter("lectureName") != null) {

lectureName = (String) request.getParameter("lectureName");

}

if(request.getParameter("professorName") != null) {

professorName = (String) request.getParameter("professorName");

}

if(request.getParameter("lectureYear") != null) {

try {

lectureYear = Integer.parseInt(request.getParameter("lectureYear"));

} catch (Exception e) {

System.out.println("강의 연도 데이터 오류");

}

}

if(request.getParameter("semesterDivide") != null) {

semesterDivide = (String) request.getParameter("semesterDivide");

}

if(request.getParameter("lectureDivide") != null) {

lectureDivide = (String) request.getParameter("lectureDivide");

}

if(request.getParameter("evaluationTitle") != null) {

evaluationTitle = (String) request.getParameter("evaluationTitle");

}

if(request.getParameter("evaluationContent") != null) {

evaluationContent = (String) request.getParameter("evaluationContent");

}

if(request.getParameter("totalScore") != null) {

totalScore = (String) request.getParameter("totalScore");

}

if(request.getParameter("creditScore") != null) {

creditScore = (String) request.getParameter("creditScore");

}

if(request.getParameter("comfortableScore") != null) {

comfortableScore = (String) request.getParameter("comfortableScore");

}

if(request.getParameter("lectureScore") != null) {

lectureScore = (String) request.getParameter("lectureScore");

}

if (lectureName == null || professorName == null || lectureYear == 0 || semesterDivide == null ||

lectureDivide == null || evaluationTitle == null || evaluationContent == null || totalScore == null ||

creditScore == null || comfortableScore == null || lectureScore == null ||

evaluationTitle.equals("") || evaluationContent.equals("")) {

PrintWriter script = response.getWriter();

script.println("<script>");

script.println("alert('입력이 안 된 사항이 있습니다.');");

script.println("history.back();");

script.println("</script>");

script.close();

return;

} else {

EvaluationDAO evaluationDAO = new EvaluationDAO();

int result = evaluationDAO.write(new EvaluationDTO(0, userID, lectureName, professorName, lectureYear,

semesterDivide, lectureDivide, evaluationTitle, evaluationContent,

totalScore, creditScore, comfortableScore, lectureScore, 0));

if (result == -1) {

PrintWriter script = response.getWriter();

script.println("<script>");

script.println("alert('평가 등록에 실패했습니다.');");

script.println("history.back();");

script.println("</script>");

script.close();

return;

} else {

PrintWriter script = response.getWriter();

script.println("<script>");

script.println("location.href = './index.jsp';");

script.println("</script>");

script.close();

return;

}

}

%>


  이제 한 번 테스트를 해봅시다.



  위와 같이 신고를 해보겠습니다.


  

  그럼 위와 같이 관리자 이메일로 신고 내용이 도착하는 것을 알 수 있습니다.


  평가 또한 등록해보도록 하겠습니다.



  성공적으로 평가 데이터가 데이터베이스에 등록되었습니다.

728x90
반응형

Comment +7

  • 김혁유 2018.05.14 23:56

    관리자의 승인을 기다리고 있는 댓글입니다

  • 살길바라냐 2018.06.14 13:07

    인프런에 답변이 없으셔서요 jdbc 최신버전인데도 안되네요 해결방법 없나요?


    Loading class com.mysql.jdbc.Driver'. This is deprecated. The new driver class iscom.mysql.cj.jdbc.Driver’. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
    Thu Jun 14 00:00:33 KST 2018 WARN: Establishing SSL connection without server’s identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn’t set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to ‘false’. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
    java.sql.SQLException: The server time zone value ‘´???¹?±¹ ???ؽ?’ is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:127)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:87)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:61)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:71)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:862)
    at com.mysql.cj.jdbc.ConnectionImpl.(ConnectionImpl.java:444)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:230)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:226)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at util.DatabaseUtil.getConnection(DatabaseUtil.java:14)
    at user.UserDAO.join(UserDAO.java:14)
    at org.apache.jsp.userJoinAction_jsp._jspService(userJoinAction_jsp.java:139)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    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:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
    Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value ‘´???¹?±¹ ???ؽ?’ is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:59)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:83)
    at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:128)
    at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2201)
    at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2225)
    at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1391)
    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:993)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:852)
    … 36 more
    java.lang.NullPointerException
    at user.UserDAO.join(UserDAO.java:15)
    at org.apache.jsp.userJoinAction_jsp._jspService(userJoinAction_jsp.java:139)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    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:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

  • 초보입니다. 2018.07.01 16:08

    관리자의 승인을 기다리고 있는 댓글입니다

  • 2019.06.19 23:32

    비밀댓글입니다

  • 2019.10.02 01:42

    비밀댓글입니다