본문 바로가기
코리아 IT아카데미/grid·flex·mySql·jsp

16일차 | jsp1

by Sharon kim 2021. 12. 6.

다이나믹 웹 프로젝트 생성

com.company.aboutking 패키지 만들기

package com.company.aboutking;

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;

/**
 * Servlet implementation class MyServlet3
 */
@WebServlet("/test4")
public class exservlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public exservlet()
	{
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		request.setCharacterEncoding("utf-8");
		String food = request.getParameter("food");
		String recipe = request.getParameter("recipe");
		
		System.out.println(food);
		System.out.println(recipe);
		
		//response.setContentType("text/html; charset=utf-8");
		response.setContentType("application/json; charset=utf-8;");
		PrintWriter out = response.getWriter();
		boolean result = true;
		
		if (result)
		{
			
			out.print("{\"food\" : " + food + ", \"recipe\" : " + recipe + " }");
			out.println("{\"Success\"}");
			out.flush();
			
//			out.println("<html>");
//			out.println("<h1 style = 'color:yellowgreen'> Success </h1>");
//			out.println("</html>");
		}
		else
		{
			out.print("{\"food\" : " + food + ", \"recipe\" : " + recipe + " }");
			out.println("{\"Fail\"}");
			out.flush();
			
//			out.println("<html>");
//			out.println("<h1 style = 'color:yellowgreen'> Fail </h1>");
//			out.println("</html>");
		}
	}

}

MyServlet1

package com.company.aboutking;

import java.io.IOException;

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

//서블릿 , 동적으로 무언가를 만들어 줄 수 있는 파일 
                    //host 인터넷 망에 연결되어 있고 각각의 서버들이 웹서버라는 곳에 연결되어 있는 것
//1. 주소 : localhost:80/jspModel1/test1
@WebServlet("/test1") //web.xml 맵핑하지 않아도 된다.(편함)
public class MyServlet1 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
// 멤버변수 초기화 과정
	int a = 0;
	
 //2. 생명주기 life cycle

    @Override
    public void init() throws ServletException {
    	// TODO Auto-generated method stub
    	super.init();
    	 System.out.println("init~~");
    }
    @Override
    protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
    	// TODO Auto-generated method stub
    	super.service(arg0, arg1);
    	System.out.println("--------------------------------------");
    	System.out.println("service : 스크립트 릿 요소를 만들어 준다.");
    	System.out.println("service~~");
    }
    
    @Override
    public void destroy() {
    	// TODO Auto-generated method stub
    	super.destroy();
    	System.out.println("destroy~~");
    }
    
    public MyServlet1() {
        super();
        System.out.println("생성자~~");
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("--------------------------------------");
		System.out.println("doGet~~");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("--------------------------------------");
		System.out.println("doPost~~");
	}

}

MyServlet2

package com.company.aboutking;

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;

//localhost:80/jspmodel1/test2
@WebServlet("/test2")
public class Myservlet2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

    public Myservlet2() {
        super();

    }

    	//1. http 통신에 request 요청방식을 처리한다.
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("-------------------------------");
		System.out.println("get 방식으로 사용자가 연결을 요청했습니다.");
		
		//2.쿼리 스트링 방식을 처리한다.
		// http://localhost:8001/jspModel1/Myservlet2?name="홍길동"&age=20
		
		String name = request.getParameter("name");
		String age = request.getParameter("age");
		
		System.out.println("name : " + name);
		System.out.println("age : " + age);
		
		//값을 통해서 DB에 접근해서 (인설트, 찾기)
		
		//3. 응답하기
		// MINE 타입 이해하기
		// 어떻게 브라우저에게 해석해야하는 지 알려주는 것
		
		//3-1 json 형태로 돌려주기
		response.setContentType("application/json; charset=utf-8;");
//		response.setContentType("text/plain; charset=utf-8;");
//		response.setContentType("text/html; charset=utf-8;");
		
		//response 
		PrintWriter out = response.getWriter();
		//- html
