Archive

JSP/Servlet-Servlet 로그인 구현

|

JSP/Servlet - Servlet 로그인 구현


DB를 연동하여 로그인 기능을 구현해보자

// 로그인 GUI
import java.io.*
import javax.servlet.*;
import javax.servlet.http.*;

public class Login extends HttpServlet {      
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	response.setContentType("text/html;charset=utf-8");
    	PrintWriter out = response.getWriter();
    	try {
    		HttpSession session = request.getSession(false);
            // 저장된 세션 여부에 따라 다른 화면 출력
    		if(session != null) {
    			String sessionId = session.getId();
    			System.out.println("세션 아이디: "+sessionId);
    			String user = (String) session.getAttribute("user");
                // 로그인 후 화면
    			out.println("<html>");
    			out.println("<body>");
    			out.println("<table border=1 width=300>");
    			out.println("<tr>");
    			out.println("<td width=300 align=center>"+user+"님이 로그인했습니다.");
    			out.println("</tr>");
    			out.println("<tr>");
    			out.println("<td align=center>");
    			out.println("<a href='#'>회원정보</a>");
    			out.println("<a href='Logout'>로그아웃</a>");
    			out.println("</td>");
    			out.println("</tr>");
    			out.println("</table>");
    			out.println("</body>");
    			out.println("</html>");
    		} else {
                // 로그인 화면
    			out.println("<html>");
    			out.println("<body>");
    			out.print("<form method=post action=LoginCheck>");
    			out.println("<table border=1 width=300>");
    			out.println("<tr>");
    			out.println("<th width=100>아이디</th>");
    			out.println("<td width=200>&nbsp;<input type=text name=id></td>");
    			out.println("</tr>");
    			out.println("<tr>");
    			out.println("<th width=100>비번</th>");
    			out.println("<td width=200>&nbsp;<input type=password name=pwd></td>");
    			out.println("</tr>");
    			out.println("<tr>");
    			out.println("<td align=center colspan=2>");
    			out.println("<input type=button value=회원가입>");
    			out.println("<input type=submit value=로그인>");
    			out.println("</td>");
    			out.println("</tr>");
    			out.println("</form>");
    			out.println("</table>");
    			out.println("</body>");
    			out.println("</html>");
    		}
    	} finally {
    		out.close();
    	}
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
}


// DB연동 로그인 확인 서블릿
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoginCheck extends HttpServlet {    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("utf-8"); // 한글 처리
    	String id = request.getParameter("id"); // 사용자 입력 id
    	String pwd = request.getParameter("pwd"); // 사용자 입력 pwd
    	
    	// db에서 사용자 정보 조회
    	StringBuffer sql = new StringBuffer();
    	sql.append("select * from login");
    	Connection con = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
    	
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection("jdbc:mysql://localhost:3306/visit_db?characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false","root","123456");
    		pstm = con.prepareStatement(sql.toString());
    		rs = pstm.executeQuery();
    		
    		while(rs.next()) {
    			String dbId = rs.getString("id");
    			String dbPwd = rs.getString("pass");
    			
    			if(dbId.equals(id) && dbPwd.equals(pwd)) {
    	    		HttpSession session = request.getSession();
    	    		// 클라이언트 정보를 HttpSession에 저장
    	    		session.setAttribute("user", id);
    	    	}
    		}
		} catch(SQLException e) {
			e.printStackTrace();
		} catch(ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {if(pstm != null)pstm.close();}catch(SQLException e) {};
    		try {if(con != null)pstm.close();}catch(SQLException e) {};
		}
    	response.sendRedirect("Login");
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
    }
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
}


// 로그아웃 서블릿
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class Logout extends HttpServlet {      
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	HttpSession session = request.getSession(false);
  
    	if(session != null) {
            // 세션 무효화
    		session.invalidate();
    	}
        // 로그인 화면으로 화면 이동
    	response.sendRedirect("Login");
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
}


실행화면

실행1

