728x90
반응형
예제1) 정수를 입력 후 해당 정수 값까지의 합을 구하여 출력
[코드]
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
// [jsp 기본 객체 중 하나 - request]
// ㄱ. 파라미터가 넘어오지 않으면 request.getParameter()로 얻어오면 null 값을 반환함 ***
// ㄴ. ex05_02.jsp?n => ?뒤에 n만 찍히고 값은 나오지 않으면 ""(빈문자열)로 반환함 ***
// getParameter 함수가 기본적으로 String을 반환
String pn = request.getParameter("n");
String content = "";
if(pn != null){
int n = Integer.parseInt(request.getParameter("n"));
int sum = 0;
for(int i=1; i <= n; i++){
content += (i == n ? i : i + "+");
sum += i;
}
content += "=" + sum;
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>2022. 6. 15.</title>
</head>
<body>
<h3>ex01.jsp</h3>
<!--
질문) value = 10 상태 값이 유지되지 않는 이유는?
ex05_02.jsp -> submit -> 서버 요청 ex05_02.jsp
서버에 요청하고 응답하는 페이지가 다름 같은 ex05_02.jsp가 아님
input 태그에 value 속성값이 유지가 되지 않음 == 상태관리X
-->
<form>
<!-- 상태관리를 할 수 있도록 value에 코딩 -->
정수 입력 : <input type="text" name="n" value="<%= pn == null ? "" : pn %>" ><br> <!-- input태그 text박스가 하나일 때는 엔터를 치면 바로 submit이 되어짐 -->
<span></span>
<p id="demo">
<%
if(pn != null) {
%>
<%= content %>
<%
}
%>
</p>
</form>
<script>
$(function () {
$(":text:first").focus().select();
$("form[0]").submit(function () {
var pattern = /^\d+$/ // 숫자인지 체크하는 패턴
// js test() 메서드
if(pattern.test($(":text:first").val())){ // 유효성 검사를 성공하면
return;
} // if
// 유효성 검사 실패
//$("form > span") 과 같은 코딩(form 태그 안에 있는 span 태그) // 보였다가 3초동안 사라지겠다.
$("span", "form").text("Not Valid").css("color", "red").show().fadeOut(3000);
event.preventDefault(); // 기본 기능 취소
});
});
</script>
</body>
</html>
[결과]
- submit을 해도 입력한 값이 text 박스 안에 남아있음(상태관리)
예제2) 두 개의 정수를 연산자 선택 후 계산하기
[코드]
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
// 파라미터가 null 값으로 들어올 경우의 예외처리
String operator ="+";
String demoOutPut = "";
try{
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
operator = request.getParameter("operator");
double result = 0;
switch(operator){
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
} // switch
demoOutPut = String.format("%d%s%d=%.2f", num1, operator, num2, result);
}catch(Exception e){
// 파라미터가 null일 경우의 예외처리 하는 코딩은 아무것도 없지만 화면은 띄워줌
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>2022. 6. 15</title>
</head>
<body>
<h3>ex04.jsp</h3>
<form method="get">
<input type="text" id="num1" name="num1" autofocus="autofocus" value="<%= request.getParameter("num1") == null ? "" : request.getParameter("num1") %>">
<select name="operator" id="operator">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<script>
// 서버에서 먼저 실행되기 때문에 페이지 소스보기를 하면 operator 부분에 값이 들어와져있음
$("#operator").val("<%= operator %>");
</script>
<%--
<select name="operator" id="operator">
<option <%= operator.equals("+") ? "selected" : "" %>>+</option>
<option <%= operator.equals("-") ? "selected" : "" %>>-</option>
<option <%= operator.equals("*") ? "selected" : "" %>>*</option>
<option <%= operator.equals("/") ? "selected" : "" %>>/</option>
</select> --%>
<!-- EL로 처리하면 null일 경우에는 안찍힘! -->
<input type="text" id="num2" name="num2" value="${param.num2}">
</form>
<p id="demo"><%= demoOutPut %></p>
<script>
$(":text").css("text-align", "center");
$(":text").eq(1).on("keyup", function () {
if(event.which == 13){
$("form").submit(); // 입력받은 값을 전송(submit)하겠다.
}
});
</script>
</body>
</html>
[결과]
- submit을 해도 두 개의 정수 값과 연산자가 선택한 값 그대로 남아있음(상태관리)
- 서버에서 먼저 실행되기 때문에 페이지 소스보기를 하면 operator 부분에는 선택한 연산자가 들어와져있음
- request.getParameter()로 값을 가져오면 null인 경우에 500번 에러 발생하기 때문에 null 처리를 해주어야 함
- EL(표현언어)로 처리하면 null일 경우에는 안찍힘
728x90
반응형
'TIL > View Template' 카테고리의 다른 글
[SIST] JSP_days04_부서 선택시 해당 부서의 사원 정보를 테이블로 출력하는 예제 (0) | 2022.06.18 |
---|---|
[SIST] JSP_days03_response 객체 / 리다이렉트(redirect) / 포워드(forward) / GET 방식 + 서블릿 + JDBC + 포워딩 예제(JSTL 맛보기) (0) | 2022.06.16 |
[SIST] JSP_days02_DB연동해보기(JDBC) (0) | 2022.06.15 |
[SIST] JSP_days02/days03 (0) | 2022.06.15 |
[SIST] JSP_days01 (0) | 2022.06.14 |