다연이네

[days01] <% %> 사용해보기 본문

JSP

[days01] <% %> 사용해보기

 다연  2020. 12. 22. 21:22
반응형

method="get"인 경우 url
http://localhost/jspPro/days01/ex03_ok.jsp?name=admin&age=23

http://localhost/jspPro/days01/
ex03_ok.jsp		form의 action 속성값
?			쿼리스트링(query string)
name=admin 		name="name"
&			파라미터를 연결하는 연산자
age=23 			name="age"

method="post"인 경우 url
http://localhost/jspPro/days01/ex03_ok.jsp

 

 

ex03.jsp

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="">
<style>
</style>
<script>
   $(document).ready(function (){     
   });
</script>
</head>
<body>

<form action="ex03_ok.jsp" method="post">
<!-- action속성값이 비어있으면 자기자신 페이지 -->
<!-- method 안쓰면 기본은 get방식 -->
	Name : <input type="text" id="name"  name="name" autofocus="autofocus"/><br>
	Age : <input type="text" id="age" name="age" />
	<!-- id가 아니라 name 속성 -->
	
	<button type="submit">전송</button>
</form>
<!-- 기억 - 톰캣은 8.대로 install버전 사용했다 -->
</body>
</html>

ex03_ok.jsp

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%
	//스크립트릿(scriptlet) - 자바코딩
	String name = request.getParameter("name");//request : jsp에 내장되어있는 객체
	String age = request.getParameter("age");
	// [기억] null이 나오면 전송 안된 것 
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="">
<style>
</style>
<script>
   $(document).ready(function (){     
   });
</script>
</head>
<body>
>이름(Name) : <%= name %><br>
>나이(Age) : <%= age %><br>

</body>
</html>

 

 

 


 

정수 입력 후 엔터치면 입력된 정수만큼의 자연수 합을 출력시키기

1번

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
	// ?num=12
	String strNum = request.getParameter("num");
	int n ;
	if(strNum == null){
		n=0;
	}else{
		n = Integer.parseInt(strNum);
	}
%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="">
<style>
</style>
<script>
   $(document).ready(function (){     
	   $("input:first").focus().select();
	   
	   $("form").submit(function(event) {
	   		var pattern = /^\d+$/; /* ^$ : 처음부터 끝까지 모두가 숫자여야한다  */
	   		if (pattern.test( $("#num").val() )) {
				return ;
			}
	   		//숫자가 아닌 유효하지 않은 값일 경우
	   		$("span")
	   			.text("Not Valid")
	   			.css("color","red")
	   			.show()
	   			.fadeOut(3000);
	   		
	   		event.preventDefault();
	   }); //submit
   }); //ready
</script>
</head>
<body>
<!-- http://localhost/jspPro/days01/ex04.jsp?num=12 -->
<form action=""> <!-- action 속성값이 없을 경우: 다시 자기자신 페이지 요청 (꼭 기억)-->
	정수 입력 : <input type="text" id="num" name="num" />
	<br>
	<span></span>
</form>
<%
	//스크립트릿(scriptlet) - 자바코딩
	//jsp 내장 객체 : out
	// 서블릿 : PrintWriter out = response.getWriter() 받아왔어야 하지만
	//jsp는 그냥 out 쓰면 됨
	int sum = 0;
	for(int i=1; i<=n; i++){
		if(i==n){
			out.print(i);
		}else{
			out.append(i+"+"); //문자열
		}
		sum +=i;
	}//for
	out.append("="+sum);
%>
</body>
</html>

2번 (1번 코드 수정)

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
	//ex01.jsp -> /days01/ex01/jsp 요청 -> 아파치 웹서버 -> 톰캣(WAS) 서버
																		//jsp -> 서블릿 java로 변환 -> 객체 생성 -> 실행
																		// <-- 응답
																		//==jsp가 톰캣 안에서 서블릿 클래스로 변환된다.

	//꼭 기억
	//?			X=> null
	//?num= 	   	     ""  
	//  ?num=12a 주면 유효성검사 의미 없이 오류남(parseInt하다가 오류) => 이것까지 신경써서 막아야함 strNum!=""
    
	String strNum = request.getParameter("num");
	if(strNum==null) strNum="";
	int n;
	
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="">
<style>
</style>
<script>
   $(document).ready(function (){     
	   $("input:first").focus().select();
	   
	   $("form").submit(function(event) {
	   		var pattern = /^\d+$/; /* ^$ : 처음부터 끝까지 모두가 숫자여야한다  */
	   		if (pattern.test( $("#num").val() )) {
				return ;
			}
	   		//숫자가 아닌 유효하지 않은 값일 경우
	   		$("span")
	   			.text("Not Valid")
	   			.css("color","red")
	   			.show()
	   			.fadeOut(3000);
	   		
	   		event.preventDefault();
	   }); //submit
   }); //ready
