본문 바로가기

JSP, Servlet/JSP, Servlet 기초

[JSP/Servlet] 자바 코드와 표현언어(EL)식 비교 - 덧셈표현하기(Servlet 이용)

자바 코드와 표현언어(EL)식 비교

표현 언어로 두 수의 합 구하기
 숫자 num1과 num2를 입력 받아 addition.jsp 에서 더한 결과를 출력한다.

 addition.jsp 덧셈 결과는 자바코드와 표현언어 2가지로 작성한다.

 

<addForm.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>
	<form method="GET" action="AddtionServlet">
		<table>
			<thead>
				<h3>로그인</h3>
			</thead>
			<tr>
				<td>숫자 1</td>
				<td><input type="text" id="num1" name="num1"></td>
			</tr>
			<tr>
				<td>숫자 2</td>
				<td><input type="text" id="num2" name="num2"></td>
			</tr>
			<tr>
				<td><input type="submit" value="전송"></td>
			</tr>
		</table>
	</form>
</body>
</html>

 

 

<AdditionServlet.java>

package unit04;

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 AddtionServlet
 */
@WebServlet("/AddtionServlet")
public class AdditionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AdditionServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int num1 = Integer.parseInt(request.getParameter("num1"));
		int num2 = Integer.parseInt(request.getParameter("num2"));
		
		int add = num1 + num2;
		
		request.setAttribute("num1", num1);
		request.setAttribute("num2", num2);
		request.setAttribute("add", add);
		
		RequestDispatcher dispatcher = request.getRequestDispatcher("05_addtion.jsp");
		dispatcher.forward(request, response);
	}

	/**
	 * @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);
	}

}

 

 

<addition.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>
스크립트를 이용한 방식 : <br>
	<%
		int num1 = (Integer)request.getAttribute("num1");
	int num2 = (Integer)request.getAttribute("num2");
	int add = (Integer)request.getAttribute("add");
	%>
	
	<%=num1 %> + <%=num2 %> = <%=add %><br><hr>
	EL을 이용한 방식<br>
	${num1 } + ${num2 } = ${add }<br>

</body>
</html>

 

728x90
반응형