학교/JAVA

05) 서블릿 예제

서윤-정 2023. 12. 16. 23:18

(loginServlet.java)

package com.hy;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LoginServlet
 */
 // LoginServlet 클래스는 HTTPServlet을 상속하며
 // @WebServlet 어노테이션을 사용해 웹서비스에서의 URL 매핑 지정
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
     // HTTP GET 요청을 처리하는 메서드
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 0. 클라이언트가 전송한 요청 데이터 인코딩 방식을 utf-8로 지정하기
		request.setCharacterEncoding("utf-8");
		// 클라이언트가 전송할 응답 데이터 인코딩 방식 utf-8로 지정
		response.setCharacterEncoding("utf-8");
		// 1. 클라이언트에 응답할 페이지 환경 설정
		response.setContentType("text/html; charset=utf-8");
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		response.getWriter().print(" Hello Servelt!");
		response.getWriter().print("<br> 헬로우");
		
		// 2. response 출력 객체를 간소화 하기 위해 PrintWriter 객체 생성
		PrintWriter out = response.getWriter();
		// 3. html 출력문
		out.print("<h2>서블릿 구조를 이해하면, JSP도 쉽다</h2>");
		out.print("<hr>");
		
		// 사용자 입력 데이터 받고 응답하기
		// 1. 데이터 받기
		String id = request.getParameter("id");
		String ps = request.getParameter("ps");
		
		// 2. 처리 결과 응답
		out.print("User ID: " + id);
		out.print("<br>User PS: " + ps);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
     // HTTP POST 요청을 처리하기 위한 doPost 메서드를 구현하며
     // 여기서는 doGet 메서드를 호출하도록 되어있음
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

 

(login.html)

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<form action="LoginServlet" method="post">
<table align=center>
<tr><td colspan=2 align=center height=40><b>로그인</b><td></tr>
<tr>
<td align=right>아이디&nbsp;</td>
<td><input type="text" name="id" placeholder="Email address" required></td>
</tr>
<tr>
<td align=right>패스워드&nbsp;</td>
<td><input type="password" name="ps" required></td>
</tr>
<tr>
<td colspan=2 align=center height=50>
<input type="submit" value="로그인하기">
</td>
</tr>
</table>
</form>
</body>
</html>

 

 

 


 

(labJoinServlet.java)

package com.hy;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LabJoinServlet
 */
@WebServlet("/LabJoinServlet")
public class LabJoinServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LabJoinServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 0. 클라이언트가 전송한 요청 데이터 인코딩 방식을 utf-8로 지정하기
		request.setCharacterEncoding("utf-8");
		// 클라이언트가 전송할 응답 데이터 인코딩 방식 utf-8로 지정
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");

		//response.getWriter().append("Served at: ").append(request.getContextPath());
		
		PrintWriter out = response.getWriter();

		String id = request.getParameter("id");
		String ps = request.getParameter("ps");
		String ps2 = request.getParameter("ps2");
		String gender = request.getParameter("gender");
		String[] sport = request.getParameterValues("sport");
		String blood = request.getParameter("blood");
		String birth = request.getParameter("birth");
		String color = request.getParameter("color");
		String comment = request.getParameter("comment");
		
		out.print("아이디: " + id);
		out.print("<br>비밀번호: " + ps);
		if(ps.equals(ps2)) {
			out.print("<br>비밀번호가 일치합니다: " + ps2);
		}else {
			out.print("<br>비밀번호가 일치하지 않습니다: " + ps2);
		}
		out.print("<br>성별: " + gender);
		out.print("<br>취미: ");
		for(int i = 0; i < sport.length; i++) {
			out.print(sport[i]+" ");
		}
		out.print("<br>혈액형: " + blood);
		out.print("<br>생일: " + birth);
		out.print("<br>좋아하는 색: " + color);
		out.print("<br>남기고 싶은 말: " + comment);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

 

--> 회원가입폼에서 입력받은 데이터를 받아와서 처리한 후, 화면에 출력하는 예제

 

(LabJoin.html)

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
<style>
	body{
		text-align:center;
	}

	div > h3{
		background-color: rgb(180, 180, 180);
	}
