Notice
Recent Posts
Recent Comments
Link
«   2024/12   »
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 31
Tags
more
Archives
Today
Total
관리 메뉴

JS Coding

[Java] Model 2 구조 사칙연산 구현 본문

Java

[Java] Model 2 구조 사칙연산 구현

JSKJS 2023. 9. 19. 00:15

 

servlet과 JSP를 활용한 Model 1 구조 

 

CalculateControllerServlet_Case2  의 servlet.java

package kr.or.ddit.calculate.controller;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.or.ddit.calculate.NumericOperatorType;

@WebServlet("/calculate/case2")
public class CalculateControllerServlet_Case2 extends HttpServlet {
/**
 * UI 제공
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String goPage = "/WEB-INF/views/calculate/case2/calForm.jsp";

if (goPage.startsWith("redirect:")) {
String location = req.getContextPath() + goPage.substring("redirect:".length());
resp.sendRedirect(location);
} else {
req.getRequestDispatcher(goPage).forward(req, resp);
}
}

private boolean validate(HttpServletRequest req, Map<String, String> errors) {
boolean valid = true;
String leftParam = req.getParameter("leftOp");
String rightParam = req.getParameter("rightOp");
String opParam = req.getParameter("operator");

// 검증 matches - 숫자인지 검증, null - 누락 검증 , isEmpty - 유무 검증
if (leftParam == null || leftParam.trim().isEmpty() || !leftParam.matches("\\d+")) {
valid &= false;
errors.put("leftOp", "좌측 피연산자 오류");
}
if (rightParam == null || rightParam.trim().isEmpty() || !leftParam.matches("\\d+")) {
valid &= false;
errors.put("rightOp", "우측 피연산자 오류");
}
// PLUS|MINUS|M.. | --> 는 or 연산자처럼 그러거나 뜻을 함
if (opParam == null || opParam.trim().isEmpty()){
valid &= false;
errors.put("operator", "연산자 누락");

}else {
try {
NumericOperatorType.valueOf(opParam);

} catch (IllegalArgumentException e) {
valid &= false;
errors.put("operator", "연산자 종류 오류");
}
}
return valid;
}

/**
 * UI 를 통해 입력한 데이터(parameter) 처리
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String leftParam = req.getParameter("leftOp");
String rightParam = req.getParameter("rightOp");
String opParam = req.getParameter("operator");


String goPage = null;
Map<String, String> errors = new LinkedHashMap<>();
req.setAttribute("errors", errors);
if (validate(req, errors)) {
int leftOp = Integer.parseInt(leftParam);
int rightOp = Integer.parseInt(rightParam);

//valueOf로 enum 상수 이름 검색 사용 가능
NumericOperatorType operator =  NumericOperatorType.valueOf(opParam);



int result = operator.operate(leftOp, rightOp);
String expression = null;



// char sign = '/';
// switch (opParam) {
// case "PLUS":
// result = leftOp + rightOp;
// sign = '+';
// break;
// case "MINUS":
// result = leftOp - rightOp;
// sign = '-';
// break;
// case "MULTIPLY":
// result = leftOp * rightOp;
// sign = '*';
// break;
// default:
// result = leftOp / rightOp;
// break;
// }

// expression = String.format("%d %c %d = %d", leftOp, operator.getSign(), rightOp, result);
expression = operator.getExpression(leftOp, rightOp);

req.setAttribute("expression", expression);
goPage = "/WEB-INF/views/calculate/case2/calculateView.jsp";

} else {
goPage = "/WEB-INF/views/calculate/case2/calForm.jsp";
}

if (goPage.startsWith("redirect:")) {
String location = req.getContextPath() + goPage.substring("redirect:".length());
resp.sendRedirect(location);
} else {
req.getRequestDispatcher(goPage).forward(req, resp);
}

}
}

 

calForm.jsp

 

<%@page import="java.util.stream.Collectors"%>
<%@page import="java.text.MessageFormat"%>
<%@page import="java.util.Arrays"%>
<%@page import="kr.or.ddit.calculate.NumericOperatorType"%>
<%@page import="java.util.Objects"%>
<%@page import="java.util.Map"%>
<%@ 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>
<jsp:include page="/includee/preScript.jsp"/>
<script src ="${pageContext.request.contextPath}/resources/js/app/calculate/calForm_case2.js"></script>
</head>
<body>

<form id="calForm" method="post" >
   <input type="number" name="leftOp" required value="${param.leftOp}"/>
   <select name="operator" required data-init-value="${param.operator}">
      <option value>연산자</option>
	  <%=
		 Arrays.stream(NumericOperatorType.values())
		 	   .map(ot->String.format("<option value='%s'>%c</option>",ot.name(),ot.getSign()))
		 	   .collect(Collectors.joining("\n"))
	   %>
   </select>
   <input type="number" name="rightOp" required value="${param.rightOp}"/>
   <input type="submit" value="=" id="calculate"/>
</form>
<div id="resultArea"></div>

<script>
// calForm.operator.value = "${param.operator}";
// $(calForm).on("submit",function(event){
//    event.preventDefault();
//    let url = this.action;
//    let method = this.method;
//    let data = $(this).serialize();   //quer string
//    let settings = {
//          url : url,
//          method : method,
//          data :    data,
//          dataType : "html" //Accept request header : Content-Type response header
//             ,
//             success : function(resp) {
//                $(resultArea).html(resp);
//             },
//             error : function(jqXhr, status, error) {
//                console.log("jqXhr : ", jqXhr);
//                console.log("status : ", status);
//                console.log("error : ", error);
//             }
//    };
//    $.ajax(settings);
//    return false;
// });
</script>

</body>
</html>

 

 

기본 전송 방식인 get 을 이용해

 

servlet 내 실행으로  calForm.jsp를 실행하고 

 

jsp내에서 form 태그를 이용해 action에서 method="post"를 이용해 

servlet내에 doPost로 받아 별도의 serlvet 없이 하나의 servlet를 활용하여 사칙연산을 가능하게 하였다.

 

'Java' 카테고리의 다른 글

[Java] 기초 Java 경마 게임 만들기  (0) 2024.01.04
[Java] 파일 다운로드 (File Download)  (0) 2024.01.02
[Java] List와 Set의 차이점  (0) 2023.11.11
[JAVA] A.O.P  (0) 2023.10.23
[Java] DataBase JDBC 연동 code 알아보기  (0) 2023.10.04