implements Servlet를 하면 여러가지 method가 나온다
service, init, destory ... 여러가지가 있는데 가장 필요한것은 service
따라서, extends GenericServlet라는 추상클래스를 상속하면 우리가 필요한 service만 override가능
그래서 서버의 역할 Data get, logic, response 3가지의 역할을 service에서 하려고하는데
근데 문제가 생김!!!
GET방식은 url?key=value&key=value ... 이런식으로 가는데
한글이 데이터로 넘어갈경우 브라우저 url에선 한글 그대로 보이지만 실제 넘어갈때는
https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=1&ie=utf8&query=%EB%84%A4%EC%9D%B4%EB%B2%84
query 뒷부분처럼 인코딩이 되어서 넘어가게됨(저부분 한글로는 네이버임)
그러면 서버에서 처리할때는 인코딩 되있는걸 다시 디코딩 해야 처리를 할 수 있는데 GET, POST의 디코딩 방식이 다름
GET, POST에 따라서 로직을 다르게 해야되는데 이게 너무 힘들고 너무 낭비임
따라서, 최종적으로 Servlet, GenericServlet을 상속하는게 아닌 extends HttpServlet를 받아서 사용하면 내부적으로 GET, POST, PUT, DELETE를 받을 때 알아서 처리해줌
그래서 NEW -> Servlet으로 만들면 HttpServlet을 상속받고 주요 메소드를 오버라이드한 클래스가 만들어진다
더보기
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;
@WebServlet("/hello")
public class hello extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/* 1. Data get
*
* 2. logic
*
* servlet의 4가지 기능은 어떻게 수행될까?
* servlet도 하나의 클래스이기 때문에
* 생성자 -> init() -> service()(doGet, doPost...) -> destory()
* 클라이언트가 접속할때 마다 service()저 부분이 계속 실행되는 것이고 새로운 thread가 만들어지는데 이부분은 WAS가 알아서 관리하는 것
* 즉, init()은 한번만 생성
*
* destory()는 서버가 끝나기전에 한번만 호출
*
* */
// 3. response page => html
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html lang=\"ko\">");
out.println(" <head>");
out.println(" <meta charset=\"UTF-8\" />");
out.println(" <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />");
out.println(" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />");
out.println(" <link");
out.println(" href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css\"");
out.println(" rel=\"stylesheet\"");
out.println(" integrity=\"sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3\"");
out.println(" crossorigin=\"anonymous\"");
out.println(" />");
out.println(" <link href=\"/board1_servlet/assets/css/app.css\" rel=\"stylesheet\" />");
out.println(" <title>SSAFY</title>");
out.println(" </head>");
out.println(" <body>");
out.println(" <div class=\"container\">");
out.println(" <div class=\"row justify-content-center\">");
out.println(" <div class=\"col-lg-8 col-md-10 col-sm-12\">");
out.println(" <h2 class=\"my-3 py-3 shadow-sm bg-light text-center\">");
out.println(" <mark class=\"sky\">글목록</mark>");
out.println(" </h2>");
out.println(" </div>");
out.println(" <div class=\"col-lg-8 col-md-10 col-sm-12\">");
out.println(" <div class=\"row align-self-center mb-2\">");
out.println(" <div class=\"col-md-2 text-start\">");
out.println(" <button type=\"button\" id=\"btn-mv-register\" class=\"btn btn-outline-primary btn-sm\">글쓰기</button>");
out.println(" </div>");
out.println(" <div class=\"col-md-7 offset-3\">");
out.println(" <form class=\"d-flex\">");
out.println(" <select id=\"key\" class=\"form-select form-select-sm ms-5 me-1 w-50\" aria-label=\"검색조건\">");
out.println(" <option selected>검색조건</option>");
out.println(" <option value=\"articleno\">글번호</option>");
out.println(" <option value=\"subject\">제목</option>");
out.println(" <option value=\"userid\">작성자</option>");
out.println(" </select>");
out.println(" <div class=\"input-group input-group-sm\">");
out.println(" <input type=\"text\" class=\"form-control\" placeholder=\"검색어...\" />");
out.println(" <button class=\"btn btn-dark\" type=\"button\">검색</button>");
out.println(" </div>");
out.println(" </form>");
out.println(" </div>");
out.println(" </div>");
out.println(" <table class=\"table table-hover\">");
out.println(" <thead>");
out.println(" <tr class=\"text-center\">");
out.println(" <th scope=\"col\">글번호</th>");
out.println(" <th scope=\"col\">제목</th>");
out.println(" <th scope=\"col\">작성자</th>");
out.println(" <th scope=\"col\">조회수</th>");
out.println(" <th scope=\"col\">작성일</th>");
out.println(" </tr>");
out.println(" </thead>");
out.println(" <tbody>");
}
}
Servlet을 이용한 Dynamic Web Page Example (JDBC 이용)
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/register")
public class ArticleRegister extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String userid = request.getParameter("userid");
String subject = request.getParameter("subject");
String content = request.getParameter("content");
Connection conn = null;
PreparedStatement pstmt = null;
int cnt = 0;
try {
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ssafyweb?serverTimezone=UTC", "root", "1234");
StringBuilder sql = new StringBuilder();
sql.append("insert into board (user_id, subject, content) \n");
sql.append("values (?, ?, ?)");
pstmt = conn.prepareStatement(sql.toString());
pstmt.setString(1, userid);
pstmt.setString(2, subject);
pstmt.setString(3, content);
cnt = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(pstmt != null)
pstmt.close();
if(conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html lang=\"ko\">");
out.println(" <head>");
out.println(" <meta charset=\"UTF-8\" />");
out.println(" <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />");
out.println(" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />");
out.println(" <link");
out.println(" href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css\"");
out.println(" rel=\"stylesheet\"");
out.println(" integrity=\"sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3\"");
out.println(" crossorigin=\"anonymous\"");
out.println(" />");
out.println(" <link href=\"../assets/css/app.css\" rel=\"stylesheet\" />");
out.println(" <title>SSAFY</title>");
out.println(" </head>");
out.println(" <body>");
out.println(" <div class=\"container\">");
out.println(" <div class=\"row justify-content-center\">");
out.println(" <div class=\"col-lg-8 col-md-10 col-sm-12\">");
out.println(" <h2 class=\"my-3 py-3 shadow-sm bg-light text-center\">");
out.println(" <mark class=\"sky\">글쓰기 결과</mark>");
out.println(" </h2>");
out.println(" </div>");
out.println(" <div class=\"col-lg-8 col-md-10 col-sm-12\">");
if(cnt != 0) {
out.println(" <div class=\"card text-center bg-light\">");
out.println(" <h2 class=\"fw-bold text-primary pt-3\">등록 완료!!!</h2>");
out.println(" <div class=\"card-body\">");
out.println(" <p class=\"card-text\">글작성이 완료되었습니다.</p>");
out.println(" <button type=\"button\" id=\"btn-list\" class=\"btn btn-outline-primary\">글목록 이동...</button>");
out.println(" </div>");
out.println(" </div>");
} else {
out.println(" <div class=\"card text-center bg-light\">");
out.println(" <h2 class=\"fw-bold text-danger pt-3\">등록 실패T.T</h2>");
out.println(" <div class=\"card-body\">");
out.println(" <p class=\"card-text\">");
out.println(" 글작성에 문제가 있습니다. <br /> 잠시 후 시도해주세요.");
out.println(" </p>");
out.println(" <button type=\"button\" id=\"btn-list\" class=\"btn btn-outline-danger\">글목록 이동...</button>");
out.println(" </div>");
out.println(" </div>");
}
out.println(" </div>");
out.println(" </div>");
out.println(" </div>");
out.println(" <script");
out.println(" src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js\"");
out.println(" integrity=\"sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p\"");
out.println(" crossorigin=\"anonymous\"");
out.println(" ></script>");
out.println(" <script>");
out.println(" document.querySelector(\"#btn-list\").addEventListener(\"click\", function() {");
out.println(" location.href = \"/board1_servlet/list\";");
out.println(" });");
out.println(" </script>");
out.println(" </body>");
out.println("</html>");
}
}
'Backend > Java' 카테고리의 다른 글
Cookie & Session (0) | 2022.09.20 |
---|---|
JSP Programming (0) | 2022.09.16 |
JDBC 프로그래밍 (0) | 2022.09.14 |
Java8 (0) | 2022.08.05 |
Java 순열과 조합 (0) | 2022.08.04 |