2.1 Petunjuk JSP
Amarga kita nemokake manawa file JSP diowahi dadi servlet biasa, mula sampeyan bisa nulis kode Java normal ing kono. Lan ing kode Jawa iki, sampeyan bisa nggunakake macem-macem kelas (Math saka conto). Iki malah luwih apik! Nanging kita bisa ndeleng manawa kabeh kode wis dipindhah menyang doGet()
cara servlet. Lan iki langsung nuwuhake sawetara pitakonan:
- Kepiye carane supaya kode kasebut dipindhah menyang metode kasebut
doPost()
? - Kepiye cara nambah kode dhewe menyang metode kasebut
init()
? - Carane ing pungkasan kanggo ndhaftar impor kelas?
Pitakonan sing apik, lan, mesthi, duwe jawaban - arahan JSP. Kabeh kode non-HTML ing JSP kudu dilampirake ing kurung khusus <%
lan %>
. Kabeh arahan JSP diwenehake dening cithakan:
<%@ directive %>
Iki minangka dhaptar atribut arahan kaca sing paling populer:
Tuladha | Katrangan | ||
---|---|---|---|
1 | ngimpor | <%@ page import="java.util.Date" %> |
Ngimpor kelas |
2 | jinis konten | <%@ page contentType=text/html %> |
Nyetel contentType |
3 | ngluwihi | <%@ page extends="Object" %> |
Sampeyan bisa nyetel kelas dhasar |
4 | info | <%@ page info="Author: Peter Ivanovich; version:1.0" %> |
Nyetel data kanggo getServletInfo() |
5 | panyangga | <%@ page buffer="16kb" %> |
Nyetel ukuran buffer respon |
6 | basa | <%@ page language="java" %> |
Nemtokake basa, standar yaiku Jawa |
7 | digatekake | <%@ page isELIgnored="true" %> |
Ngidini sampeyan mateni skrip EL |
8 | ikuThreadSafe | <%@ page isThreadSafe="false" %> |
Titik kanggo threadsafe |
9 | autoFlush | <%@ page autoFlush="false" %> |
Ngatur buffer nyerat |
10 | sesi | <%@ page session="false" %> |
Sampeyan bisa mateni sesi kanggo kaca |
sewelas | pageEncoding | <%@ page pageEncoding="UTF-8"%> |
Sampeyan bisa nyetel enkoding kaca |
12 | kesalahanPage | <%@ page errorPage="errorpage.jsp" %> |
Sampeyan bisa nyetel kaca kesalahan |
2.2 Impor
Ayo nambah sawetara impor menyang file JSP kanggo seneng-seneng lan nemtokake kelas dhasar.
Tuladha file JSP:
<%@ page import="java.util.Date" %>
<%@ page import="java.lang.Math" %>
<%@ page extends="com.codegym.MyHttpServlet" %>
<html>
<body>
<%
double num = Math.random();
if (num > 0.95) {
%>
<h2>You are lucky, user!</h2><p>(<%= num %>)</p>
<%
}
%>
</body>
</html>
Lan iki sing bakal teka:
import java.util.Date;
import java.lang.Math;
public class HelloServlet extends com.codegym.MyHttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
PrintWriter out = response.getWriter();
out.print("<html> ");
out.print("<body> ");
double num = Math.random();
if (num > 0.95) {
out.print("<h2> You're lucky, user! </h2> <p> (" + num + ")</p> ");
}
out.print("</body> ");
out.print("</html> ");
}
}
Nyambut gawe. apik tenan!