카테고리 없음

자바 풀 스택 1/3 오후 기록 030-2

파티피플지선 2025. 1. 3. 17:35

<14:30 5교시>
실습 시간을 줬을 땐 실습을 해라, 라고 혼(?)났다
 
 
확장 for 문 또 틀렸음 ㅠㅠ
for(tmp의데이터 타입  tmp :  ArrayList객체)

package test.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

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

@WebServlet("/friends")
public class FriendsServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//DB에서 읽어온 친구 목록이라고 가정하자
		List<String> names=new ArrayList<>();
		names.add("친구1");
		names.add("친구2");
		names.add("친구3");
		
		//names 객체에 들어있는 친구 목록을 ul, li 요소를 이용해서 출력해보자.
		
		//응답 인코딩 설정
		response.setCharacterEncoding("utf-8");
		//응답 컨텐트 설정
		response.setContentType("text/html; charset=utf-8");
		//html 형식의 utf-8을 응답해줄게, 라고 알려주는 정석적인 형식

		//요청한 클라이언트에게 문자열을 출력할 수 있는 객체
		PrintWriter pw = response.getWriter();
		pw.println("<!doctype html>");
		pw.println("<html>");
		pw.println("<head>");
		pw.println("<meta charset='utf-8'>");
		pw.println("<title></title>");
		pw.println("</head>");
		pw.println("<body>");
		pw.println("<h1>친구목록</h1>");
		pw.println("<ul>");
		pw.println("<li>"+names.get(0)+"</li>");
		pw.println("<li>"+names.get(1)+"</li>");
		pw.println("<li>"+names.get(2)+"</li>");
		pw.println("</ul>");
		pw.println("<h1>친구목록2</h1>");
		pw.println("<ul>");
		for (int i=0; i<names.size(); i++) {
			pw.println("<li>"+names.get(i)+"</li>");
		}
		pw.println("</ul>");
		pw.println("<h1>친구목록3</h1>");
		pw.println("<ul>");
		for (String tmp : names) {
			pw.println("<li>"+tmp+"</li>");
		}
		pw.println("</ul>");
		
		
		pw.println("</body>");
		pw.println("</html>");
		pw.close();
		
		
		
		
	}
}

 

package test.servlet;

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

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import test.dto.MemberDto;

@WebServlet("/member")
public class MemberServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//DB에서 읽어온 회원정보라고 가정하기
		MemberDto dto = new MemberDto(1,"이름2","주소2");
		
		//응답 인코딩 설정
		response.setCharacterEncoding("utf-8");
		//응답 컨텐트 설정
		response.setContentType("text/html; charset=utf-8");
		//html 형식의 utf-8을 응답해줄게, 라고 알려주는 정석적인 형식

		//요청한 클라이언트에게 문자열을 출력할 수 있는 객체
		PrintWriter pw = response.getWriter();
		pw.println("<!doctype html>");
		pw.println("<html>");
		pw.println("<head>");
		pw.println("<meta charset='utf-8'>");
		pw.println("<title></title>");
		pw.println("</head>");
		pw.println("<body>");
		pw.println("<p> 번호 : <strong>"+dto.getNum()+"</strong></p1>");
		pw.println("<p> 이름 : <strong>"+dto.getName()+"</strong></p1>");
		pw.println("<p> 주소 : <strong>"+dto.getAddr()+"</strong></p1>");
		pw.println("</body>");
		pw.println("</html>");
		pw.close();
				
				
	
	}
}

 
 
 
 
<15:30 6교시>
 

 

package test.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import test.dto.MemberDto;

@WebServlet("/member/list")
public class MemberListServlet extends HttpServlet{
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<MemberDto> list = new ArrayList<>();
		list.add(new MemberDto(1,"이름1","주소1"));
		list.add(new MemberDto(2,"이름2","주소2"));
		list.add(new MemberDto(3,"이름3","주소3"));
		
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		PrintWriter pw = response.getWriter();
		pw.println("<!doctype html>");
		pw.println("<html>");
		pw.println("<head>");
		pw.println("<meta charset='utf-8'>");
		pw.println("<title></title>");
		pw.println("</head>");
		pw.println("<body>");
		pw.println("<table>");
		pw.println("<tr><th>번호</th><th>이름</th><th>주소</th></tr>");
		for (MemberDto tmp:list) {
			pw.println("<tr><td>"+tmp.getNum()+"</td><td>"+tmp.getName()+"</td><td>"+tmp.getAddr()+"</td></tr>");
		}
		pw.println("</table>");
		pw.println("</body>");
		pw.println("</html>");
		pw.close();
	}
}

 
 
 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>index.html</title>
</head>
<body>
	<div class="container">
		<h1>인덱스 페이지</h1>
		<ul>
			<li><a href="fortune">오늘의 운세</a></li>
			<li><a href="friends">친구목록</a></li>
			<li><a href="member">회원의 정보 보기</a></li>
			<li><a href="member/list">회원목록보기</a></li>
		</ul>
		
		<form action="send" method="get">
			<input type="text" name="msg" placeholder="할말 입력..."/>
			<button type="submit">전송</button>
		</form>
	</div>
</body>
</html>

 

package test.servlet;

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

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

/*
 * 클라이언트는 msg라는 파라미터명으로 문자열을 전송한 상황이다.
 * 이 서블릿에서는 그 파라미터를 추출해서 콘솔에 출력하는 테스트를 해보고자 한다
 * 요청 파라미터 추출은 HttpServletRequest 객체를 이용해서 추출하면 된다.
 */


