Dev log - 59, Java #13, Servlet #3

박강산·2022년 6월 29일
0
post-thumbnail

Java Servlet

인터페이스와 라이프사이클

  • init() / service() / destroy() / getServletConfig()
  1. 요청에 의해 특정 서블릿 호출
  2. 해당 서블릿 생성 및 로드
  3. init() 메소드 호출 (최초 1회 호출)
  4. service() 메소드 호출
  5. destroy() 메소드 호출

이미지 출처 : https://mangkyu.tistory.com/14

Servlet 라이프사이클 실습

  • init() 메소드는 처음 한번만 실행, 공통적으로 사용해야하는 것이 있다면 오버라이딩하여 구현됨

  • 실행 중 서블릿이 변경될 경우, 기존 서블릿을 파괴(destroy() 메소드)하고 init()을 통해 새로운 내용을 다시 불러옴

public class LifecycleTestServlet extends HttpServlet {
	private static final long serialVersionUID = -847099311093228759L;

	public void init(ServletConfig config) throws ServletException {
		System.out.println("init() method called.");
	}

	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("service() method called.");
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<html><head><title>" + "LifecycleTestServlet" + "</title></head><body>");
		out.println("<h3>Servlet Lifecycle Test</h3>");
		out.println("</body></html>");
		out.close();
	}

	public void destroy() {
		System.out.println("destroy() method called");
	}
}

ServletConfig 실습

  • <init-param> 태그 안에 <param-name>,<param-value>
    ServletConfig 를 이용해 불러올 값을 지정해줌
	<servlet>
		<servlet-name>ServletConfigTestServlet</servlet-name>
		<servlet-class>com.varxyz.jv300.mod003.ServletConfigTestServlet</servlet-class>
		<init-param>
			<param-name>season-list</param-name>
			<param-value>Spring, Summer, Fall, Winter</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>ServletConfigTestServlet</servlet-name>
		<url-pattern>/config.view</url-pattern>
	</servlet-mapping>
  • config.getInitParameter로 web.xml의 <param-name> 을 불러와서 <param-value> 값을 불러옴
  • if문을 이용해 <param-value> 값이 없다면 DEFAULT_SEASONS 값을 이용
public class ServletConfigTestServlet extends HttpServlet {
	private static final String DEFAULT_SEASONS = "Spring, Summer, Fall, Winter";
	private String[] seasons;

	public void init(ServletConfig config) throws ServletException {
		String season_list = config.getInitParameter("season-list"); 
		if (season_list == null) {  
			season_list = DEFAULT_SEASONS;
		}
		seasons = season_list.split(", ");
	}

	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<html><head><title>" + "ServletConfigTestServlet" + "</title></head><body>");
		out.println("<h3>ServletConfig Test123</h3>");
		out.println("<ul>");
		for (String season : seasons) {
			out.println("<li>" + season + "</li>");
		}
		out.println("</ul>");
		out.println("</body></html>");
		out.close();
	}
}

Java Servlet 구조

  • 이클립스에서 보이는 구조와 실제 구조는 다름

Java Web 실습 (<form> 태그 활용)

이클립스 html 문서 생성

  • src -> main -> webapp -> 프로젝트명 -> html 문서 생성

  • action 속성은, 폼의 입력 값들을 전송하는(받는) 측의 URL을 설정

  • method 속성은, 데이터 방식을 GET으로 보낼 지, POST로 보낼 지 설정(기본은 GET)

이클립스 Servlet 생성

  • 프로젝트 오른쪽 클릭 -> New -> Servlet으로 생성

  • 하나를 눌러서 Edit으로 변경

  • Constructors 해제 후, Finish

@WebServlet("/mod004/hello.do") // 이 코드로 html 문서와 연결
public class FormBasedHelloServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static final String DEFAULT_NAME = "World";

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String name = request.getParameter("userName");
		if (name == null || name.length() == 0) {
			name = DEFAULT_NAME;
		}

		String pageTitle = "Hello World";
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<head><title>" + pageTitle + "</title></head>");
		out.println("<body>");
		out.println("<h3>" + name + "</h3>");
		out.println("</body></html>");
		out.close();
	}

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