//		out.println("<html>");
//		out.println("<head>");
//		out.println("</head>");
//		out.println("<body>");
//		
//		out.println("<div style='background-color:red;'>");
//		
//		out.println("<h1>응답을 돌려준다.</h1>");
//		
//		out.println("</div>");
//		
//		out.println("</body>");
//		out.println("</html>");
//		
//		out.flush();
		
		//- json
		// name/홍길동
		// {"name" : "홍길동", "age": 30}
		out.print("{\"name\":"+ name +", \"age\":"+ age +"}");
		out.flush();
		
	}
//http://localhost:8001/jspModel1/Myservlet2?name=야스오& age=30

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		doGet(request, response);
	}

}

MyServlet3







package com.company.aboutking;

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("/test3")
public class Myservlet3 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
 
    public Myservlet3() {
        super();
        
    }


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

//post방식 (암호화되서 사용자에게 요청값들이 날라온다.)
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//블로그 (음식 조리 방법)
		request.setCharacterEncoding("utf-8");
		String food = request.getParameter("food");
		String recipe = request.getParameter("recipe");
		
		System.out.println("food: " + food);
		System.out.println("recipe: " + recipe);
		
		//DB에 저장
		//저장 결과에 따라서 응답 결과를 다르게 보내줘야 한다.
		//저장 불가/ 저장 성공
		
//		response.setContentType("text/html; charset=utf-8");
		response.setContentType("application/json; charset=utf-8");
		PrintWriter out = response.getWriter();
		
		
//		boolean result = false;
		boolean result = true;
		
		
//		if(result) {
//			//성공에 대한 응답
//			out.println("<html>");
//			out.println("<h1 style='color:green'>저장성공</h1>");
//			out.println("</html>");
//		}else {
//			//실패에 대한 응답
//			out.println("<html>");
//			out.println("<h1 style='color:red'>저장실패</h1>");
//			out.println("</html>");
//		}
		out.print("{\"food\":"+ food +", \"recipe\":"+ recipe +"}");
		out.flush();
		//응답을 JSON형식으로 만들어서 보내주세요
	}

}

MyServlet3 풀이

package com.company.aboutking;

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;

/**
 * Servlet implementation class MyServlet3
 */
@WebServlet("/test4")
public class exservlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public exservlet()
	{
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		request.setCharacterEncoding("utf-8");
		String food = request.getParameter("food");
		String recipe = request.getParameter("recipe");
		
		System.out.println(food);
		System.out.println(recipe);
		
		//response.setContentType("text/html; charset=utf-8");
		response.setContentType("application/json; charset=utf-8;");
		PrintWriter out = response.getWriter();
		boolean result = true;
		
		if (result)
		{
			
			out.print("{\"food\" : " + food + ", \"recipe\" : " + recipe + " }");
			out.println("{\"Success\"}");
			out.flush();
			
//			out.println("<html>");
//			out.println("<h1 style = 'color:yellowgreen'> Success </h1>");
//			out.println("</html>");
		}
		else
		{
			out.print("{\"food\" : " + food + ", \"recipe\" : " + recipe + " }");
			out.println("{\"Fail\"}");
			out.flush();
			
//			out.println("<html>");
//			out.println("<h1 style = 'color:yellowgreen'> Fail </h1>");
//			out.println("</html>");
		}
	}

}

test3.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

 <h1>POST 방식으로 값 보내기</h1>
 
	<form action="test3" method="post">
	  <label for="fname">음식:</label>
	  <br>
	  <input type="text" id="fname" name="food"  value="된장찌개">
	  <br>
	  <label for="lname">조리방법:</label>
	  <br>
	  <input type="text" id="lname" name="recipe" value="">
	  <br>
	  <br>
	  <input type="submit" value="Submit">
	</form>

</body>
</html>

page_directive.jsp //이미지 x

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" %>
 <%@page import="java.util.*"%>
 <%@page session="true" %>
 <!-- 세션이란 : 두 대의 컴퓨터가 연결되어 있다는 논리적인 설정  -->
 <%@page buffer="8kb" %>
 <%@page autoFlush="true" %>
 <!--  -->
<%@page errorPage='error.jsp' %>  
<%@page trimDirectiveWhitespaces="true" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>페이지 지시자</h1>
	<%
	
		Date date = new Date();
	
		//int a = 10 / 0;
		
	%>
	
</body>
</html>

