일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- clone
- 에러
- DataGrip
- MySQL
- php
- localhost
- Python
- csv
- 데이터베이스
- error
- vscode
- PHPStorm
- 클론
- 따옴표 삭제
- run sql script
- github clone
- Visual Studio Code
- 파이썬
- 단축키
- console창
- error 해결
- OrCAD 다운로드
- database
- cmd
- import data
- github token
- 깃 토큰
- jupyter
- 오류
- visualstudio code
- Today
- Total
개발 노트
9/5 <%! %>, application, request, error 처리하는 여러가지 방법, 서블릿 구조 init, doGet, doPost, destroy 본문
9/5 <%! %>, application, request, error 처리하는 여러가지 방법, 서블릿 구조 init, doGet, doPost, destroy
hayoung.dev 2022. 9. 12. 19:37num.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>숫자를 입력하세요</h1>
<form action="num.jsp" name="frm" >
<!-- <form action="num3.jsp" name="frm" > -->
숫자 : <input type="text" name="num"><p>
<input type="submit" value="확인">
</form>
</body>
</html>
num.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
<%
int num = Integer.parseInt(request.getParameter("num"));
int sum = 0;
for (int i = 1; i <= num; i++) {
sum += i;
}
%>
</head>
<body>
<h1>1부터<%=num%>까지 합</h1>
<%=sum%>
</body>
</html>
출력 결과
num3.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
<%
int num = Integer.parseInt(request.getParameter("num"));
int sum = 0;
for (int i = 1; i <= num; i++) {
sum += i;
out.println(i + "일때 합계는 " + sum + "<p>");
}
%>
</head>
<body>
</body>
</html>
출력 결과
[JSP 선언문]
<%! %>
[JSP 페이지의 내장 변수]
power.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<!-- 선언 -->
<%!
int power(int x, int y) {
int result = 1;
for (int i = 0; i<y; i++) {
result *= x;
}
return result;
}
%>
2^1 = <%=power(2,1) %><p>
2^2 = <%=power(2,2) %><p>
2^3 = <%=power(2,3) %><p>
2^4 = <%=power(2,4) %><p>
2^5 = <%=power(2,5) %><p>
</body>
</html>
출력 결과
select.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>보고 싶은 것을 선택하시오</h1>
<form action="select.jsp">
배경<input type="radio" name="pgm" value="color1"><br>
구구단<input type="radio" name="pgm" value="gugu1"><br>
네이버<input type="radio" name="pgm" value="response"><br>
<input type="submit" value="선택완료"><br>
</form>
</body>
</html>
select.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String[] col={"red","orange","yellow","green","blue","navy","violet","black"};
// 8미만 숫자가 랜덤하게 나옴.
int n = (int)(Math.random() * 8);
// color1.jsp, gugu1.jsp, response.jsp
String pgm = request.getParameter("pgm") + ".jsp";
/* RequestDispatcher : form문 없이 page를 이동할 필요가 있을 때 사용하는 객체 */
/* pgm페이지로 이동하겠다. */
RequestDispatcher rd = request.getRequestDispatcher(pgm);
if (pgm.equals("color1.jsp")) {
// 변수 선언
//setAttribute로 보내면 getAttribute로 받아야 한다.
request.setAttribute("color", col[n]);
// rd = request.getRequestDispatcher("color1.jsp");
} else if (pgm.equals("gugu1.jsp")) {
// 2단 ~ 9단
request.setAttribute("num", n + 2);
// rd = request.getRequestDispatcher("gugu1.jsp");
} else if (pgm.equals("response.jsp")) {
// 예비
}
// 2. 이동 Page를 지정하는 객체 선언를 실제적으로 이동
//form문은 url에 표시되지만, 이 방법으로 이동하면 url에 표시되지 않는다.
rd.forward(request, response);
%>
</body>
</html>
color1.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<%
//선언한 변수 꺼내는 방법
//setAttribute로 보내면 getAttribute로 받아야 한다.
//문자로 받을 때는 .toString() 사용.
String color = request.getAttribute("color").toString();
%>
<body bgcolor="<%=color %>">
</body>
</html>
출력 결과
gugu1.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<%
int num = Integer.parseInt(request.getAttribute("num").toString());
out.println("<h1>구구단 " + num + "단</h1>");
for (int i=1; i<=9; i++) {
out.println(num + " * " + i + " = " + (num * i)+"<br>");
}
%>
<body>
</body>
</html>
출력 결과
response.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
/* sendRedirect : 페이지 이동 방법 */
response.sendRedirect("http://naver.com");
%>
</body>
</html>
출력 결과
[och04]
[웹 어플리케이션 내부 객체의 영역 : page, request, session, application]
application.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String info = application.getServerInfo();
int major = application.getMajorVersion();
int minor = application.getMinorVersion();
String path = application.getRealPath("/");
%>
<h2>Application내장객체 예제</h2>
웹 컨테이너의 이름과 버전 : <%=info%><p>
서블릿의 버전 : <%=major%>.<%=minor%><p>
웹 어플리케이션 폴더의 로컬 시스템 경로 : <%=path%>
</body>
</html>
출력 결과
request.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String protocol = request.getProtocol();
String server = request.getServerName();
int port = request.getServerPort();
String clientIp = request.getRemoteAddr();
String clientHost = request.getRemoteHost();
String methodType = request.getMethod();
String url = new String(request.getRequestURL());
String uri = request.getRequestURI();
String contextPath = request.getContextPath();
%>
<h2>Request내장 객체 예제2</h2>
프로토콜명 : <%=protocol%><p>
접속한 서버명 : <%=server%> <p>
접속한 서버의 포트 번호 : <%=port%> <p>
클라이언트의 IP : <%=clientIp%> <p>
클라이언트의 호스트명 : <%=clientHost%> <p>
현재 페이지의 method방식 : <%=methodType%> <p>
요청한 현재 페이지의 경로(URL) : <%=url%> <p>
요청한 현재 페이지의 경로(URI) : <%=uri%> <p>
웹어플리케이션에서의 컨텍스트 경로 : <%=contextPath%> <p>
</body>
</html>
출력 결과
[och05]
num1.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>연산할 숫자 입력 Servlet 이용한 Error 처리</h2>
<form action="Cal">
<!-- <form action="Cal2"> -->
첫번째 숫자 : <input type="text" name="num1"><p>
두번째 숫자 : <input type="text" name="num2"><p>
<input type="submit" value="확인">
</form>
</body>
</html>
Cal.java
package och05;
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 Cal
*/
@WebServlet("/Cal")
public class Cal extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Cal() {
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.print("<html><body><h1>연산결과</h1>");
try {
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
out.println(num1 + " + " + num2 + " = " + (num1+num2) + "<p>");
out.println(num1 + " - " + num2 + " = " + (num1-num2) + "<p>");
out.println(num1 + " * " + num2 + " = " + (num1*num2) + "<p>");
out.println(num1 + " / " + num2 + " = " + (num1/num2) + "<p>");
} catch (NumberFormatException e) {
out.println("연산결과 NumberFormatException");
} catch (ArithmeticException e) {
out.println("0으로 나누었어");
} catch (Exception e) {
out.println("e.getMessage()->" + e.getMessage());
}
out.println("</body></html>");
out.close();
}
/**
* @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);
}
}
출력 결과 (두 번째 숫자를 0으로 입력한 경우)
(두 번째 숫자를 aa로 입력한 경우)
Cal2.java
package och05;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
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 Cal2
*/
@WebServlet("/Cal2")
public class Cal2 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Cal2() {
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.print("<html><body><h1>연산결과</h1>");
try {
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
out.println(num1 + " + " + num2 + " = " + (num1+num2) + "<p>");
out.println(num1 + " - " + num2 + " = " + (num1-num2) + "<p>");
out.println(num1 + " * " + num2 + " = " + (num1*num2) + "<p>");
out.println(num1 + " / " + num2 + " = " + (num1/num2) + "<p>");
} catch (Exception e) {
/* 페이지 이동을 통해 에러처리 */
RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
rd.forward(request, response);
}
out.println("</body></html>");
out.close();
}
/**
* @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);
}
}
error.jsp : error 페이지는 isErrorPage="true"로 error페이지라는 것을 반드시 작성해줘야 한다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isErrorPage="true"%>
<%
//200이 정상값이다. 정상값 setting
response.setStatus(200);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>공지사항</h1>
작업중...<p>
</body>
</html>
출력 결과 (두 번째 숫자에 0이나 aa를 입력한 경우)
num2.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function init() {
frm.num1.value = "100";
frm.num2.value = "5";
frm.num1.focus();
}
</script>
</head>
<!-- 초기값 세팅 -->
<body onload="init()">
<h2>연산할 숫자 입력 jsp 이용한 Error 처리</h2>
<form action="cal1.jsp" name="frm">
<!-- <form action="cal2.jsp" name="frm"> -->
<!-- <form action="cal3.jsp" name="frm"> -->
<!-- <form action="cal4.jsp" name="frm"> -->
<!-- <form action="cal5.jsp" name="frm"> -->
첫번째 숫자 : <input type="text" name="num1"><p>
두번째 숫자 : <input type="text" name="num2"><p>
<input type="submit" value="확인">
</form>
</body>
</html>
cal1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>연산결과</h2>
<%
try {
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
out.println(num1 + " + " + num2 + " = " + (num1 + num2) + "<p>");
out.println(num1 + " - " + num2 + " = " + (num1 - num2) + "<p>");
out.println(num1 + " * " + num2 + " = " + (num1 * num2) + "<p>");
out.println(num1 + " / " + num2 + " = " + (num1 / num2) + "<p>");
} catch (NumberFormatException e) {
out.println("연산결과 NumberFormatException");
} catch (ArithmeticException e) {
out.println("0으로 나누었어");
} catch (Exception e) {
out.println("e.getMessage()->" + e.getMessage());
}
%>
</body>
</html>
cal2.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<h2>연산결과 오류 시 error Page 이동</h2>
<%
try {
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
out.println(num1 + " + " + num2 + " = " + (num1 + num2) + "<p>");
out.println(num1 + " - " + num2 + " = " + (num1 - num2) + "<p>");
out.println(num1 + " * " + num2 + " = " + (num1 * num2) + "<p>");
out.println(num1 + " / " + num2 + " = " + (num1 / num2) + "<p>");
} catch (Exception e) {
RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
rd.forward(request, response);
}
%>
</body>
</html>
cal3.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>연산결과 오류시 Java Script 이용 처리</h2>
<%
try {
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
out.println(num1 + " + " + num2 + " = " + (num1 + num2) + "<p>");
out.println(num1 + " - " + num2 + " = " + (num1 - num2) + "<p>");
out.println(num1 + " * " + num2 + " = " + (num1 * num2) + "<p>");
out.println(num1 + " / " + num2 + " = " + (num1 / num2) + "<p>");
} catch (NumberFormatException e) {
%>
<!-- 자바문 사이사이에 자바스크립트로 처리 -->
<script type="text/javascript">
alert("그게 숫자냐");
//바로 전 페이지로 이동
history.go(-1);
</script>
<%
} catch (ArithmeticException e) {
%>
<script type="text/javascript">
alert("0으로 못나눠");
//바로 전 페이지로 이동
history.back();
</script>
<%
} catch (Exception e) {
out.println(e.getMessage());
%>
<script type="text/javascript">
alert("하여튼 에러야");
//페이지 이동
location.href = "num2.html";
</script>
<%
}
%>
</body>
</html>
cal4.jsp : try catch문을 걸지 않아도 cal4.jsp를 에러페이지로 지정했기 때문에 에러가 나면 알아서 error2.jsp를 실행시킨다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" errorPage="error2.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>연산결과 error Page이용한 처리</h2>
<%
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
out.println(num1 + " + " + num2 + " = " + (num1+num2)+"<p>");
out.println(num1 + " - " + num2 + " = " + (num1-num2)+"<p>");
out.println(num1 + " * " + num2 + " = " + (num1*num2)+"<p>");
out.println(num1 + " / " + num2 + " = " + (num1/num2)+"<p>");
%>
</body>
</html>
error2.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isErrorPage="true"%>
<% response.setStatus(200); %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>공지</h2>
나은 서비스를 위해서 준비중입니다 <p>
메세지 : <%=exception.getMessage()%> <p>
클래스 : <%=exception.getClass()%>
</body>
</html>
cal5.jsp : 에러페이지로 지정하지 않고 web.xml로 에러처리를 한다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>연산결과 setting(web.xml) 통한 error 처리</h2>
<%
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
out.println(num1 + " + " + num2 + " = " + (num1+num2)+"<p>");
out.println(num1 + " - " + num2 + " = " + (num1-num2)+"<p>");
out.println(num1 + " * " + num2 + " = " + (num1*num2)+"<p>");
out.println(num1 + " / " + num2 + " = " + (num1/num2)+"<p>");
%>
</body>
</html>
main > webapp > WEB-INF > web.xml
<?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_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>och05</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.jsp</welcome-file>
<welcome-file>default.htm</welcome-file>
</welcome-file-list>
<error-page>
<exception-type>java.lang.NumberFormatException </exception-type>
<location>/error/errorFormat.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.ArithmeticException</exception-type>
<location>/error/errorArith.jsp</location>
</error-page>
</web-app>
main > webapp > error폴더 생성 후 errorFormat.jsp 작성
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR" isErrorPage="true"%>
<% response.setStatus(200); %>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<h1>Format을 잘못 입력한거야</h1>
</body>
</html>
error> errorArith.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isErrorPage="true"%>
<% response.setStatus(200); %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>0으로 나누면 되니</h1>
</body>
</html>
[och06]
서블릿 구조 : init, doGet, doPost, destroy
name.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function chk() {
if (!frm.name.value) {
alert("너 이름이 뭐니 ?");
frm.name.focus();
return false;
}
return true;
}
</script>
</head>
<body>
<h2>이름을 입력하세요</h2>
<form action="Greet" name="frm" onsubmit="return chk()">
<!-- <form action="greet.jsp" name="frm" onsubmit="return chk()"> -->
이름 : <input type="text" name="name"><p>
<input type="submit" value="확인">
</form>
</body>
</html>
Greet.java(설정 시 init, destrory도 사용 체크)
package och06;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.GregorianCalendar;
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 Greet
*/
@WebServlet("/Greet")
public class Greet extends HttpServlet {
//서블릿의 버전 정보. 코드 건들지 않음.
private static final long serialVersionUID = 1L;
//파일 이름을 log로 하여 파일 생성
PrintWriter log;
/**
* @see HttpServlet#HttpServlet()
*/
public Greet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
//가장 처음 최초에 실행되는 것
try {
System.out.println("init start...");
//d:/delete/log 폴더가 미리 존재해야 한다.
log = new PrintWriter(new FileWriter("d:/delete/log/log.txt", true));
} catch (IOException e) {
e.printStackTrace();
System.out.println("에러!");
} }
/**
* @see Servlet#destroy()
*/
public void destroy() {
System.out.println("destory start...");
//죽기 전에 실행되는 것
//서블릿이 종료가 됐을 때 log가 null이 아니면 닫기.
if (log != null) log.close();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet start...");
String name = request.getParameter("name");
String msg = name + "님 반가워\r\n";
GregorianCalendar gc = new GregorianCalendar();
String date = String.format("%TF %TT\r\n", gc, gc);
// File 출력 --> date + msg
log.print(date + msg);
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
// 화면 출력 --> msg
out.println("<html><body><h2>인사</h2>"+msg);
out.println("</body></html>");
out.close();
}
/**
* @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);
}
}
실행 결과
처음 접속할 땐 init과 doGet이 실행되는데, 두번째 실행부터는 doGet만 실행된다. init은 맨 처음 초기화하는 작업만 하기 때문이다.
서버를 죽이면 destory가 실행된다.
d:/delete/log/log.txt 파일 확인
greet.jsp
<%@page import="java.io.FileWriter"%>
<%@page import="java.util.GregorianCalendar"%>
<%@page import="java.io.PrintWriter"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%!
private PrintWriter pw;
String date;
public void jspInit() {
GregorianCalendar gc = new GregorianCalendar();
//날짜와 시간
date = String.format("%TF %TT", gc, gc);
System.out.println("date->"+date);
//date값에는 :이 있는데 파일 이름에는 :을 쓸 수 없기 때문에 :를 없애준다.
String fileName = "d:/delete/log/" + date.replaceAll(":", "") + ".txt";
try {
pw = new PrintWriter(new FileWriter(fileName, true));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("jspInit 헐 !");
}
}
%>
<%
String name = request.getParameter("name");
String msg = name + "님 반가워 ";
out.println(msg + "<p> 현재시간 : " + date);
pw.println(msg + "\r\n 현재시간 : " + date + "\r\n");
%>
<%!
public void jspDestroy() {
System.out.println("jspDestroy start...");
pw.flush(); // buffer 강제출력
if (pw != null) pw.close();
}
%>
</body>
</html>
실행 결과
destory가 되면 하단 txt파일이 생긴다.
'프로젝트 기반 JAVA 응용 SW개발 : 22.07.19~23.01.20 > Servlet, JSP' 카테고리의 다른 글
9/19 css 셀렉터, Ajax (0) | 2022.09.24 |
---|---|
9/8 JSTL을 구성하는 작은 라이브러리들, forEach, forTokens (0) | 2022.09.15 |
9/7 EL, jsp.forward, 자바빈 (0) | 2022.09.12 |
9/2 Servlet, web setting의 get과 post, JSP 시작 (0) | 2022.09.12 |
9/1 JSP의 Get, Post 방식, IP, DNS, Port (0) | 2022.09.09 |