- init()
서블릿 시작 - 요청
- service()
무조건 요청이 생겼을 경우 (사용하는 것 지양) - doGet()
get 방식의 요청이 생겼을 경우 - doPost()
post방식의 요청이 생겼을 경우 - destroy()
서블릿 종료 - 선택적으로 필요한 기능을 구현
1.서블릿
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>ServletEx01</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 서블릿 클래스에 서블릿 이름정함, 서블릿 이름으로 URL을 정함 -->
<servlet>
<servlet-name>ServletEx01</servlet-name>
<servlet-class>servlet1.ServletEx01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletEx01</servlet-name>
<url-pattern>/servlet01</url-pattern>
</servlet-mapping>
</web-app>
package servlet1;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletEx01 extends HttpServlet {
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("service 호출");
}
@Override
public void destroy() {
// TODO Auto-generated method stub
System.out.println("destroy 호출");
}
@Override
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
System.out.println("init 호출");
}
}
init 메서드는 최초 클라이언트에 의해 한번 수행됨
이후에 서버는 켜진채로 유지되며 다른 클라이언트요청이 오면 service 메서드만 사용
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>ServletEx01</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 서블릿 클래스에 서블릿 이름정함, 서블릿 이름으로 URL을 정함 -->
<servlet>
<servlet-name>ServletEx01</servlet-name>
<servlet-class>servlet1.ServletEx01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletEx01</servlet-name>
<url-pattern>/servlet01</url-pattern>
</servlet-mapping>
</web-app>
package servlet1;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletEx01 extends HttpServlet {
//@Override
//protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
// TODO Auto-generated method stub
// System.out.println("service 호출");
//}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("doGet 호출");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("doPost 호출");
}
@Override
public void destroy() {
// TODO Auto-generated method stub
System.out.println("destroy 호출");
}
@Override
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
System.out.println("init 호출");
}
}
3.클래스마다 서블릿 등록
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>ServletEx01</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 서블릿 클래스에 서블릿 이름정함, 서블릿 이름으로 URL을 정함 -->
<servlet>
<servlet-name>ServletEx01</servlet-name>
<servlet-class>servlet1.ServletEx01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletEx01</servlet-name>
<url-pattern>/servlet01</url-pattern>
</servlet-mapping>
<!-- 클래스 하나당 각각 서블릿등록 -->
<servlet>
<servlet-name>ServletEx02</servlet-name>
<servlet-class>servlet1.ServletEx02</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletEx02</servlet-name>
<url-pattern>/servlet02</url-pattern>
</servlet-mapping>
</web-app>
package servlet1;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletEx02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("doGet 호출");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("doPost 호출");
}
}
4.JSP파일에서 서블리 호출
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- JSP 파일에서 서블릿 get, post방식 호출 -->
<form action="./servlet02" method="post">
아이디 : <input type="text" name="id" />
<input type="submit" value="전송" />
</form>
</body>
</html>
5.서블릿 매핑
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>ServletEx01</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>ServletEx01</servlet-name>
<servlet-class>servlet1.ServletEx01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletEx01</servlet-name>
<url-pattern>/servlet01</url-pattern>
</servlet-mapping>
<!-- 호출 패턴의 변경 -->
<!-- 서블릿 URL 두개적을 수 있음 -->
<!-- 확장자를 뒤에 적어줘서 실제파일이 아니라 가상의 파일임을 암시할 수 있음
웹상에서 URL실제 파일이 없을때 실제파일을 찾으려면 설정파일 web.xml을 봐야한다-->
<!-- 가상의 디렉토리를 표시할 수있음 -->
<!-- *.daum 어느파일이름을 써도 뒤에 확장자가daum을 붙이면 서블릿이 다 받음 -->
<servlet>
<servlet-name>ServletEx02</servlet-name>
<servlet-class>servlet1.ServletEx02</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletEx02</servlet-name>
<url-pattern>/servlet02.do</url-pattern>
<url-pattern>/servlet03.naver</url-pattern>
<url-pattern>/dir/servlet03.naver</url-pattern>
<url-pattern>*.daum</url-pattern>
</servlet-mapping>
</web-app>
package servlet1;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletEx02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("doGet 호출");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("doPost 호출");
}
}
ex
6.톰캣에서 해주는 서블릿 제작을 직접하기
package servlet1;
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;
public class ServletEx01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doProcess(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doProcess(req, resp);
}
//doGet, doPost 같이 받는 메소드 만듦
protected void doProcess(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter out =resp.getWriter();
out.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body>");
out.println("Hello Servlet");
out.println("</body>");
out.println("</html>");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>ServletEx02</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 서블릿 등록 -->
<servlet>
<servlet-name>ServletEx01</servlet-name>
<servlet-class>servlet1.ServletEx01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletEx01</servlet-name>
<url-pattern>/servlet01</url-pattern>
</servlet-mapping>
</web-app>
7. 서블릿 간의 요청, 응답
package servlet1;
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;
public class ServletEx01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doProcess(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doProcess(req, resp);
}
//클라이언트 get or post 요청시 실행
protected void doProcess(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//서블릿 응답 한글인코딩 ◀JSP에서 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
resp.setContentType("text/html; charset=utf-8");
PrintWriter out =resp.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<meta charset='UTF-8'>"); //HTTP 한글 페이지 인코딩
out.println("</head>");
out.println("<body>");
out.println("<form action='servlet02' method='post'>");
out.println("아이디 : <input type='text' name='id' />");
out.println("<input type='submit' value='전송' />");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}
}
package servlet1;
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;
public class ServletEx02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doProcess(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doProcess(req, resp);
}
//
protected void doProcess(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String id = req.getParameter("id");
resp.setContentType("text/html; charset=utf-8");
PrintWriter out = resp.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<meta charset='UTF-8'>");
out.println("</head>");
out.println("<body>");
out.println("아이디 :" +id);
out.println("</body>");
out.println("</html>");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>ServletEx02</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 서블릿 등록 -->
<servlet>
<servlet-name>ServletEx01</servlet-name>
<servlet-class>servlet1.ServletEx01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletEx01</servlet-name>
<url-pattern>/servlet01</url-pattern>
</servlet-mapping>
<!-- 서블릿 등록 -->
<servlet>
<servlet-name>ServletEx02</servlet-name>
<servlet-class>servlet1.ServletEx02</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletEx02</servlet-name>
<url-pattern>/servlet02</url-pattern>
</servlet-mapping>
</web-app>
8. annotation기법: 서블릿을 만들고 web.xml에 일일적어주는 것을 개량
자동 생성됨
package servlet1;
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;
/**
* Servlet implementation class ServletEx01
*/
@WebServlet("/servlet01")
public class ServletEx01 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doProcess(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doProcess(request, response);
}
protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
9
package servlet1;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
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 ServletEx01
*/
@WebServlet("/servlet01")
public class ServletEx01 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doProcess(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doProcess(request, response);
}
protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=utf-8");
ServletContext context = getServletContext();
String serverInfo = context.getServerInfo();
int majorVersion = context.getMajorVersion();
String path1 = context.getContextPath(); //프로젝트 경로를 알기위해서 자주 사용함
String path2 = context.getRealPath("/text.html");
PrintWriter out =response.getWriter();
//서블릿 정보 출력
out.println("<html>");
out.println("<head>");
out.println("<meta charset='UTF-8'>");
out.println("</head>");
out.println("<body>");
out.println("웹서버 : "+ serverInfo + "<br>");
out.println("버전 : "+ majorVersion+ "<br>");
out.println("경로1 : "+ path1 + "<br>");
out.println("경로2 : "+ path2 + "<br>");
out.println("</body>");
out.println("</html>");
}
}
10.서블릿 구구단
서블릿명 : gugudan.java URL명: /gugudan
package servlet1;
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 gugudan
*/
@WebServlet("/gugudan")
public class gugudan extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request, response);
}
protected void doProcess(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//서블릿 응답 한글인코딩 ◀JSP에서 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
resp.setContentType("text/html; charset=utf-8");
PrintWriter out =resp.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<meta charset='UTF-8'>"); //HTTP 한글 페이지 인코딩
out.println("</head>");
out.println("<body>");
out.println("<form action='gugudan_ok' method='post'>");
out.println("시작단 : <input type='text' name='startdan' />");
out.println("끝단 : <input type='text' name='enddan' />");
out.println("<input type='submit' value='전송' />");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}
}
서블릿명 : gugudanok.java URL명: /gugudan_ok
package servlet1;
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 gugudanok
*/
@WebServlet("/gugudan_ok")
public class gugudanok extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request, response);
}
protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
int startdan = Integer.parseInt((request.getParameter("startdan")== null || request.getParameter("startdan").equals(""))?"1":request.getParameter("startdan"));
int enddan = Integer.parseInt((request.getParameter("enddan")== null || request.getParameter("startdan").equals(""))?"2":request.getParameter("enddan"));
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<meta charset='UTF-8'>");
out.println("</head>");
out.println("<body>");
out.println("구구단 :<br>");
out.print("<table border='1'>");
for(int i=startdan; i<=enddan; i++){
out.print("<tr>");
for(int j=1;j<=9;j++){
out.print("<td>"+i+" X "+j+" = "+i*j+"</td>");
}
out.print("</tr>");
}
out.print("</table>");
out.println("</body>");
out.println("</html>");
}
}
11. 웹실행시 초기값을 주고싶을때
package servlet1;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(
//초기화 데이터 생성됨
urlPatterns = { "/ServletEx01" },
initParams = {
@WebInitParam(name = "user", value = "tester"),
@WebInitParam(name = "password", value = "1234")
})
public class ServletEx01 extends HttpServlet {
private static final long serialVersionUID = 1L;
private String user;
private String password;
@Override
public void init() throws ServletException {
// 서버실행시 초기화
user = getInitParameter("user");
password = getInitParameter("password");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
response.getWriter().append("user : "+user);
response.getWriter().append("password: "+password);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
12. 톰캣 서버시작시에 초기화
package servlet1;
import java.io.IOException;
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;
//톰캣이 가동되었을때 미리 init()을 메모리에 올려둠 loadOnStartup, 빠른속도로 데이터에 접근할 수있음
//올려지는 순서 =1
@WebServlet(urlPatterns = "/ServletEx01", loadOnStartup=1)
public class ServletEx01 extends HttpServlet {
private static final long serialVersionUID = 1L;
public ServletEx01() {
super();
}
public void init(ServletConfig config) throws ServletException {
System.out.println("ServletEx01 init()");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
package servlet1;
import java.io.IOException;
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;
//톰캣이 가동되었을때 미리 init()을 메모리에 올려둠 loadOnStartup, 빠른속도로 데이터에 접근할 수있음
//올려지는 순서 =2
@WebServlet(urlPatterns = "/ServletEx02", loadOnStartup=2)
public class ServletEx02 extends HttpServlet {
private static final long serialVersionUID = 1L;
public ServletEx02() {
super();
}
public void init(ServletConfig config) throws ServletException {
System.out.println("ServletEx02 init()");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
package servlet1;
import java.io.IOException;
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;
//톰캣이 가동되었을때 미리 init()을 메모리에 올려둠 loadOnStartup, 빠른속도로 데이터에 접근할 수있음
//올려지는 순서 =3
@WebServlet(urlPatterns = "/ServletEx03", loadOnStartup=3)
public class ServletEx03 extends HttpServlet {
private static final long serialVersionUID = 1L;
public ServletEx03() {
super();
}
public void init(ServletConfig config) throws ServletException {
System.out.println("ServletEx03 init()");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
13. 서블릿은 이미지 전송 가능함
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>부부 클리닉</title>
</head>
<body>
<center>
<h3>이부부의 이혼에 찬성하십니까? 반대하십니까</h3>
<form action="ServletEx01" method="post">
<input type="radio" name="choice" value="yes" />찬성이에요.<br>
<input type="radio" name="choice" value="no" />반대입니다.<br>
<input type="submit" value="투표하기" />
</form>
</center>
</body>
</html>
package servlet1;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
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;
public class ServletEx01 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//파일저장하는 실제경로, 초기화 매개변수 파일 이름 획득
String path = this.getServletContext().getRealPath("/data");
String file_name = this.getInitParameter("result");
//디렉토리만듦, 파일객체 만듦
File dir = new File(path);
if(!dir.exists())dir.mkdir();
File file= new File(dir,file_name);
//파일있으면 읽어와서 기존 찬성반대수 입력받음
int agree =0;
int disagree = 0;
if(file.exists()){
DataInputStream f_in = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
try{
agree=f_in.readInt();
disagree =f_in.readInt();
}catch(Exception e){
agree = 0;
disagree = 0;
}
f_in.close();
}
//방금 투표한 값을 찬반수에 더해줌
String choice = request.getParameter("choice");
if(choice != null && choice.equalsIgnoreCase("yes")) agree++;
else if(choice != null && choice.equalsIgnoreCase("no")) disagree++;
//투표로 변경된 찬반수를 파일로 다시 저장함
DataOutputStream f_out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
f_out.writeInt(agree);
f_out.writeInt(disagree);
f_out.close();
//이미지 형태의 서블릿을 HTML출력
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<html><head><title>결과</title></head>");
out.println("<body><center>");
out.println("<h3>찬반투표결과!</h3>");
out.println("<img src='ServletEx01_Sub?agree=" +agree);
out.println("&disagree="+disagree +"'/>");
out.println("</center></body></html>");
}
}
package servlet1;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class ServletEx01_Sub extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//서블릿으로 전달된 파라매터 받음
int agree = Integer.parseInt(request.getParameter("agree"));
int disagree = Integer.parseInt(request.getParameter("disagree"));
int tot = agree+disagree;
//차트그림
Graphics2D g = null;
try{
int width = 300;
int height = 200;
//그림판 생성
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//그림판에 그래픽객체 생성
g= img.createGraphics();
int x_start = 30;
int agree_y_start = height*1/4;
int disagree_y_start = height*3/5;
int g_height =25;
int space =5;
int y_space = 20;
//배경
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0, 0, width, height);
//좌표
g.setColor(Color.BLACK);
g.drawLine(x_start, space, x_start, height-y_space);
g.drawLine(x_start, height-y_space, width-space, height-y_space);
g.drawString("찬성", space, height*1/3);
g.drawString("반대", space, height*2/3);
g.drawString("0%", x_start, height-space);
g.drawString("50%", x_start+(width-(x_start+space))/2, height-space);
g.drawString("100%", width-30, height-space);
//찬성막대그래프
g.setColor(Color.RED);
g.fillRect(x_start, agree_y_start, (width-(x_start+space))*agree/tot, g_height);
//반대막대그래프
g.setColor(Color.GREEN);
g.fillRect(x_start, disagree_y_start, (width-(x_start+space))*disagree/tot, g_height);
//응답유형 정함
response.setContentType("image/jpeg");
//이미지처리 1바이트 출력 스트림 생성
ServletOutputStream out = response.getOutputStream();
//인코딩 객체 생성
JPEGImageEncoder encode = JPEGCodec.createJPEGEncoder(out);
//인코딩 후 출력
encode.encode(img);
}catch(Exception e){
e.printStackTrace();
}finally{
if(g !=null) g.dispose();
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>ServletEx00</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 서블릿 등록, 초기값 지정 -->
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>servlet1.ServletEx01</servlet-class>
<init-param>
<param-name>result</param-name>
<param-value>result.dat</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/ServletEx01</url-pattern>
</servlet-mapping>
<!-- 서블릿 등록 -->
<servlet>
<servlet-name>MyServlet_Sub</servlet-name>
<servlet-class>servlet1.ServletEx01_Sub</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet_Sub</servlet-name>
<url-pattern>/ServletEx01_Sub</url-pattern>
</servlet-mapping>
</web-app>
댓글 없음:
댓글 쓰기