36일차는 취업 특강
웹 애플리케이션 컴포넌트
public
으로 선언해야 하고, HttpServlet을 상속받아야 함doGet( ) 메서드나 doPost( ) 메서드
를 반드시 오버라이딩(throws)
선언HttpServletResponse
를 사용package 패키지명;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class 서블릿클래스명 extends HttpServlet { // HttpServlet 상속
@Override // doGet() 오버라이딩
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 메서드의 실행부
}
}
클라이언트의 요청을 전달한 “요청명” 결정
서블릿은 요청명을 기준으로 이를 처리할 서블릿 선택
요청명과 서블릿을 연결해주는 작업 매핑(mapping)
web.xml(DD)
@WebServelt 어노테이션을 사용하여 코드에 직접 명시
<servlet> <!-- 1. 서블릿 등록 자바 클래스 순서 중요 -->
<servlet-name>HelloServlet</servlet-name>
<servlet-class>servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping> <!-- 2. 서블릿과 요청명 매핑 jsp 파일-->
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/12Servlet/HelloServlet11.so</url-pattern>
</servlet-mapping>
<servlet> <!-- 서블릿 등록 -->
<servlet-name>DirectServletPrint</servlet-name>
<servlet-class>servlet.DirectServletPrint</servlet-class>
</servlet>
<servlet-mapping> <!-- 서블릿과 요청명 매핑 -->
<servlet-name>DirectServletPrint</servlet-name>
<url-pattern>/13Servlet/DirectServletPrint.do</url-pattern>
</servlet-mapping>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HelloServlet</title>
</head>
<body>
<h2>HelloServlet 1. web.xml에서 매핑한 후 JSP 출력하기</h2>
<P>
<%= request.getAttribute("message") %>
<a href="./HelloServlet.so">바로가기</a>
</P>
</body>
</html>
```java
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("message", "Hello Servelt nice meet you!!");
req.getRequestDispatcher("/12Servlet/HelloServlet.jsp").forward(req, resp);
}
}
```
package servlet;
import java.io.IOException;
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("/12Servlet/AnnoMapping.do")
public class AnnoMapping extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("message", "Hello AnnoMapping Servelt nice meet you!!");
req.getRequestDispatcher("/12Servlet/AnnoMapping.jsp").forward(req, resp);
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AnnoMapping</title>
</head>
<body>
<h2>AnnoMapping</h2>
<P>
${message}<br/>
<a href="<%= request.getContextPath() %>/12Servlet/AnnoMapping.do">바로가기</a>
</P>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>FrontController</title>
</head>
<body>
<h2>FrontController : 한 번의 매핑으로 여러 가지 요청을 처리하기</h2>
${resultValue } <!-- 서블릿에서 request 영역에 저장할 결과값 -->
<ol>
<li>URI : ${uri}</li> <!-- 클라이언트가 요청한 전체경로를 표시 -->
<li>요청명 : ${commandStr}</li> <!-- 사용자가 요청 -->
</ol>
<ul>
<li><a href="../12Servlet/regist.one">회원가입</a></li>
<li><a href="../12Servlet/login.one">로그인</a></li>
<li><a href="../12Servlet/board.one">게시판</a></li>
</ul>
</body>
</html>
req.getRequestDispatcher("/12Servlet/FrontController.jsp").forward(req, resp);
package servlet;
import java.io.IOException;
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("*.one")
public class FrontController extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String uri = req.getRequestURI(); //12Servlet/regist.on
int lastSlash = uri.lastIndexOf("/"); //
String commandStr = uri.substring(lastSlash); // regist.one
if(commandStr.equals("/regist.one"))
registFunc(req);
else if(commandStr.equals("/login.one"))
loginFunc(req);
else if(commandStr.equals("/board.one"))
boardFunc(req);
req.setAttribute("uri", uri);
req.setAttribute("commandStr", commandStr);
req.getRequestDispatcher("/12Servlet/FrontController.jsp").forward(req, resp);
}
void registFunc(HttpServletRequest req) {
req.setAttribute("resultValue", "<h3>회원가입</h3>");
}
void loginFunc(HttpServletRequest req) {
req.setAttribute("resultValue", "<h3>로그인</h3>");
}
void boardFunc(HttpServletRequest req) {
req.setAttribute("resultValue", "<h3>게시판</h3>");
}
}
DirectServletPrint.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>DirectServletPrint</title>
</head>
<body>
<h2>DirectServletPrint web.xml에 매핑 후 Servlet에서 직접 출력</h2>
<form method="post" action="../12Servlet/DirectServletPrint.do">
<input type="submit" value="바로가기">
</form>
</body>
</html>
DirectServletPrint.java
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// 클래스를 http 서블릿 방식으로 변경
public class DirectServletPrint extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//응답,
resp.setContentType("text/html;charset=UTF-8");
//쓰기 기능
PrintWriter writer = resp.getWriterre();
//비동기 방식으로 통신할때 XML 이나 JSON방식을 처리할때(순수 데이터만 출력할때)
writer.println("<html>");
writer.println("<head><title>Insert title here</title></head>");
writer.println("<body>");
writer.println("<h2>서블릿에서 직접출력</h2>");
writer.println("<p>jsp로 포워딩 하지 않습니다.</p>");
writer.println("</body>");
writer.println("</html>");
writer.close();
}
}
📌 01. Get방식의 HTTP 요청을 처리하기 위한 서블릿의 멤버 함수 이름은 무엇인가요?
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{}
📌 02. 쿼리 스트링에서 이름이 name인 파라미터 값을 추출하기 위한 HttpServeltRequest 클래스의 멤버 함수 이름은 뭔가요?
request.getParameter("name")
📌 03. 체크박스 형태의 HTML 페이지로부터 전달되는 입력 값을 추출하기 위해 가장 적절하기 이용될 수 있는 HttpServletRequest 클래스의 멤버 함수 이름은 무엇인가요?
reqeust.getParameterValues()
📌 04. 다음은 사용자로부터 좋아하는 색깔을 받기 위한 color.html입니다. 다음 코드를 실행시켰을 때, 사용자가 입력한 값이 ‘Green’이라면, ‘Favorite Color:Green’이 출력되도록 ColorServlet 코드를 작성해주세요
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Favorite Color</title>
</head>
<body>
<form action="ColorServlet">
What is your favorite color? <br />
<input type="text" name="select" placeholder="Red, green, or blue?">
<br/> <br/>
<input type="submit" value="OK">
</form>
</body>
</html>
📌 여기에는 req.getRequestDispatcher("/12Servlet/FrontController.jsp").forward(req, resp);
안쓰는 이유는 PrintWriter out = resp.getWriter();
: 이 서블릿은 프론트 컨트롤러 패턴과 달리 직접 HTML 응답을 생성하여 보냄
package servlet;
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/ColorServlet")
public class ColorServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
PrintWriter writer = resp.getWriter();
String color = req.getParameter("select");
String result = "<html><h2>Favorite Color : " + color + "</h2></html>";
resp.getWriter().print(result);
}
}
📌 05.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>05</title>
</head>
<body>
<form action="CityServlet" method="get">
<input type="checkbox" name="city" value="seoul" checked>Seoul<br>
<input type="checkbox" name="city" value="busan" checked>Busan<br>
<input type="checkbox" name="city" value="incheon">Incheon<br>
<input type="submit" value="Ok">
</form>
</body>
</html>
java 파일
package servlet;
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/CityServlet")
public class CityServelt extends HttpServlet{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String[] usel = request.getParameterValues("city");
String res = "<html>";
for(String str : usel) {
res += "<h3>Selected city: " + str + "</h3>";
}
res += "</html>";
response.getWriter().print(res);
}
}
📌 06.
html 파일
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="get" action="SignupServlet">
<table align=center>
<tr><td colspan=2 align=center height=40><b>로그인</b><td></tr>
<tr>
<td align=right>아이디 </td>
<td><input type="text" name="id" placeholder="Email address" required></td>
</tr>
<tr>
<td align=right>패스워드 </td>
<td><input type="password" name="ps" required></td>
</tr>
<tr>
<td align=right>패스워드 확인 </td>
<td><input type="password" name="ps2" required></td>
</tr>
<tr>
<td align=right>이름 </td>
<td><input type="text" name="name" placeholder="name" required></td>
</tr>
<tr>
<td colspan=2 align=center height=50>
<input type="submit" value="회원가입하기">
</td>
</tr>
</table>
</form>
</body>
</html>
java 파일
package servlet;
import java.io.IOException;
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/SignupServlet")
public class SignupServlet extends HttpServlet{
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
String res = "<html>";
res += "<h3>User ID: " + req.getParameter("id") + "</h3>";
res += "<h3>Password: " + req.getParameter("ps") + "</h3>";
res += "<h3>Name: " + req.getParameter("name") + "</h3>";
res += "</html>";
resp.getWriter().print(res);
}
}
예제
package ex;
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 HelloWorld
*/
@WebServlet(description="My first Servlet", urlPatterns = {"/hello"} )
//@WebServlet("/hello")
// 현재 클래스가 서브클래스인 것을 컨테이너에 알리기 위해서 @WebServlet 에너테이션 사용
// 어떤 요청에 의해 서블릿을 호출할 것인지 결정하는 url-mapping 부분이 urlPattern ()
public class HelloWorld extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public HelloWorld() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.append("<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><title>HelloWorld</title></head><body>")
.append("<h2>HelloWorld!</h2><hr>")
.append("현재 날짜와 시간은: " +java.time.LocalDateTime.now())
.append("</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);
}
}
@PostConstruct
init()
service()
doGet( )
메서드를, post면 doPost( )
메서드를 호출destroy()
@PreDestroy
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>서블릿 LifeCycle</title>
</head>
<body>
<script type="text/javascript">
function requestAction(frm, met){
if(met == 1){
frm.method = 'get';
}
else{
frm.method='post';
}
frm.submit();
}
</script>
<h2>서블릿 LifeCycle</h2>
<form action="./LifeCycle.so">
<input type="button" value="Get방식 요청" onclick="requestAction(this.form, 1);" />
<input type="button" value="Post방식 요청" onclick="requestAction(this.form, 2);" />
</form>
</body>
</html>
package servlet;
import java.io.IOException;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.servlet.ServletConfig;
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 LifeCycle
*/
@WebServlet({ "/LifeCycle", "/12Servlet/LifeCycle.so" })
public class LifeCycle extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @return
* @see HttpServlet#HttpServlet()
*/
@PostConstruct
public void myPostConstruct() {
System.out.println("myPostConstruct()호출");
}
@Override
public void init(ServletConfig config) throws ServletException {
System.out.println("init() 호출 : 난 서블릿이 서브스 되기 전 초기화 셋팅");
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("service메소드 호출");
super.service(req, resp);
}
public LifeCycle() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet() 호출");
request.getRequestDispatcher("/12Servlet/LifeCycle.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost() 호출");
request.getRequestDispatcher("/12Servlet/LifeCycle.jsp").forward(request, response);
}
@Override
public void destroy() {
System.out.println("destory()메소드 호출");
super.destroy();
}
@PreDestroy
public void myPreDestory() {
System.out.println("myPreDestory() 실행");
}
}
오늘은 서블릿의 수명주기와 서블릿 개념에 대해 학습함 writer을 처음에는 이해 못했으나.. 퀴즈때 쓰고 이해하기 시작... 근데 공부 방식을 바꿔야 겠다는 생각을 요즘한다.. 어떻게 공부해야 좀 더 효율적으로 공부할 수 있을까 고민이다..