본문 바로가기

Application/JSP Server

[JSP] 3. 서블릿 만들기

반응형
  • URL Mapping
    • 서블릿 동작시키기 위해 클래스명 대신 문자열을 서브릿 클래스와 매핑
    • 실제 서블릿 클래스를 공개하지 않기 위해
    • URL pattern과 서블릿 클래스 이름을 매핑

서블릿 클래스

public class AdditionServlet03 extends HttpServlet

 

두 수에 대한 합을 구하여 결과 출력 [일반]

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int num1 =20;
		int num2 =10;
		int add = num1+num2;
		PrintWriter out =response.getWriter();
		out.println("<html><head><title>Addition</title></head>");
		out.println(num1+ "+"+num2+"="+add);
		out.println("</body>");
		out.println("</html>");// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Addition</title>
</head>
<body>
<% 
int num1= 20;
int num2=10;
int add = num1 +num2;
%>

<%=num1 %>+<%=num2 %>=<%=add %>

</body>
</html>

두 수에 대한 합을 구하여 결과 출력 [서블릿과 JSP의 분리]

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int num1=20;
		int num2=10;
		int add=num1+num2;
		request.setAttribute("num1", num1);
		request.setAttribute("num2", num2);
		request.setAttribute("add", add);
		
		RequestDispatcher dispatcher= request.getRequestDispatcher("addition03.jsp");
		dispatcher.forward(request, response);// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Addition</title>
</head>
<body>
${num1 }+${num2 }=${add }

</body>
</html>

 

컨텐츠 타입

response.setContentType("text/html; charset=UTF-8");
response.setContentType("text/html; charset=EUC-KR");

->HttpServletResponse 객체로 setContentType()을 호출해 응답 방식 결정


  • 쿼리 스트링
    • 서블릿 클래스에서 사용자가 입력한 값을 얻어오는 방법
ParamServlet? id=pinksung&age =15

->?이름=값&이름=값 

->pinksung [사용자가 입력한 값]을 얻어오기 위해 이름(id)를 알아야 한다.

 

폼 양식

<form method="get/post" action="호출할서블릿">

 

텍스트 박스

<input type = "text" name="텍스트 박스 이름">

 

  • 요청 객체(request)와 파라미터 관련 메소드(getParameter)
    • request객체의 getParameter() 메소드로 <input> 태그를 통해 입력값 읽어오기
    • name속성값을 getParameter()의 매개변수로
String id=req.getParameter("id");
<input type="text" name="id">
id=pinksung

-> pinksung은 String 변수 id에 저장

-> getParameter()의 파라미터 값은 항상 문자열이므로 데이터 형 변환

int age=Integer.parseInt(request.getParameter("age"));

 -> parseInt : String형을 int형으로 변환 메소드


 

반응형

'Application > JSP Server' 카테고리의 다른 글

[JSP] 액션 태그  (0) 2021.04.01
[JSP] 3-1. 텍스트 박스에 입력된 값 얻어오기  (0) 2021.03.31
[JSP] 2. JSP & Servlet  (0) 2021.03.31
JSP 공부하기 2  (0) 2021.03.31
JSP 공부하기  (0) 2021.03.27