반응형
calc2.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="calc2" method="post">
<div>
<label>입력 : </label> <input type="text" name="v">
</div>
<div>
<input type="submit" name="operator" value="+"> <input
type="submit" name="operator" value="-"> <input
type="submit" name="operator" value="=">
</div>
<div>결과 : 0</div>
</form>
</body>
</html>
Calc2.java
package com.newlectrue.web;
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;
@WebServlet("/calc2")
public class Calc2 extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
ServletContext application = request.getServletContext();
String v_ = request.getParameter("v");
String op = request.getParameter("operator");
int v = 0;
if (!v_.equals("")) {
v = Integer.parseInt(v_);
}
// 계산
if (op.equals("=")) {
int x = (Integer) application.getAttribute("value");
int y = v;
String operator = (String) application.getAttribute("op");
int result = 0;
if (operator.equals("+")) {
result = x + y;
} else {
result = x - y;
}
response.getWriter().printf("result is %d\n", result);
} else {
// 값을 저장
application.setAttribute("value", v);
application.setAttribute("op", op);
}
}
}
https://youtu.be/s9ggk3FK-Ck?list=PLq8wAnVUcTFVOtENMsujSgtv2TOsMy8zd
https://youtu.be/leZ6Cf3cqEs?list=PLq8wAnVUcTFVOtENMsujSgtv2TOsMy8zd
반응형
'Java' 카테고리의 다른 글
Cookie와 상태 관리 (0) | 2021.09.02 |
---|---|
Session 객체와 상태 관리 (0) | 2021.09.02 |
필터 어노테이션을 이용한 한글 출력 (0) | 2021.09.02 |
서블릿 필터 (0) | 2021.09.02 |
post 요청 (0) | 2021.09.02 |