JSP

context.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--><!-- The contents of this file will be loaded for each web application --><Context>

    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->

    <!-- Uncomment this to enable Comet connection tacking (provides events
         on session expiration as well as webapp lifecycle) -->
    <!--
    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
    -->
    
    <Resource name="jdbc/myoracle" auth="Container"
              type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
              url="jdbc:oracle:thin:@127.0.0.1:1521:xe"
              username="java" password="1111" maxTotal="20" maxIdle="10"
              maxWaitMillis="-1"/>
              
             
</Context>

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- xml 지시어
web.xml 웹프로젝트의 설정 -->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>web03_jsp</display-name>
  
  <servlet>
  <!-- 서블릿의 별칭 -->
  	<servlet-name>while</servlet-name>
    <!-- 실제로 호출될 클래스 이름 -->
  	<servlet-class>ch03.WhileController</servlet-class>
  </servlet>
  <servlet-mapping>
  	<!-- 서블릿의 별칭 -->
  	<servlet-name>while</servlet-name>
  	<!-- url 패턴 -->
  	<url-pattern>/ch03_servlet/while.do</url-pattern>
  </servlet-mapping>
  
  
  <!-- 기본 페이지 설정 -->
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  
</web-app>


 

 

1. ifTestForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>

</head>
<body>
<form method="post" action="ifTest.jsp" name="form1">
<dl><!--  Definition List 정의 목록 -->

<!-- Definition Description 설명 -->
	<dt>입력하세요</dt>
	<dd>이름<input name="name"></dd>
	<dd>색상
		<select name="color">
		  <option value="blue">파랑</option>
		  <option value="green">초록</option>
		  <option value="red">빨강</option>
		</select>
	</dd>
	
	<dd>
	<input type="range" name="range" min="1" max="100"
	 onchange="document.form1.rangout.value=this.value"
	>
	<output name="rangout" for="range">5</output>
	</dd>
	
	<dd>
	<input type="submit" value="확인">
	</dd>
</dl>

</form>


</body>
</html>

 

출력 =>

 

입력하세요

이름

색상 

 5

 

 

 

 

 

 

ifTest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>

</head>
<body>

<%
//ifTest.jsp
 String name=request.getParameter("name");
 String color =request.getParameter("color");
 String selectColor="";
 if(color.equals("blue")){//== 오류 발생 가능성 높음
	 selectColor="파랑";
 }else if(color.equals("green")){
	 selectColor="초록";
 }else if(color.equals("red")){
	 selectColor="빨강";
 }
 
/*  
 switch(color){ //조건식(정수) JDK1.7 부터 스트링도 가능
   case "blue":
	   selectColor="파랑";
	   break;

   case "green":
	   selectColor="초록";
	   break;
	
   case "red":
	   selectColor="빨강";
	   break;
  }
  */
 
%>

<%=name %>님이 선택한 색상은 
<%= selectColor %> 입니다.

<div style="background:<%= color %>; width:300px; height:300px;"></div>

</body>
</html>

 

=>결과 

 

 

님이 선택한 색상은 파랑 입니다.

 

 

 

 

 

 

2. whileTestForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>

</head>
<body>

<!-- whileTestForm.jsp
jsp 페이지가 아닌 서블릿 클래스로 결과 제출
request.getContextPath() 현재 프로젝트의 컨텍스트 패스
컨텍스트 패스 : 웹프로젝트의 식별자 -->

<form method="post" action="<%= request.getContextPath() %>/ch03_servlet/while.do">

곱해질 값 : <input name="number" type="number"><br>
곱해질 횟수 : <input name="num" type="number"><br>
<input type="submit" value="확인">


</form>


</body>
</html>

 

=>출력

곱해질 값 : 
곱해질 횟수 : 

 

 

 

 

 

class WhileController

package ch03;

import java.io.IOException;

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

//서블릿 : 서버에서 실행되는 자바 프로그램
//annotation(어노테이션, 코드에 대한 설명문)



//whileTestForm.jsp  => WhileController.java =>while_result.jsp
//저장 영역(범위)
//pageContext :  현재 페이지
//request : 요청페이지 + 응답페이지
//session : 사용자 단위 (로그인 ~ 로그아웃)
//application : 서버단위


//url mapping:
//http://localhost:8080/컨텍스트/ch03_servlet/while.do
//whileController.java 가 실행됨


/*@WebServlet("/ch03_servlet/while.do")*/
public class WhileController extends HttpServlet {
	
	//자바 클래스의 id :
	private static final long serialVersionUID = 1L;
//get방식으로 호출할 때 실행
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		
		int number=Integer.parseInt(
				request.getParameter("number"));
		int num=Integer.parseInt(
				request.getParameter("num"));
		int result=1;
		for(int i=1; i<=num; i++){
			result *=number;
		}
		//request 영역에 저장  setAttribuet(key, value)
		request.setAttribute("result", result);
		
		//request정보분석 개체
		//request.getRequestDispatcher(url);;
		RequestDispatcher rd=
				request.getRequestDispatcher("/ch03_2/while_result.jsp");	
		rd.forward(request, response);
		
	}
//post 방식으로 호출할 때 실행
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}


 

while_result.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>

<%

	//저장할 때  :request.setAttribute("변수명", 값)
	//읽어올 때 :  (형변환)request.getAttribuet("변수명")
	int result =(Integer)request.getAttribute("result");
%>

계산 결과 :  <%= result %>

<p>

<!-- EL(Expression Language) 표현언어 -->

계산 결과 ${result }
</body>
</html>



=>결과

 

 

계산 결과 : 1953125

계산 결과 1953125

 

 


 

 

 

 

 

 

 

 

 

 

about author

PHRASE

Level 60  머나먼나라

건강식사법. ① 식사는 즐거운 마음으로 먹는다. ② 천천히 잘 씹어 먹는다. ③ 다소 싱겁게 담백하게 먹는다. ④ 약간 부족한 상태에서 그친다. ⑤ 식사 도중에는 물을 가급적 마시지 않는다.- New Life 편집부

댓글 ( 4)

댓글 남기기

작성