이클립스에서 어떻게 표현되는지 알아보기 위해서 소스코드로 표현을 해보자
01. HttpServlet클래스를 상속받는 MyServlet라는 클래스를 생성해보자
public class MyServlet extends HttpServlet {
}
02. request객체와 response객체를 담는 service() 메서드를 호출한다.
(이때, 서블릿이나 입출력시 발생할 수 있는 예외처리가 존재한다.)
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
}
✅ 03. MyServlet 클래스 위에 @WebServlet("/서블릿 요청주소") 애너테이션을 통해 좀 더 간단하게 서블릿 경로를 설정할 수 있다.
(어노테이션방식은 web.xml과 중복으로 작성할 수는 없다.)
@WebServlet("/hello2")
public class MyServlet2 extends HttpServlet {
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
PrintWriter out = arg1.getWriter();
out.println("Hello Servlet!!!");
}
}
PrintWriter는 브라우저 상에 출력할 수 있는 출력 스트림 객체를 생성한다.
web.xml에서 서블릿 등록을 한다.<servlet> // 해당 서블릿이름 <servlet-name>myServlet</servlet-name> // 서블릿 클래스 지정 <servlet-class>com.kh.web.servlet.MyServlet</servlet-class> </servlet>
- 해당 url(/hello)에 요청이 올때, 서블릿(myServlet)으로 요청하고 이 클래스(MyServlet)가 호출된다.
<servlet-mapping> // 서블릿 이름을 매핑 <servlet-name>myServlet</servlet-name> // 서블릿요청주소 매핑 <url-pattern>/hello</url-pattern> </servlet-mapping>
- response 객체에 응답을 보내줄 때, "UTF-8"로 한글 인코딩을 해준다.
arg1.setCharacterEncoding("UTF-8"); arg1.setContentType("text/html; charset=UTF-8");
- PrintWriter객체를 생성하여 브라우저에 출력까지 구현한다.
PrintWriter out = arg1.getWriter(); for (int i=0; i<100; i++) { out.println((i+1) + " 안녕 Servlet!!!<br/>"); } }
request.getParameter("(name속성값)");
만약, 동일한 name속성값이 여러개가 있으면 "배열의 형태"로 파라미터를 받아온다.
String[] 변수명 = request.getParameterValues("name속성값");pram값 예외상황
/hello?cnt=3: 문자열 "3" 값으로 처리
/hello?cnt=: 문자열 " " 값으로 처리
/hello?: 문자열이 null값으로 처리 (key값을 parse하지 않음)
/hello: 문자열이 null값으로 처리 (key값을 parse하지 않음)
// 초기값 세팅
int cnt = 100;
if (paramCnt != null && !paramCnt.equals("")) {
// 문자열을 숫자값으로 처리한다. )
cnt = Integer.parseInt(paramCnt);
}
// (호스트이름)/cnt로 이동
<a href="cnt">인사하기1</a>
// (호스트이름)/cnt?cnt=5로 이동
<a href="cnt?cnt=5">인사하기2</a>
1. GET
2. POST
클라이언트로부터 요청이 백엔드로 가기 전에 가로채서 서버로부터의 응답이 클라이언트로 보내지기 전에 조작하기 위해서 사용한다.
모든 요청에 대한 URL을 필터를 지나가게 한다.
@WebFilter("/*")
jakarta.servlet.Filter "API" 안에 존재하는 "Filter"라는 인터페이스를 상속받는다.public class CharacterEncodingFilter implements Filter{
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
// 필터에 대한 요청은 받아온다
arg0.setCharacterEncoding("UTF-8");
// filterchain으로 다음작업 진행 여부를 정한다.
arg2.doFilter(arg0, arg1);
// 필터에 대한 요청을 보내준다.
arg1.setCharacterEncoding("UTF-8");
arg1.setContentType("text/html; charset=UTF-8");
}
}
1XX(정보)
: 요청을 받았으며 프로세스를 계속한다.
2XX(성공)
: 요청을 성공적으로 받았으며 인식했고 수용하였다.
3XX(리다이렉션)
: 요청완료를 위해 추가작업조치가 필요하다.
4XX(클라이언트 오류)
: 요청의 문법이 잘못 되었거나 요청을 처리할 수 없다.
5XX(서버 오류)
: 서버가 명백히 유효한 요청에 대해 충족을 실패했다.
- 출처 : 위키백과