error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page isErrorPage = "true" %>    
    
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

	<h1> 에러 페이지 입니다.</h1>
	<a href="hello_world.jsp">hello world 페이지로 이동</a>
</body>
</html>

gugudan.jsp

<%@ 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>
	<h1>구구단 화면에 출력</h1>
	
	<%
		 for(int i = 2; i < 10; i ++){
			 
			 for(int j = 1; j < 10; j ++){
				 System.out.println(i + " * " + j + " = " + i * j);
			 }
			 System.out.println();
		 }
	%>
	
	<%
		 for(int i = 2; i < 10; i ++){
			 for(int j = 1; j < 10; j ++){
	 %>
	  		<%=i %>*<%=j %> = <%=i*j %>&nbsp;&nbsp;
	 <%
				 /*  System.out.println(i + " * " + j + " = " + i * j); */
			 }
		%>
		<br>
	<%
			 System.out.println();
		 }
	%>
</body>
</html>

hello_world.jsp

<%@ 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>
<!-- html 에 자바가 묻은 것 : JSP -->
<body>
		
		Hello world JSP ~
		
</body>
</html>

script1.jsp

<%@ 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>
		<%
		
			/*
			  service 메서드 에서 만들어 주는 요소
	
			*/
			//메서드 안에서 메서드를 사용하는 것과 마찬가지이다. 안됨
			/*public void intCrement(){
			
			} */
		%>
		<!-- 선언문 -->
		<%!
			public void intCrement(){
			
		}
		public int intAdd(int a, int b){
			return a + b;
		}
		%>
		
		<%!
			int a = 10; //멤버 변수
		%>
		<%!
			/* int a = 10; //멤버 변수 --> 멤버 변수 중복 선언과 같음 */
		%>
		<%
			int a = 100; //지역 변수 
		%>
		<%
		   /* int a = 1100; //지역 변수 --> 지역변수 중복 선언과 같음 */
		   //안녕하세요 
		%>
		<!-- 표현식에서 세미콜론은 사용 하지 않음 -->
		<div style="border:1px solid #ddd; padding:100px;width:200px;"></div>
		<%=intAdd(10, 30) %>
</body>
</html>

count.jsp

<%@ 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>
		<h1>1부터 10까지 화면에 출력</h1>
		
		<!-- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 -->
		<!-- 스트립트 릿 -->
		<%
			//1. 콘솔 창에 출력
			//1 ~ 10까지
			for(int i = 1; i <=10; i++){
				//System.out.println(i);
		%>
			<!-- 표현식 -->
			<%= i %><br> 
		<%	
			}
		%>
		
</body>
</html>

while.jsp

<%@ 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>
	<h1>While Example</h1>
	
	<%
	
		int number = 10;
		int count = 0;
		//count < number;
		/* while 문 작성해서 count 값을 브라우저에 출력 0 ~ 9, 0 다음 한 줄 띄움 */
		while(count < number){
			count++;
			System.out.println(count-1);
		}
	
	%>
</body>
</html>

 


API.txt

 

API 문서 작성

음식 레시피를 저장하는 서버 

요청 주소 : http://localhost:8001/jspModel1/test3

//POST / GET
요청방식 : POST

요청 데이터 타입(Content-type) : x-www.form.urlenencoded

요청 데이터
키 : food ,                   값(String) : "입력값(된장. 김치)"
키 : recipe                   값(String) : "입력값()"

응답결과 : 
성공 : 
1.text/plain (평문)
2.text/html
3.application/json
-{"success" : true"}
-{"success" : fail"}
4.다른 파일로 이동처리

실패 (json형식이라고 가정)

{"error":fail} - boolean
{error":fail"} - String
{"error":-1} - int


1. 페이지 지시자 개념

2.  jsp 스크립트 요소 

1. 스크립트 릿
<%
자바코드 삽입
%>
: 보통 service 메서드에서 코드를 만들어 준다. (마치 지역변수 개념)

2. 선언문(declaration)
<!%
자바코드 삽입
%>
: 멤버 변수처럼 자바 파일이 만들어 진다.

3. 표현식
<%=
자바코드 삽입
%>

4. 주석
//
/*

*/