회원가입 form 실습

  • 회원가입 폼(add_user.html)
    회원 아이디 : userId
    비밀번호 : passwd
    이름 : userName
    주민번호 : ssn (앞의 6자리만)
    이메일1 : email1(아이디)
    이메일2 : email2(메일도메인 ex: naver.com, gmail.com...)
    관심분야 : concerns(체크박스 : 다중 선택가능, ex: Java, Servlet/JSP, EJB, Android, Spring...)

회원가입 서블릿(AddUserServlet.java)
: 회원이 등록한 정보를 받아 회원가입에서 입력한 정보를 출력

회원가입 폼 작성 시, 스크립트나 css 사용가능
체크박스처럼 하나 이상의 값이 전달되는 경우 서블릿에서 파라메터 정보 받는 법
String[] concerns = request.getParameterValues("concerns");

  • HTML 문서
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 
	<url-pattern>/mod004/hello.do</url-pattern>
 -->
	<form action="add_user.do" method="get">
		<p>회원 아이디 : <input type="text" name="userId"> </p>
		<p>비밀번호 : <input type="password" name="passwd"></p>
		<p>이름 : <input type="text" name="userName"></p>
		<p>주민번호 : <input type="text" name="ssn" maxlength="6" placeholder="앞 6자리"></p>
		<p>이메일1 : <input type="text" name="email1"placeholder="아이디"></p>
		<p>이메일2 : <input type="text" name="email2" placeholder="메일도메인 ex) naver.com"></p>
		<p>관심분야 : <label><input type="checkbox" name="concerns" value="java">Java</label>
      <label><input type="checkbox" name="concerns" value="servlet/jsp">Servlet/JSP</label>
      <label><input type="checkbox" name="concerns" value="ejb">EJB</label>
      <label><input type="checkbox" name="concerns" value="android">Android</label>
      <p>
  	    <input type="submit" value="확인">
    	  <input type="reset" value="리셋">
      </p>
	</form>
</body>
</html>
  • Servlet 문서
@WebServlet("/mod004/add_user.do")
public class AddUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static final String DEFAULT_USERID = "홍길동";
	public static final String DEFAULT_PASSWD = "hong1234";
	public static final String DEFAULT_USERNAME = "허균";
	public static final String DEFAULT_SSN = "691103";
	public static final String DEFAULT_EMAIL1 = "홍길동123";
	public static final String DEFAULT_EMAIL2 = "naver.com";
	public static final String[] DEFAULT_CONCERNS = new String[0];

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String userId = request.getParameter("userId");
		if (userId == null || userId.length() == 0) {
			userId = DEFAULT_USERID;
		}
		String passwd = request.getParameter("passwd");
		if (passwd == null || passwd.length() == 0) {
			passwd = DEFAULT_PASSWD;
		}
		String userName = request.getParameter("userName");
		if (userName == null || userName.length() == 0) {
			userName = DEFAULT_USERNAME;
		}
		String ssn = request.getParameter("ssn");
		if (ssn == null || ssn.length() == 0) {
			ssn = DEFAULT_SSN;
		}
		String email1 = request.getParameter("email1");
		if (email1 == null || email1.length() == 0) {
			email1 = DEFAULT_EMAIL1;
		}
		String email2 = request.getParameter("email2");
		if (email2 == null || email2.length() == 0) {
			email2 = DEFAULT_EMAIL2;
		}
		String[] concerns = request.getParameterValues("concerns");
		if (concerns == null || concerns.length == 0) {
			concerns = DEFAULT_CONCERNS;
		}

		String pageTitle = "회원가입 폼";
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<head><title>" + pageTitle + "</title></head>");
		out.println("<body>");
		out.println("<h2>" + "회원가입 승인서" + "</h3>");
		out.println("<h3>" + "회원아이디 : " + userId + "</h3>");
		out.println("<h3>" + "비밀번호 : " + passwd + "</h3>");
		out.println("<h3>" + "이름 : " + userName + "</h3>");
		out.println("<h3>" + "주민번호 : " + ssn + "</h3>");
		out.println("<h3>" + "이메일 : " + email1 + "@" + email2 + "</h3>");
		out.println("<h3> 관심분야 : ");
		for (int j = 0; j < concerns.length; j++) {
			out.println("[ " + concerns[j] + " ] ");
		}
		out.println("</h3>");
		out.println("</body></html>");
		out.close();
	}

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

profile
안녕하세요. 맡은 업무를 확실하게 수행하는 웹 개발자가 되기 위하여 끊임없이 학습에 정진하겠습니다.

0개의 댓글

관련 채용 정보