Web/기초

[WEB] Servlet & JSP 연동

hh_lin 2018. 12. 9. 21:57

Servlet & JSP 연동

  • 서블릿과 JSP는 상호 보완적인 관계를 가지고 있다.
  • 서블릿은 로직을 구현하기에 알맞지만, HTML을 출력하기엔 불편하다.                                                                                                                (JAVA파일이기 때문에 로직 구현이 쉬움. HTML 출력을 위해서는 out.print를 이용해야 하는 불편함이 있음.)
  • JSP는 로직을 구현하는 것은 불편하지만, HTML을 출력하기엔 편리하다.                                                                                                                (로직 구현은 스크립틀릿이나 선언문을 이용해야 함. HTML은 태그 이용해서 쉽게 입력 가능.)
  • 이러한 서블릿과 JSP를 잘 사용하기 위해 Servlet에서 프로그램 로직을 수행하고, 그 결과를 JSP에 포워딩하는 방법이 사용되게 되었다. 이를 Servlet과 JSP의 연동이라고 한다.

- LogicServlet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@WebServlet("/logic")
public class LogicServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    public LogicServlet() {}
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        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");
        requestDispatcher.forward(request, response);
    }
}
cs


- result.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
1. EL표기법으로 출력<br>
${v1} + ${v2} = ${result} <br><br>
 
2. 스클립틀릿과 표현식을 이용해 출력<br>
<%
    int v1 = (int)request.getAttribute("v1");
    int v2 = (int)request.getAttribute("v2");
    int result = (int)request.getAttribute("result");
%>
 
<%=v1%> + <%=v2 %> = <%=result %>
</body>
</html>
cs


http://localhost:9090/firstWeb/logic로 URL을 요청하게 되면 아래와 같이 result.jsp 페이지의 결과가 보여지게 된다.









참고자료

https://www.edwith.org