③ JSP프로젝트-2 jsp파일로 1~20까지 더한수를 출력하기, Servlet파일로 출력하기
먼저 jsp파일을 만듭니다.
1. 자신이 만들었던 프로젝트명에 오른쪽 클릭을 하면 new를 보시면 jsp라고 있습니다 해당을 클릭하고 이름을 지정해줍니다.
2. finish를 누르게 되면 이제 WebContent 아래에 jsp파일이 생성되게 됩니다.
3. 이제 코드를 적어주면됩니다.
Gaesan.jsp |
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>1~20까지 계산하기</title>
</head>
<body>
<%
int total = 0;
for (int cnt = 1; cnt <= 20; cnt++)
total += cnt;
%>
1부터 20까지 더한 값은?
<%=total%>
</body>
</html>
이코드를 쓰시면 1부터 20까지 더한 값은? 210 이라는 웹에서의 결과를 얻을 수 있습니다.
이제 Servlet파일로 출력해 보겠습니다.
Servlet파일은 JSP파일을 만든것 처럼 NEW-Servlet를 누르시고 만드시면 됩니다.
servlet 파일은 jsp파일과는 다르게 java Resources밑에 파일이 생기게 됩니다.
GaesanServlet.jsp |
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 GaesanServlet
*/
@WebServlet("/GaesanServlet")
public class GaesanServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public GaesanServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html; charset=euc-kr");
int total = 0;
for (int cnt = 1; cnt <= 20; cnt++)
total += cnt;
PrintWriter out = response.getWriter();
out.println( "<HTML>");
out.println( "<HEAD><TITLE>1~20계산하기</TITLE></HEAD>");
out.println( "<BODY>");
out.printf( "1 + 2 + 3 + ... + 20 = %d ", total);
out.println( "</BODY> ");
out.println( "</HTML> ");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
이코드를 쓰시면 1 + 2 + 3 + ... + 20 = 210 이라는 웹에서의 결과를 얻을 수 있습니다.
Servlet 방법으로 하는데 한글이 깨지신다면
response.setContentType("text/html; charset=euc-kr");를 입력시켜 주시면 한글 깨짐을 방지 할 수 있습니다.