Servlet과 JSP
- Servlet은 자바 언어이기 때문에 JSP에 비해 프로그램 로직이 수행되기 유리하다. (JSP는 스크립트릿 등을 사용해야함)
- JSP는 필요한 HTML문을 그냥 입력하면 되기 때문에 결과를 출력하기 유리
- Servlet에서 로직 수행 + JSP에서 결과 출력 하는 것이 Servlet과 JSP의 연동이라고 함
실습
LogicServlet에서 1-100사이의 random값 2개와 그 합을 구해 result.jsp에 포워딩하기
1. LogicServlet 생성하기
▶ url mapping은 /logic
▶ method는 GET, POST 방식 모두 실행가능하게 하기 위해 service 메소드만 오버라이드
코드
package examples;
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;
/**
* Servlet implementation class LogicServlet
*/
@WebServlet("/logic")
public class LogicServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LogicServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
int v1 = (int)(Math.random() * 100) + 1;
int v2 = (int)(Math.random() * 100) + 1;
int result = v1 + v2;
request.setAttribute("v1", v1);
request.setAttribute("v2", v2);
request.setAttribute("result", result);
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/result.jsp"); // 요청할 URL주소
requestDispatcher.forward(request, response);
}
}
2. WebContent 폴더에 result.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>
<%
int v1 = (int)request.getAttribute("v1");
int v2 = (int)request.getAttribute("v2");
int result = (int)request.getAttribute("result");
%>
<%=v1 %> + <%=v2 %> = <%=result %>
</body>
</html>
3. 실행 결과
출처 : https://www.boostcourse.org/web316/lecture/16706/?isDesc=false
'Web' 카테고리의 다른 글
표현 언어 EL (0) | 2021.08.23 |
---|---|
Scope (0) | 2021.08.23 |
Redirect & Forward (0) | 2021.08.08 |
JSP 내장 객체 (0) | 2021.08.02 |
[eclipse] 자바 웹 어플리케이션 생성 (+ Finish버튼 비활성화 시) (0) | 2021.08.01 |