실행2



참고 자료


KG 아이티뱅크 강의 자료

JSP/Servlet-Servlet 댓글 구현

|

JSP/Servlet - Servlet 댓글 구현


DB를 연동하여 사용자가 글을 남기면 방명록이 남는 댓글 기능을 구현해보자

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>방명록 작성하기</title>
</head>
<body>
    <!-- post 방식으로 서블릿에게 데이터 전달 -->
	<form method="post" action="/myWeb/VisitInsert">
		<table align="center" width="500" border="1">
			<tr>
				<th width="70">작성자</th>
			<td width="430">
				&nbsp;<input type="text" name="writer" size="50">
			</td>
			</tr>
			<tr>
			<th>내용</th>
			<td>
				&nbsp;<textarea rows="7" cols="50" name="memo"></textarea>
			</td>
			</tr>
			<tr>
				<td colspan="2" align="center">
					<input type="submit" value="저장">&nbsp;&nbsp;
					<input type="reset" value="취소">
				</td>
			</tr>
		</table>
	</form>
</body>
</html>


// 입력을 담당하는 서블릿
import java.io.*;
import java.sql.*
import javax.servlet.*;
import javax.servlet.http.*;

public class VisitInsert extends HttpServlet {
    // 편의상 doGet과 doPost를 한 곳에서 처리   
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("utf-8"); //한글처리
    	//client가 http 요청으로 전송한 값 읽기
    	String writer = request.getParameter("writer");
    	String memo = request.getParameter("memo");
    	
        // mysql DB에 HTTP 요청 데이터 저장
    	StringBuffer sql = new StringBuffer();
    	sql.append("insert into visit(writer,memo,regdate)");
    	sql.append("values (?, ?, curdate())");
    	Connection con = null;
    	PreparedStatement pstm = null;
    	try {
    		Class.forName("com.mysql.jdbc.Driver");
    		con = DriverManager.getConnection("jdbc:mysql://localhost:3306/visit_db?characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false","root","123456");
    		pstm = con.prepareStatement(sql.toString());
    		pstm.setString(1, writer);
    		pstm.setString(2, memo);
    		pstm.executeUpdate();
    	} catch(SQLException e) {
    		e.printStackTrace();
    	} catch(ClassNotFoundException e) {
    		e.printStackTrace();
    	} finally {
    		try {if(pstm != null)pstm.close();}catch(SQLException e) {};
    		try {if(con != null)pstm.close();}catch(SQLException e) {};
    	}
        // submit 후 페이지 이동
    	response.sendRedirect("VisitList");
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
}


// 웹서버에서 받은 데이터를 화면에 출력하는 서블릿
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class VisitList extends HttpServlet {
	private static final long serialVersionUID = 1L;
      
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    	response.setContentType("text/html;charset=utf-8");
    	PrintWriter out = response.getWriter();
    	
    	try {
    		out.println("<html>");
    		out.println("<head><title>방명록 리스트</title></head>");
    		out.println("<body>");
    		// DB에서 데이터 조회
    		StringBuffer sql = new StringBuffer();
    		sql.append("select * from visit");
    		Connection con = null;
    		PreparedStatement pstm = null;
    		ResultSet rs = null;
    		
    		try {
    			Class.forName("com.mysql.jdbc.Driver");
    			con = DriverManager.getConnection("jdbc:mysql://localhost:3306/visit_db?characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false","root","123456");
        		pstm = con.prepareStatement(sql.toString());
        		rs = pstm.executeQuery();
        		
        		while(rs.next()) {
        			int no = rs.getInt("no");
        			String writer = rs.getString("writer");
        			String memo = rs.getString("memo");
        			java.sql.Date regdate = rs.getDate("regdate");
        			out.println("<table align=center width=500 border=1>");
        			out.println("<tr>");
        			out.println("<th width=50>번호</th>");
        			out.println("<td width=50 align=center>"+no+"</td>");
        			out.println("<th width=70>작성자</th>");
        			out.println("<td width=180 align=center>"+writer+"</td>");
        			out.println("<th width=50>날짜</th>");
        			out.println("<td width=100 align=center>"+regdate+"</td>");
        			out.println("</tr>");
        			out.println("<tr>");
        			out.println("<th width=50>내용</th>");
        			out.println("<td colspan=5>&nbsp;<textarea rows=3 cols=50>"+memo+"</textarea></td>");
        			out.println("</tr>");
        			out.println("</table>");
        			out.println("<p>");
        		}
    		} catch(SQLException e) {
    			e.printStackTrace();
    		} catch(ClassNotFoundException e) {
    			e.printStackTrace();
    		} finally {
    			try {if(pstm != null)pstm.close();}catch(SQLException e) {};
        		try {if(con != null)pstm.close();}catch(SQLException e) {};
    		}
    		out.println("<p align=center><a href=/myWeb/bbs/write.html>글쓰기</a></p>");
    		out.println("</body>");
    		out.println("</html>");
    	} finally {
    		out.close();
    	}
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
}