</script>
</head>
<body>
<!-- http://localhost/jspPro/days01/ex04.jsp?num=12 -->
<form action=""> <!-- action 속성값이 없을 경우: 다시 자기자신 페이지 요청 (꼭 기억)-->
	정수 입력 : <input type="text" id="num" name="num" value="<%= strNum%>"/>
	<br>
	<span></span>
</form>
<%
	//if(strNum!=null && strNum!=""){ 
	if(strNum!=""){ 
		n= Integer.parseInt(strNum);
	int sum=0;
	for(int i=1; i<=n; i++){
		if(i==n){
%><%= i %><% //중간에 끊었다
	}else{
%><%= i %>+<% //중간에 끊었다 - 아무리 끊어도 랜더링시 하나로 만들어진다
		}
		sum+=i;
	}//for
	//out.append("="+sum);
			%>=<%=sum %><%
	}	//if
%>
</body>
</html>

 

 


 

 

텍스트 박스에 자연수를 입력하고, 뒤의 텍스트박스에서 엔터를 치면 밑의 공간에 계산 값 출력

(엔터를 쳐도 입력 값이 남아있게 해라) 

 

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String output ="";
String operator="+" ;
int num1=0, num2=0;
try{
	num1 = Integer.parseInt(request.getParameter("n1"));
	num2 = Integer.parseInt(request.getParameter("n2"));
	operator = request.getParameter("op");
	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;
	}
	
	output = String.format("%d%s%d=%.2f", num1,operator,num2, result);
}catch(Exception e){
	System.out.println(e.toString());
}
%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="">
<style>
</style>
<script>
   $(document).ready(function (){     
	   
	   $(":text").eq(1).on("keyup", function(event) {
	   	if(event.keyCode==13){
	   		$("form").submit();
	   	}
	   })//keyup
	   
	   //jquert select option selected 설정하는 코딩
	   $("#op").val("<%=operator%>");
	   
   });//ready
</script>
</head>
<body>
<!--
       ㄱ. 마지막으로  n2 입력 후  엔터 치면 
       ㄴ. 상태가 유지 되면서
       ㄷ. p 태그의 연산 결과 출력.
-->
<form method="get">
  <input type="text" id="n1" name="n1"  autofocus value="${param.n1}"/> <!-- 0이 아니라 공백 -->
  <select id="op" name="op">
 <option>+</option>
 <option>-</option>
 <option>*</option>
 <option>/</option>
  </select>
  <input type="text" id="n2" name="n2" value="${param.n2 }" />
</form>

<p id="demo"> <%=output %></p>

<a href="ex01_03.jsp?name=admin&age=20">a태그</a>
</body>
</html>

n1와 n2의 value를 <%= %>를 통해서 받지 않고 표현언어를 통해서 받아야 맨 처음 값 0이 출력되지 않는다.

또, 기호를 남아있게 하는 방법은 여러 가지가 존재한다. 밑은 하나의 추가적인 방법이다. 

(하지만  $("#op").val("<%=operator%>"); 이 한 줄이 훨씬 간단하다는 것)

<select id="op" name="op">   
	<option <%if( operator.equals("+")  ){%>selected<%}%>>+</option>
	<option <%if( operator.equals("-")  ){%>selected<%}%>>-</option>
	<option <%if( operator.equals("*")  ){%>selected<%}%>>*</option>
	<option <%if( operator.equals("/")  ){%>selected<%}%>>/</option>
</select>

 

 

 

 

<script> 
       $(":text").first().click(function(event) {         alert("1");      })
       $(":text:first-of-type").click(function(event) {         alert("11");      })
       $(":text").eq(0).click(function(event) {         alert("1");      })
      
       $(":text").last().click(function(event) {         alert("2");      })
       $(":text:nth-of-type(2)").click(function(event) {         alert("2");      })
       $(":text:nth-last-of-type(1)").click(function(event) {         alert("2");      })
       $(":text").eq(1).click(function(event) {         alert("2");      })
       $("form").find(":text").eq(1).click(function(event) {         alert("2");      })
</sript>
반응형
Comments