폼 데이터 처리

♣ contact.html
<form method="post" action="/servlet/Contact">
이름 <input type="text" name="name" /><br />
메일 <input type="text" name="email" />
...

♣ Contact.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Contact extends HttpServlet {

    // get 요청시
    public void doGet(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
        process(req, res);
    }
    // post 요청시
    public void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
        process(req, res);
    }

    public void process(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {

 

        // client에 전송된 요청의 MIME charset을 지정
        req.setCharacterEncoding("UTF-8");

        // client에 전송될 응답의 content-type을 지정 (getWriter 전에 호출되어야 함)
        res.setContentType("text/html;charset=UTF-8");
        // client에 character text를 전송할 수 있도록 PrintWriter 객체 반환
        PrintWriter out = res.getWriter();
                
        // 요청 파라미터의 값을 문자열로 반환
        String name = req.getParameter("name");
        String email = req.getParameter("email");

        out.println("<a href='mailto:" + email + "'>" + name + "</a>");
    }
}


HttpServletRequest 객체의 getParameter 메소드로 GET 이나 POST 로 전달된 파라미터 값을 전달 받을 수 있음.

 

♣ 컴파일 - javac Contact.java


WRITTEN BY
손가락귀신
정신 못차리면, 벌 받는다.

,