20220405 복습

2022 - 0405 - 복습

서블릿 기초

Servlet이 컨트롤러 역할을 한다.
URL Mappings에서 서블릿 이름 수정 가능.
(보통 서블릿의 이름을 노출시키지 않는다)

doGet() - ProductListServlet.java (URL매핑 : productList.do)

response.setContentType("text/html;charset=UTF-8");
response.getWriter().append("Served at: ").append(request.getContextPath());

[싱글톤]
ProductDAO pDao = ProductDAO.getInstance();

[연가보 (연결 > 가져오기 > 보내기)]
List<ProductVO>productList = pDao.selectAllProduct();
request.setAttribute("productList", productList);

[페이지 이동]
RequestDispatcher rd = request.getRequestDispatcher("product/productList.jsp");
rd.forward(request,response);

doPost() - ProductWriteServlet.java (URL매핑 : productWrite.do)

//doGet(request, response);
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.println("post 전송");

//업로드 코드
ServletContext context = getServletContext();
String path = context.getRealPath("img"); //Context로 서블릿이 이미지 실제 경로를 찾게 해줌.
String encType="UTF-8";
int sizeLimit=20*1024*1024; //20MB

MultipartRequest multi = new MultipartRequest(request, path, sizeLimit, encType, new DefaultFileRenamePolicy());

String productId = multi.getParameter("produtId");
String pname = multi.getParameter("pname");
int unitPrice = Integer.parseInt(multi.getParameter("unitPrice"));
String description = multi.getParameter("description");
String manufacturer = multi.getParameter("manufacturer");
String category = multi.getParameter("category");
int unitInStock = Integer.parseInt(multi.getParameter("unitInStock"));
String conditions = multi.getParameter("conditions");
String upfile = multi.getFilesystemName("upfile");

//VO 객체
ProductVO pVO = new ProductVO();
pVO.setProductId(productId);
pVO.setPname(pname);
pVO.setUnitPrice(unitPrice);
pVO.setDescription(description);
pVO.setManufacturer(manufacturer);
pVO.setCategory(category);
pVO.setUnitInStock(unitInStock);
pVO.setConditions(conditions);
pVO.setUpfile(upfile);

     ProductDAO pDao=ProductDAO.getInstance();
     if( pDao.insertProduct() ) {
          System.out.println("등록 성공");
          //response.sendRedirect("productList.do");
     }else {
          System.out.println("등록 실패");
     }


인코딩 & out

PrintWriter out = response.getWriter();
out.println("jsp와 달리 객체를 생성해서 사용해야함.");

response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");

JSTL(Jsp Standard Tag Library)

main -> webapp -> WEB-INF -> lib 폴더 안에
cos.jar / jstl.jar / standard.jar 넣어주기

     <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
     <c:forEach var="product" items="${productList}">
     ${product.idx }
     </c:forEach>
(for반복문을 태그로 사용. 향상된 for문 X )

+ 코드

<a href="/DWP_0405_03/productWrite.do">상품 등록</a> --- 링크
<img src=./img/ style="width:100px;height:100px;"></img> --- 이미지
<form method="post" name="myform" enctype="multipart/form-data"> --- 업로드 폼
</form>
<label for="formGroupExampleInput" class="form-label">상품번호</label> --- LABEL
<input type="text" class="form-control" id="productId" name="productId"> --- input TEXT
<button class="btn btn-success" type="submit" onclick="return productCheck()">등록</button> --- 버튼(유효성)
<button class="btn btn-danger" type="reset" >리셋</button> --- 버튼(리셋)
<button class="btn btn-dark" type="button" onclick="location.href='productList.do'">목록</button> --- 버튼(링크)


패키지 클래스


com.jslhrd.minishop.controller
(ctl.jsp역할의 컨트롤러)
ProductListServlet.java
ProductWriteServlet.java
ProductUpdateServlet.java
ProductDeleteServlet.java
com.jslhrd.minishop.DAO (조회,추가,갱신,삭제 등)
ProductDAO.java
com.jslhrd.minishop.DTO (상품 정보 저장)
ProductVO.java
util (DB연결/ 연결해제)
DBManager.java

Webapp / product
productList.jsp
productWrite.jsp
productUpdate.jsp
productDelete.jsp
Webapp / script
Webapp / css
product.js
shopping.css

DBManager 코드


static Connection conn = null;
static PreparedStatement pstmt = null;
static String jdbc_driver="com.mysql.cj.jdbc.Driver";
static String jdbc_url="jdbc:mysql://localhost:3306/db53";
static String id="root";
static String pw="123456";

     public static Connection connect() {
          try {
               Class.forName(jdbc_driver);
               conn = DriverManager.getConnection(jdbc_url,id,pw);
          }catch(ClassNotFoundException e){

          }catch(SQLException e) {

          }
          return conn;
     }

     public static void disconnect() {
          if(pstmt != null) {
               try {
                    pstmt.close();
               } catch (SQLException e) {
                    e.printStackTrace();
               }
          }
          if(conn != null) {
               try {
                    conn.close();
               } catch (SQLException e) {
                    e.printStackTrace();
               }
          }
     }