1. 서블릿으로 파라미터를 보내는 form.html 페이지

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Form.html</title>
</head>
<body>
 
<!-- 필터는 post 방식으로 받을 때에만 적용됨. -->
<!-- form.do라는 서블릿으로 파라미터들을 보냄. -->
<form action="form.do" method="post" name="textform"> 
    Name : <input type="text" name="name"><br⁄> 
    <input type="submit" value="전송" name="submitbtn"> 
</form> 
 
</body>
</html>
cs

 

2. WEB-INF/web.xml 파일에 필터 매핑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" 
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
                             http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name>Archetype Created Web Application</display-name>
  
  <!-- 서블릿을 매핑하듯 필터도 같은 방식으로 WEB-INF/web.xml 파일에 매핑함. -->
  <!-- filter-name : 필터 클래스 파일 이름. -->
  <!-- filter-class : 필터 클래스 경로(애플리케이션 내에서의 절대 경로). -->
  <!-- init-param : 필터 클래스에서 사용하려는 파라미터의 이름, 값을 web.xml에서 미리 지정할 수 있음. -->
  <filter>
      <filter-name>HangulEncodingFilter</filter-name>
      <filter-class>com.filter.HangulEncodingFilter</filter-class>
      <init-param>
          <param-name>encoding</param-name>
          <param-value>UTF-8</param-value>
      </init-param>      
  </filter>
  
  <!-- url-pattern : 해당 애플리케이션 내에서 필터를 적용시키고자 하는 범위. -->
  <!--                 /* - 애플리케이션 내 모든 post 방식에서 적용(servlet, jsp 구분 없이). -->
  <!--                 /*.do - 애플리케이션 내 *.do로 이름을 지은 서블릿 post 메소드만 적용. -->
  <!-- servlet-name : 애플리케이션 내 특정 서블릿에만 적용할 때 씀.-->
  <filter-mapping>
      <filter-name>HangulEncodingFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>
cs

 

3. form.do 서블릿이 실행되기 전에 실행되는 filter 클래스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.filter;
 
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
 
/**
 * Servlet Filter implementation class ExampleBFilter
 */
public class HangulEncodingFilter implements Filter {
 
    //인코딩을 수행할 인코딩 캐릭터 셋 지정
    String encoding;
    
    //필터 설정 관리자
    FilterConfig filterConfig;
    
    /**
     * Default constructor. 
     */
    public HangulEncodingFilter() {
        // TODO Auto-generated constructor stub
    }
 
    /**
     * @see Filter#init(FilterConfig)
     */
    public void init(FilterConfig fConfig) throws ServletException {
        //초기화
        //getInitParameter() : web.xml에 초기화해서 지정한 파라미터 값을 불러오는 메소드. 
        this.filterConfig = fConfig;
        this.encoding = fConfig.getInitParameter("encoding");
        
//        System.out.println("debug > init %%%%%%%%%");
    }    
    
    /**
     * @see Filter#destroy()
     */
    //destroy : 웹 애플리케이션이 끝날 때 같이 끝남
    public void destroy() {
        
        this.encoding = null;
        this.filterConfig = null;
        
//        System.out.println("debug > destroy %%%%%%%%%%%");
    }
 
    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
                throws IOException, ServletException {
 
        //request.setCharacterEncoding("utf-8");
        
//        System.out.println("characterEncoding : " + request.getCharacterEncoding());
        
        if (request.getCharacterEncoding() == null) {
            if (encoding != null
                request.setCharacterEncoding(encoding);
        }
        
        chain.doFilter(request, response);
    }
}
cs

 

4. form.do 서블릿

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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;
 
@WebServlet("/form.do")
public class MyServlet extends HttpServlet {
    
    public MyServlet() {
        super();
    }
       
//    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
//                throws ServletException, IOException {
//        // TODO Auto-generated method stub
//    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
                throws ServletException, IOException {
        
        // 한글깨짐방지
        // 한글 필터를 쓰면 아래것은 쓸모없다
        // request.setCharacterEncoding("utf-8");
 
        // 아래 2줄 넣으면 한글 무조건 깨진다.
        // PrintWriter out = response.getWriter();
        // out.println("name : " + name);        
        String name = request.getParameter("name");
        
//        System.out.println("Debug> name : " + name);
        
        request.setAttribute("name", name);
        
        RequestDispatcher rd = request.getRequestDispatcher("result.jsp");    
        rd.forward(request, response);
    }
}
cs

 

5. 서블릿에서 파라미터를 받아 출력하는 jsp 페이지

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 
<%@ page isELIgnored="false" %>
    
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 
<!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>화면 결과 출력 예제</title>
</head>
<body>
    name : ${name}
</body>
</html>
cs

+ Recent posts