62일 차 - httpServlet, jsp 활용문제, JSP 스크립트릿, [SQL] 형 변환 함수, NVL 함수 (23.03.27)

yvonne·2023년 3월 27일
0

📂JSP

목록 보기
2/7
post-thumbnail

1. JSP

📌 HttpServlet

  • doGet() 과 doPost()로 캡슐화
  • 안에는 resquest와 response 객체가 있다.
@WebServlet("/FormEx2") //애너테이션
  • FormEx2 객체를 생성해주는 역할



📌 Servlet 활용

  • Formex.html (체크박스와 라디오박스 적용)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="FormEx" method="get">
		이름 : <input type="text" name="name" size="10"><br /> 
		아이디 : <input type="text" name="id" size="10"><br /> 
		<input type="checkbox" name="hobby" value="cook">요리 
		<input type="checkbox" name="hobby" value="run">조깅 
		<input type="checkbox" name="hobby" value="swim">수영
	    <input type="checkbox" name="hobby" value="sleep">잠~~<br /> 
	    <input type="radio" name="major" value="kor">국어 
	    <input type="radio" name="major" value="eng" checked="checked">영어
	    <input type="radio" name="major" value="mat">수학
	    <input type="submit" value="전송"> <input type="reset" value="리셋"><br />
	</form>
</body>
</html>
  • FormEx.java (체크박스와 라디오박스 request 받기)
	protected void doGet(HttpServletRequest request, HttpServletResponse response) // ** request객체, response객체
			throws ServletException, IOException {
		System.out.println("doGet()..");
		System.out.println(request.getRemoteAddr());
		System.out.println(request.getRemoteHost());

		request.setCharacterEncoding("UTF-8");

		String name = request.getParameter("name"); // ** formex.html의 name을 받아오는 함수
		System.out.println(name);
		String id = request.getParameter("id"); // ** formex.html의 name을 받아오는 함수
		System.out.println(id);
		String[] hobbys = request.getParameterValues("hobby");
		System.out.println(hobbys);
		String major = request.getParameter("major");

        response.setContentType("text/html; charset=UTF-8"); // 한글 출력하기
		PrintWriter writer = response.getWriter();
		writer.println("<html><head></head><body>");
		writer.println("아이디 : " + id + "<br>");
		writer.println("이름 : " + name + "<br>");
		writer.println("취미들 : " + Arrays.toString(hobbys) + "<br>");
		writer.println("전공 : " + major + "<br>");
		writer.println("</body></html>");
	}
  • 결과

📌 원의 넓이 구하는 서블릿 생성하기

  • circle.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="circle" method="get">
		원의 반지름 : <input type="text" name="radius" size="5"><br /> 
			<input type="submit" value="전송"> 
			<input type="reset" value="리셋"><br />
	</form>
</body>
</html>
  • circle.java
package edu.global.ex;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

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 edu.global.ex.shape.getCircle;

/**
 * Servlet implementation class rsp
 */
@WebServlet("/circle") // formex.html파일의 action명과 같게 설정
public class circle extends HttpServlet {
	private static final long serialVersionUID = 1L;
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public circle() {
		super();
		// TODO Auto-generated constructor stub
	}
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) // ** request객체, response객체
			throws ServletException, IOException {
		System.out.println("doGet()..");

		request.setCharacterEncoding("UTF-8");

		String radius = request.getParameter("radius"); 
		double r = Double.valueOf(radius);  // String으로 받아오기 때문에 double형으로 형 변환
		System.out.println(radius); 
		getCircle c = new getCircle(r); 
		
		response.setContentType("text/html; charset=UTF-8"); // 한글 출력하기
		PrintWriter writer = response.getWriter();
		writer.println("<html><head></head><body>");
		writer.println("원의 반지름 : " + radius + "<br>");
		writer.println("넓이 : " + c.getArea() + "<br>");
		writer.println("</body></html>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("doPost()..");
		System.out.println(request.getRemoteAddr());
		System.out.println(request.getRemoteHost());

		request.setCharacterEncoding("UTF-8");
	}

}
  • getCircle.java
package edu.global.ex.shape;

public class getCircle {
	private double radius;
	
	public getCircle(double radius) {
		this.radius=radius;
	}
	
	public double getArea() {
		return radius * radius * Math.PI;
	}
}
  • 결과




📌 로또 번호 생성하는 서블릿 생성하기

  • lotto.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="lotto" method="get"> 
	<h1>로또 추첨</h1>
			<input type="submit" value="로또번호 생성"> 
	</form>
</body>
</html>
  • 결과


  • getLotto.java