실행 화면

실행1 실행2



참고 자료


KG 아이티뱅크 강의 자료

JSP/Servlet-Servlet 개요(2)

|

JSP/Servlet - Servlet 개요(2)


  1. HttpServletRequest

    • 컨테이너는 HTTP 요청으로 전달된 클라이언트의 요청 데이터를 HttpServletRequest 객체를 생성하여 이름/값으로 저장하고 서블릿에 전달
    • 주요 메소드

    리퀘스트

    메소드


  2. HttpServletResponse

    • 서버가 클라이언트로 보내는 응답정보를 처리하는 객체
    • 클라이언트로 전송될 응답 헤더정보를 설정하고 응답을 위한 스트림을 얻거나, 세션 관리를 위한 추가 정보를 설정할 수 있다
    • 주요 메소드

    리스폰스


    • http://tomcat.apache.org/tomcat-9.0-doc/servletapi/index.html api 문서 참조
  3. HttpSession

    • HTTP 프로토콜은 무상태(stateless)의 특징을 가지고 있기에 HttpSession 객체를 이용한다
    • 작동 순서
    • 클라이언트의 요청을 접수하면 HttpSession 객체를 생성하고 고유 id를 부여한다
    • HttpSession 객체 내에 클라이언트의 정보를 저장하고 고유 id와 함께 응답을 클라이언트로 보낸다
    • 클라이언트는 다음 요청부터 고유 id를 서버에 전송하고 서버는 id에 해당하는 HttpSession 객체를 찾아 요청을 처리한다
    • 주요 메소드

    세션




참고 자료


KG 아이티뱅크 강의 자료

처음 해보는 Servlet&JSP 웹 프로그래밍

JSP/Servlet-Servlet 개요

|