</style>
</head>
<body>
<div><h3>Step1: 아이디/비번 입력</h1></div>
<form action="LabJoinServlet" method="post">
아이디&nbsp;
<input type="text" name="id" placeholder="아이디 입력" required><br><br>
비밀번호&nbsp;
<input type="password" name="ps" required><br><br>
비밀번호 확인&nbsp;
<input type="password" name="ps2" required><br><br>
<div><h3>Step2: 개인정보</h1></div>
성별&nbsp;
<input type="radio" name="gender" value="woman">여성
<input type="radio" name="gender" value="male">남성<br><br>
혈액형&nbsp;
<select name="blood">
<option value="A">A</option>
<option value="B">B</option>
<option value="O">C</option>
<option value="AB">D</option>
</select><br><br>
생일
<input type="date" name="birth"><br><br>
<div><h3>Step3: 선호도</h1></div>
취미
<input type="checkbox" name="sport" value="football">축구
<input type="checkbox" name="sport" value="basketball">농구
<input type="checkbox" name="sport" value="baseball">야구 <br><br>

좋아하는 색깔
<input type="color" name="color"><br><br>
<div><h3>Step4: 적고싶은말</h1></div>
<textarea name="comment" rows="10" cols="50" placeholder="Add your comment">
</textarea><br><br>

<input type="submit" value="제출">
<input type="reset" value="초기화">

</form>
</body>
</html>

 

 

 

 


 

(Lab1Servlet.java)

package com.smart;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SignupServlet
 */
