3.1 Kelas HttpServletResponse

Sawise nelpon service()metode servlet sampeyan, wadhah web bakal ngasilake respon kanggo klien adhedhasar file HttpServletResponse. Dadi yen sampeyan pengin piye wae pengaruhe respon kanggo klien, sampeyan kudu ngowahi obyek iki.

Tanggapan server kasusun saka telung bagean:

  • Baris status (contone: 200 OK)
  • Headers
  • Badan tanggapan

Lan metode kelas HttpServletResponseuga dipérang dadi 3 klompok? meh:

Metode Katrangan
1 void setStatus(int sc) Nyetel kode status respon.
2 void sendError(int sc) Ngirim kesalahan menyang klien kanthi kode sing ditemtokake.
3 void sendError(int sc, String msg) Ngirim kesalahan karo kode kasebut lan pesen menyang klien.
4 void addHeader(String name, String value) Nambahake header menyang dhaptar header respon.
5 void setHeader(String name, String value) Ngganti header ing dhaptar header respon.
6 boolean containsHeader(String name) Priksa manawa header wis ana.
7 void addCookie(Cookie cookie) Nambahake Cookie menyang respon.
8 void sendRedirect(String location) Ngalihake klien menyang URL sing beda.
9 String encodeRedirectURL(String url) Ngodhe URL sing ditemtokake kanggo digunakake ing metode sendRedirect.
10 String encodeURL(String url) Ngodhe URL sing ditemtokake, kalebu ID sesi.
sewelas void setContentType(String type) Nyetel MimeType asil.
12 void setContentLength(int len) Nyetel dawa awak respon.
13 void setCharacterEncoding(String charset) Nyetel set enkoding respon.
14 void setBufferSize(int size) Nyetel ukuran buffer kanggo awak respon.
15 boolean isCommitted() Priksa yen buffer wis ditulis kanggo respon.
16 void flushBuffer() Nulis isi buffer kanggo nanggepi.
17 void reset() Ngreset kabeh data sing disimpen ing buffer, header lan kode respon.
18 void resetBuffer() Mbusak buffer respon.

Cara ing kene cukup sepele. Nanging aku bakal menehi sawetara sorotan ing ngisor iki.

Buffer . Tanggepan servlet sampeyan ditulis menyang buffer, ora langsung dikirim menyang pangguna. Mulane, ing sawetara tataran (yen, contone, ana kesalahan), sampeyan bisa ngreset (mbusak) kabeh sing ditulis ing buffer. Sampeyan bisa malah nelpon reset () cara lan mbusak ora mung isi buffer, nanging uga header karo kode respon.

3.2 pangalihan ()

Titik penting kapindho yaiku pangalihan. Yen servlet sampeyan mutusake kanggo ngarahake klien menyang URL liyane, mula sampeyan kudu ngirim URL iki menyang klien. Iki bisa ditindakake kanthi nggunakake sendRedirect.

Nanging ana nuansa penting. URI bisa ngemot sawetara karakter sing luwih akeh tinimbang sing diidini ing awak respon. Mula, URL kudu dienkode dhisik dadi set karakter sing bener sadurunge nelpon metode sendRedirect(). Ana cara khusus kanggo iki encodeRedirectURL(String url). Nggunakake.

Tuladha pangalihan:


public class RedirectServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String newUrl = "http://google.com?q=Learn to google!";
        String redirectUrl = response.encodeRedirectURL(newUrl);
        response.sendRedirect(redirectUrl);
    }
}

3.3 metode getWriter().

Lan saiki kita bakal sinau carane nulis teks minangka badan respon. Kanggo nindakake iki, kelas HttpServletResponseduwe cara khusus getWriter()sing ngasilake obyek PrintStream. Yen ana sing lali, iki jinis lapangan kanthi jeneng System.out.

Kanggo nulis sawetara teks minangka respon servlet, sampeyan kudu:

  • Entuk obyek PrintStream kanthi nelpon response.getWriter().
  • Tulis apa wae sing perlu kanggo obyek PrintStream (kabeh data bakal ditulis menyang buffer).
  • Kirimi buffer menyang pangguna kanthi nelpon metode close()ing PrintStream.

Ayo nulis servlet sing nambah rong nomer alan bngasilake asil menyang pangguna:



public class CalculatorServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
         // Getting the parameter “a” and “b” from request
        String a = request.getParameter("a");
        String b = request.getParameter("b");
 
        try {
            // Convert strings to numbers and calculate sum
            int sum = Integer.parseInt(a) + Integer.parseInt(b);
 
            // Print HTML as a response for browser
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
 
            out.println("<html>");
            out.println("<head> <title> CalculatorServlet </title> </head>");
            out.println("<body>");
            out.println("<h1> Sum == " + sum + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }
}