package edu.global.ex.shape;

import java.util.HashSet;
import java.util.Set;

public class getLotto {

	public HashSet<Integer> getNumber() { // 중복이 나오지 않기 때문에 HashSet 사용하여 로또 번호 생성하는 것이 가장 편리
		HashSet<Integer> lottoNum = new HashSet<>();

		while (lottoNum.size() < 6) {
			int random = (int) ((Math.random() * 45) + 1);
			lottoNum.add(random);
		}
		System.out.println(lottoNum);
		return lottoNum;
	}

}
  • lotto.java
package edu.global.ex;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

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 edu.global.ex.shape.getLotto;

/**
 * Servlet implementation class rsp
 */
@WebServlet("/lotto") // formex.html파일의 action명과 같게 설정
public class lotto extends HttpServlet {
	private static final long serialVersionUID = 1L;
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public lotto() {
		super();
		// TODO Auto-generated constructor stub
	}
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) // ** request객체, response객체
			throws ServletException, IOException {
		System.out.println("doGet()..");
		
		request.setCharacterEncoding("UTF-8");
		getLotto l = new getLotto();
		
		response.setContentType("text/html; charset=UTF-8"); // 한글 출력하기
		PrintWriter writer = response.getWriter();
		writer.println("<html><head></head><body>");
		writer.println("로또번호 : " + l.getNumber() +"<br>");
		writer.println("</body></html>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("doPost()..");
		System.out.println(request.getRemoteAddr());
		System.out.println(request.getRemoteHost());

		request.setCharacterEncoding("UTF-8");
	}

}
  • 결과






📝 JSP (Java Server Page)

  • HTML코드에 JAVA를 삽입하여 동적 문서를 생성
  • Servlet 파일로 변환된다.



  • test.jsp 파일을 Servlet 파일로 변환한 test_jsp.java

📌 스크립트릿(scriptlet)

  • <% java 코드 기술 %>

🔎 구구단 생성하기

<%@ 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>
</head>
<body>

	<%  // 스크립트릿 문법
		for (int i = 2; i <= 9; i++) {
			for (int j = 1; j <= 9; j++) {
				out.println(i + " * " + j + " = " + (i * j));
				out.println("<br/>");
			}out.println("<hr/>");
			
		}
	%>
</body>
</html>
  • 결과




🔎 기본 문법

  • <%! code %>:변수 선언 문법
  • <%= code %>: 표현, 출력을 위한 문법
<%@ 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>
</head>
<body>
	<%!// 변수 선언 문법
	int i = 10;
	String str = "abc";

	private int sum(int a, int b) {
		return a + b;
	}%>
	<%
		out.println("<hr>");
	%>
	<%=i%><br />  // 표현, 출력을 위해 사용되는 문법
	<%=str%><br />
	<%=sum(1, 5)%>

</body>
</html>
  • 결과







2. SQL

📝형 변환 함수

  • 숫자, 문자, 날짜의 데이터형을 다른 데이터형으로 변환하는 함수

🔎 TO_CHAR

  • 날짜형 혹은 숫자형을 문자형으로 변환하는 함수
  • ✔ 사원들의 입사일을 출력하되, 요일까지 함께 출력하는 쿼리문
SELECT HIREDATE, TO_CHAR(HIREDATE, 'YYYY/MM/DD DAY') FROM EMP;
  • 결과

🔎 TO_DATE

  • 문자형을 날짜형으로 변환하는 함수
  • 기본 날짜 형식은 'YY/MM/DD' 형식으로 '년/월/일'을 나타낸다.
  • ✔ 1981년 2월 20일에 입사한 사원을 검색하는 쿼리문
select ename, hiredate from emp where hiredate=to_date(19810220,'YYYYMMDD');
select ename, hiredate from emp where hiredate='19810220';
select ename, hiredate from emp where hiredate='810220';
select ename, hiredate from emp where hiredate='81,02,20';
  • 결과

🔎 TO_NUMBER

  • ✔ '20,000'과 '10,000'의 차이를 알아보기 위해서 빼기(-)연산을 구하는 쿼리문
SELECT TO_NUMBER('20,000', '99,999')-TO_NUMBER('10,000', '99,999') FROM DUAL;
  • 결과




📝 NVL(Null Value) 함수

  • NULL을 0 또는 다른 값으로 변환하기 위해서 사용하는 함수
  • ✔ 연봉 계산을 하는 쿼리문
select ename,sal,comm, sal*12+nvl(comm,0) 연봉 from emp;
  • 결과
profile
개발 연습장

0개의 댓글