JSP/Servlet - Servlet 개요


  1. Servlet Container

    • 서블릿과 JSP는 동적 콘텐츠를 생성하는 웹 컴포넌트이다
    • 컨테이너는 이런 웹 컴포넌트를 저장하는 저장소 역할, 메모리 로딩, 객체 생성 및 초기화 등 서블릿의 생명주기를 관리하고 JSP를 서블릿으로 변환하는 기능을 수행한다
    • 컨테이너는 웹서버와 서블릿 사이의 통신을 지원한다
    • 컨테이너는 새로운 요청이 들어올 때 마다 자바 스레드를 생성하여 사용자의 요청을 처리한다
  2. Servlet

    • 서블릿은 웹 서버에서 실행되는 자바 프로그램이다

    • 클라이언트의 요청을 서버에서 실행 후 결과값을 클라이언트에게 전송

    • HTTP 프로토콜로 통신하는 웹의 특징을 활용할 수 있는 API가 제공된다

    • 최초 생성된 서블릿 객체를 재사용하여 처리속도가 빠르다

    • javax.servlet.http.HttpServlet 클래스를 상속받아서 service() 메소드를 재정의하여 서블릿 프로그램을 작성

    • HttpServlet의 부모 클래스는 GenericServlet으로 service() 메소드를 제외한 모든 메소드를 가지고 있다

    • 서블릿의 실행 순서

      1. 클라이언트로부터 처리 요청을 받는다 : 웹 서버에서 요청을 받아 헤더의 URI를 분석, 요청받은 페이지가 서블릿이면 서블릿 컨테이너에 넘긴다
      2. 서블릿 객체 생성 : 서블릿 컨테이너는 최초 요청 여부를 판단하여 객체를 생성한다. HttpServletRequest, HttpServletResponse 객체를 생성, url을 분석하여 서블릿 객체 생성, 사용자의 요청을 처리하기 위한 스레드 생성
      3. init() 메소드 실행 : 서블릿 객체 생성 후 init() 호출, 초기화를 담당한다
      4. service() 메소드 실행 : 클라이언트의 요청에 맞는 처리를 한다.(doGet, doPost)
      5. 요청 방식에 따른 메소드 실행 후 응답을 클라이언트에게 전송
      6. destroy() 메소드를 호출하여 자원해제 작업을 실행한다 (서비스,서버 중지 시)


  3. 배포서술자(Deploy Descriptor : DD)

    • web.xml 파일
    • 배포서술자는 서블릿과 jsp를 어떻게 실행하는지에 대한 환경설정 정보가 들어있다
    • 배포서술자는 서블릿과 URL을 매핑시키는 작업을 한다
    • 배포 서술자는 URL 매핑 외에 보안 설정, 오류 페이지 설정, 초기화 구성 등의 내용 등도 설정 할 수 있다
  4. 초기 파라미터

    • ServletConfig : 컨테이너가 서블릿을 생성할 때 생성되는 객체
    • DD를 읽어 이름/값의 쌍으로 된 초기화 파라미터를 읽어서 저장한다
    • ServletConfig 객체는 Servlet 객체당 한 개씩 생성
    <servlet>
    	<init-param>
        	<param-name>이름</param-name>
            <param-value></param-value>
        </init-param>
    </servlet>
    
    • ServletContext : 웹 애플리케이션 당 하나씩 생성
    • 웹 애플리케이션 전역에서 참조할 수 있는 초기화 파라미터를 저장한다
    • web.xml의 가장 위쪽에 위치시키는 것이 좋다
    <context-param>
    	<param-name>이름</param-name>
        <param-value></param-value>
    </context-param>
    
    @Override
    public void init() throws ServletException {
     	String name = getServletContext().getInitParameter("이름 혹은 값");
    	String name = getServletConfig().getInitParameter("이름 혹은 값");   
    }
    




참고 자료


KG 아이티뱅크 강의 자료

처음 해보는 Servlet&JSP 웹 프로그래밍

2021-02-15 TIL

|

2021-02-15 TIL


  • 오늘 한 것
    1. 리액트 공부 Redux - 지금까지 만든 튜토리얼 프로젝트를 수정하여 action creator로 action을 분류하고 redux-thunk를 이용하여 서버사이드 HTTP request를 action에서 비동기로 처리하게끔 바꾸는 작업을 했다.
    2. 학원 비대면 수업 (15:30~22:00) JSP/Servlet 환경 구축 - 오늘부터 JSP / Servlet 진도를 나간다. 항상 새로운 것을 배울때마다, 처음 개발환경을 구축할때 느끼는 설레임, 긴장 같은 감정들이 있다.



  • 내일 할 것
    1. 리액트 공부 - React The complete Guide
    2. 학원 비대면 수업(15:30~22:00)



  • 끝으로

훈련 과정의 절반정도가 지났다. 나는 지금 어디쯤 와있을까? 요즘 이런저런 생각이 많지만 아직은 계속 앞만 보고 달려야할 때라고 생각한다.

오늘의 한 줄 총평 : 다시 초심으로