모델(Model), 뷰(View), 컨트롤러(Controller) 따로 mvc패턴으로 구분을 두지않고 한번에 모두 만들어봤다.
1. 환율계산기
package ex01;
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("/calc")
public class CalcServlet extends HttpServlet { // controller
private static final float USD_RATE = 0.00081f;
private static final float JPY_RATE = 0.095f;
private static final float CNY_RATE = 0.0051f;
private static final float GBP_RATE = 0.00062f;
private static final float EUR_RATE = 0.00074f;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset = utf-8");
PrintWriter pw = response.getWriter();
String command = request.getParameter("command");
String won = request.getParameter("won");
String operator = request.getParameter("operator");
if(command != null && command.equals("caculate")) { // jsp
String result = caculate(Float.parseFloat(won), operator);
pw.print("<html><font size = 10>반환결과</font><br>");
pw.print("<html><font size = 10>" + result + "</font><br>");
pw.print("<a href='calc'>환율 계산기</a>");
// pw.print("<a href='calc?command=caculate&operator=dollar&won=10000'>환율 계산기</a>"); // a태그는 오로지 겟방식.
return;
}
else {
pw.print("<html><title>환율 계산기</title>");
pw.print("<font size=5>환율 계산기</fonr><br>");
pw.print("<form name='frmCalc' method='get' action='calc' />");
pw.print("원화: <input type='text' name='won' size=10 /> ");
pw.print("<select name='operator' >");
pw.print("<option value='dollar'>달러</option>");
pw.print("<option value='en'>엔화</option>");
pw.print("<option value='wian'>위안</option>");
pw.print("<option value='pound'>파운드</option>");
pw.print("<option value='euro'>유로</option>");
pw.print("</select>");
pw.print("<input type='hidden' name='command' value='caculate' />");
pw.print("<input type='submit' value='변환' />");
pw.print("</form>");
pw.print("</html>");
pw.close();
}
}
private static String caculate(float won, String operator) { // 메서드(Service)
String result = null;
if(operator.equals("dollar")) {
result = String.format("%.6f", won / USD_RATE);
} else if(operator.equals("en")) {
result = String.format("%.6f", won / JPY_RATE);
} else if(operator.equals("wian")) {
result = String.format("%.6f", won / CNY_RATE);
} else if(operator.equals("pound")) {
result = String.format("%.6f", won / GBP_RATE);
} else if(operator.equals("euro")) {
result = String.format("%.6f", won / EUR_RATE);
}
return result;
}
}
2. 실행결과
반응형
'JAVA_SERVLET' 카테고리의 다른 글
[JAVA_SERVLET] 파일 업로드 (다중업로드, 자동 요일별분류) (0) | 2022.03.19 |
---|---|
[JAVA_SERVLET] 회원 목록 조회 (+DB 연동) (0) | 2022.03.16 |
[JSP] 로그인 기능, 창 만들기 (bootStrap5 적용), 유효성 검사 (0) | 2022.03.15 |
[JAVA_SERVLET] .jsp 적용이 안된 경우 (0) | 2022.03.14 |