@WebServlet("/Lab1Servlet")
public class Lab1Servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 1. request 객체 데이터 인코딩 방식 지정
		request.setCharacterEncoding("utf-8");
		// 2. 클라이언트에게 전송할 페이지 양식 지정
		response.setCharacterEncoding("utf-8");
		// 3. 클라이언트에게 전송한 데이터 인코딩 방식 지정
		response.setContentType("text/html; charset=utf-8");
		// 4. 클라이언트가 보내온 데이터 받기
		String name = request.getParameter("name");
		int age = Integer.parseInt(request.getParameter("age"));
		String food = request.getParameter("food");
		String gender = request.getParameter("gender");
		String[] hobbies = request.getParameterValues("hobby");

		// 5. 클라이언트에게 데이터 확인을 위한 피드백
		// PrintWriter 객체를 생성 -> out 레퍼런스 변수로 지정
		PrintWriter out = response.getWriter();
		// out 객체를 이용하여 HTML 페이지 생성하기
		out.print("<html><body>");
		out.print("<p><b>이름: " + name + "</b></p>");
		out.print("<p><b>나이: " + age + "</b></p>");
		String ageRange = null;
		if(age >= 10 && age < 20) {
		    ageRange = "10대";
		}
		else if (age >= 20 && age < 30) {
		    ageRange = "20대";
		} else if (age >= 30 && age < 40) {
		    ageRange = "30대";
		} else if (age >= 40 && age < 50) {
		    ageRange = "40대";
		}
		else if (age >= 50 && age < 60) {
		    ageRange = "50대";
		}
		else if (age >= 60 && age < 70) {
		    ageRange = "60대";
		}
		else if (age >= 70 && age < 80) {
		    ageRange = "70대";
		}
		out.print("<p><b>나이대: " + ageRange + "</b></p>");
		out.print("<p><b>좋아하는 음식: " + food + "</b></p>");
		out.print("<p><b>성별: " + gender + "</b></p>");
		out.print("<p><b>관심분야: ");
		for(int i = 0; i < hobbies.length; i++) {
			out.print(hobbies[i] + "<br>");
		}
		out.print("</body></html>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

 

ageRange를 case문으로 변경한 코드

String ageRange = null;
switch (age / 10 * 10) {
    case 10:
        ageRange = "10대";
        break;
    case 20:
        ageRange = "20대";
        break;
    case 30:
        ageRange = "30대";
        break;
    case 40:
        ageRange = "40대";
        break;
    case 50:
        ageRange = "50대";
        break;
    case 60:
        ageRange = "60대";
        break;
    case 70:
        ageRange = "70대";
        break;
    case 80:
        ageRange = "80대";
        break;
}

out.print("<p><b>나이대: " + ageRange + "</b></p>");

 

 

lab1.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="Lab1Servlet" method="post">
<table align=center>
<tr><td colspan=2 align=center height=40><b>회원가입</b><td></tr>
<tr>
<td align=right>이름&nbsp;</td>
<td><input type="text" name="name" placeholder="이름 입력"></td>
</tr>
<tr>
<td align=right>나이&nbsp;</td>
<td><input type="number" name="age" placeholder="나이 입력"></td>
</tr>
<tr>
<td align=right>좋아하는 음식&nbsp;</td>
<td>
<select name="food">
<option value="김치째개">김치찌개</option>
<option value="케이크">케이크</option>
<option value="불고기">불고기</option>
<option value="비빔밥">비빔밥</option>
<option value="none">없음</option>
</td>
</tr>
<tr>
<td align=right>성별&nbsp;</td>
<td><input type="radio" name="gender" value="여성" checked>여성
<input type="radio" name="gender" value="남성">남성</td>
</tr>
<tr>
<td align=right>관심분야</td>
<td>
<input type="checkbox" name="hobby" value="웹프로그램">웹프로그램
<input type="checkbox" name="hobby" value="네트워크관리">네트워크관리
<input type="checkbox" name="hobby" value="보안">보안
<input type="checkbox" name="hobby" value="게임프로그램">게임프로그램
<input type="checkbox" name="hobby" value="데이터분석">데이터분석
</td>
</tr>
<tr>
<td colspan=2 align=center height=50>
<input type="submit" value="회원가입">
</td>
</tr>
</table>
</form>
</body>
</html>

 

 


 

(SignupServlet.java)

package com.smart;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SignupServlet
 */
@WebServlet("/SignupServlet")
public class SignupServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 1. request 객체 데이터 인코딩 방식 지정
		request.setCharacterEncoding("utf-8");
		// 2. 클라이언트에게 전송할 페이지 양식 지정
		response.setCharacterEncoding("utf-8");
		// 3. 클라이언트에게 전송한 데이터 인코딩 방식 지정
		response.setContentType("text/html; charset=utf-8");
		// 4. 클라이언트가 보내온 데이터 받기
		String id = request.getParameter("id");
		String ps1 = request.getParameter("ps1");
		String ps2 = request.getParameter("ps2");
		String name = request.getParameter("name");
		String job = request.getParameter("job");
		String gender = request.getParameter("gender");
		String[] hobbies = request.getParameterValues("hobby");

		// 5. 클라이언트에게 데이터 확인을 위한 피드백
		// PrintWriter 객체를 생성 -> out 레퍼런스 변수로 지정
		PrintWriter out = response.getWriter();
		// out 객체를 이용하여 HTML 페이지 생성하기
		out.print("<html><body>");
		out.print("<p><b>User ID: " + id + "</b></p>");
		out.print("<p><b>User Password: " + ps1 + "</b></p>");
		out.print("<p><b>User name: " + name + "</b></p>");
		out.print("<p><b>직업: " + job + "</b></p>");
		out.print("<p><b>성별: " + gender + "</b></p>");
		out.print("<p><b>취미: </b></p>");
		for(int i = 0; i < hobbies.length; i++) {
			out.print(hobbies[i] + "<br>");
		}
		out.print("</body></html>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

 

 

signup.html

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<form action="SignupServlet" method="post">
<table align=center>
<tr><td colspan=2 align=center height=40><b>회원가입</b><td></tr>
<tr>
<td align=right>이름&nbsp;</td>
<td><input type="text" name="name" placeholder="이름 입력"></td>
</tr>
<tr>
<td align=right>아이디&nbsp;</td>
<td><input type="text" name="id" placeholder="아이디 입력"></td>
</tr>
<tr>
<td align=right>패스워드&nbsp;</td>
<td><input type="password" name="ps1"></td>
</tr>
<tr>
<td align=right>패스워드 확인&nbsp;</td>
<td><input type="password" name="ps2"></td>
</tr>
<tr>
<td align=right>직업&nbsp;</td>
<td>
<select name="job">
<option value="free">프리랜서</option>
<option value="student">학생</option>
<option value="programmer">개발자</option>
<option value="professor">교수</option>
<option value="none">없음</option>
</td>
</tr>
<tr>
<td align=right>성별&nbsp;</td>
<td><input type="radio" name="gender" value="woman" checked>여성
<input type="radio" name="gender" value="male">남성</td>
</tr>
<tr>
<td align=right>취미</td>
<td>
<input type="checkbox" name="hobby" value="football">축구
<input type="checkbox" name="hobby" value="basketball">농구
<input type="checkbox" name="hobby" value="baseball">야구 
<input type="checkbox" name="hobby" value="piano">피아노
</td>
</tr>
<tr>
<td colspan=2 align=center height=50>
<input type="submit" value="회원가입">
</td>
</tr>
</table>
</form>
</body>
</html>

 

 

 


 

 

 

'학교 > JAVA' 카테고리의 다른 글

자바빈(JavaBean)  (0) 2023.12.17
06) JSP 예제  (0) 2023.12.17
07) 내장 객체 예제  (0) 2023.12.15
05) 서블릿  (0) 2023.12.14
06) JSP  (0) 2023.12.14