@WebServlet("/send")
public class SendServlet extends HttpServlet{
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String msg= request.getParameter("msg");
		System.out.println("폼 전송된 내용: "+msg);
		//간단 응답
		PrintWriter pw=response.getWriter();
		pw.println("/send okay~");
		pw.close();
	}
}

 
 
 
<16:30 7교시>

 
 

 
preference 가서 emmet 에 jsp 추가해주기
 
서블릿 : 클라이언트의 요청에 응답할 수 있는 객체
 
jsp 또한 특별한 서블릿이기 때문에 html 같긴 하지만 자바 코드를 쓸 수도 있음
 

jsp에서 기본적으로 출력할 수 있는 기본 참조값들의 모음. 
 

 

 


 
 
jsp를 servlet으로 바꿔주는 코드 받음

더보기
/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/10.1.34
 * Generated at: 2025-01-03 08:15:41 UTC
 * Note: The last modified time of this file was set to
 *       the last modified time of the source file after
 *       generation to assist with modification tracking.
 */
package org.apache.jsp;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.jsp.*;

public final class send_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent,
                 org.apache.jasper.runtime.JspSourceImports,
                 org.apache.jasper.runtime.JspSourceDirectives {

  private static final jakarta.servlet.jsp.JspFactory _jspxFactory =
          jakarta.servlet.jsp.JspFactory.getDefaultFactory();

  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;

  private static final java.util.Set<java.lang.String> _jspx_imports_packages;

  private static final java.util.Set<java.lang.String> _jspx_imports_classes;

  static {
    _jspx_imports_packages = new java.util.LinkedHashSet<>(4);
    _jspx_imports_packages.add("jakarta.servlet");
    _jspx_imports_packages.add("jakarta.servlet.http");
    _jspx_imports_packages.add("jakarta.servlet.jsp");
    _jspx_imports_classes = null;
  }

  private volatile jakarta.el.ExpressionFactory _el_expressionfactory;
  private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager;

  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
    return _jspx_dependants;
  }

  public java.util.Set<java.lang.String> getPackageImports() {
    return _jspx_imports_packages;
  }

  public java.util.Set<java.lang.String> getClassImports() {
    return _jspx_imports_classes;
  }

  public boolean getErrorOnELNotFound() {
    return false;
  }

  public jakarta.el.ExpressionFactory _jsp_getExpressionFactory() {
    if (_el_expressionfactory == null) {
      synchronized (this) {
        if (_el_expressionfactory == null) {
          _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
        }
      }
    }
    return _el_expressionfactory;
  }

  public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() {
    if (_jsp_instancemanager == null) {
      synchronized (this) {
        if (_jsp_instancemanager == null) {
          _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
        }
      }
    }
    return _jsp_instancemanager;
  }

  public void _jspInit() {
  }

  public void _jspDestroy() {
  }

  public void _jspService(final jakarta.servlet.http.HttpServletRequest request, final jakarta.servlet.http.HttpServletResponse response)
      throws java.io.IOException, jakarta.servlet.ServletException {

    if (!jakarta.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) {
      final java.lang.String _jspx_method = request.getMethod();
      if ("OPTIONS".equals(_jspx_method)) {
        response.setHeader("Allow","GET, HEAD, POST, OPTIONS");
        return;
      }
      if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method)) {
        response.setHeader("Allow","GET, HEAD, POST, OPTIONS");
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSP들은 오직 GET, POST 또는 HEAD 메소드만을 허용합니다. Jasper는 OPTIONS 메소드 또한 허용합니다.");
        return;
      }
    }

    final jakarta.servlet.jsp.PageContext pageContext;
    jakarta.servlet.http.HttpSession session = null;
    final jakarta.servlet.ServletContext application;
    final jakarta.servlet.ServletConfig config;
    jakarta.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    jakarta.servlet.jsp.JspWriter _jspx_out = null;
    jakarta.servlet.jsp.PageContext _jspx_page_context = null;


    try {
      response.setContentType("text/html; charset=UTF-8");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write('\r');
      out.write('\n');

	String fortuneToday="서쪽으로 가면 강남역을 만나요!";
	//요청 파라미터 추출
	String msg=request.getParameter("msg");
	//콘솔에 출력 
	System.out.println(msg);

      out.write("\r\n");
      out.write("<!DOCTYPE html>\r\n");
      out.write("<html>\r\n");
      out.write("<head>\r\n");
      out.write("<meta charset=\"UTF-8\">\r\n");
      out.write("<title>/send.jsp</title>\r\n");
      out.write("</head>\r\n");
      out.write("<body>\r\n");
      out.write(" 	<h1>나는 jsp 페이지</h1>\r\n");
      out.write(" 	<p> 오늘의 운세 : <strong>");
out.print(fortuneToday); 
      out.write("</strong></p>\r\n");
      out.write(" 	<p> 오늘의 운세 : <strong>");
      out.print(fortuneToday );
      out.write("</strong></p>\r\n");
      out.write("</body>\r\n");
      out.write("</html>");
    } catch (java.lang.Throwable t) {
      if (!(t instanceof jakarta.servlet.jsp.SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try {
            if (response.isCommitted()) {
              out.flush();
            } else {
              out.clearBuffer();
            }
          } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}

 
 
<17:30 8교시> 
남은 시간 연습하기