Servlet Basics اساسيات Servlet
The
goal of this lab is to exercise basic features of Servlet leveraging
NetBeans IDE. You are going to build, run, and modify
ServletExamples sample application using NetBeans. والهدف من هذا
المختبر هو التعرف على السمات* الاساسية للServlet من خلال بيئة التطوير
المتكاملة* Netbeans. ستقوم ببناء و تشغيل وتعديل أمثلة تطبيقية ServletExamples
باستخدام عينة Netbeans. Expected duration: 60 minutes (excluding homework) المدة المتوقعة : 60 دقيقة (باستثناء العمل المنزلي)
Software Needed البرامج اللازمة
Before you begin, you need to install the following software on your computer. قبل أن نبدأ، أنت بحاجة الى تثبيت البرامج التالية على جهاز الكمبيوتر الخاص بك.
- 4002_servletbasics.zip ( download ) 4002_servletbasics.zip (تنزيل)
- The zip file contains this document and the lab contents الملف المضغوط يحتوي على النسخة الأصلية لهذه الصفحة و المكتوبة باللغة الأنجليزية
- Download it and unzip in a directory of your choice تحميل وunzip في دليل من اختيارك
OS platforms you can use اذا اردت يمكنك استخدام المنصات التالية
- Windows Windows
- Solaris x86, Solaris Sparc سولاريس x86 ، سولاريس SPARC
- Linux لينكس
- Mac OS X ماكنتوش
Change Log غير المفتاح
- Oct. 12th, 2006: Homework is added تشرين الاول / اكتوبر 12th ، 2006 : تم اضافة الواجبات المنزلية
- Nov. 3rd, 2006: The hyperlink to J2EE 1.4 JavaDoc is corrected تشرين الثاني / نوفمبر 3rd ، 2006 : تم تصحيح وصلة الدخول الى J2EE 1.4 javadoc
- April 9th, 2008: NetBeans 6.0 is used في التاسع من أبريل الجارى ، 2008 : تم استخدام Netbeans 6.0
- June 10th, 2008: NetBeans 6.1 is used يونيو 10th ، 2008 : تم استخدام Netbeans 6.1
Lab Exercises تمارين المختبر
Exercise 1: Build and run HelloWorld Servlet Application تمرين 1 : بناء وتشغيل تطبيق HelloWorld Servlet
In this exercise, you are going to open "hello2" NetBeans project, which is provided as part of the hands-on lab zip file. في هذا التمرين، ستقوم بفتح مثال لمشروع Hello2 Netbeans الموجود في الملف المضغوط الخاص بهذا المختبر.
(1.1) Open, build, and run "hello2" sample Servlet application (1.1) فتح وبناء وتشغيل لمثال تطبيق hello2 Servlet
0. Start NetBeans IDE. إفتح بيئة التطوير المتكاملة Netbeans
1. Open hello2 NetBeans project. إفتح مشروع Hello2 Netbeans
- Select File -> Open Project (Ctrl+Shift+O) . اختر File --> Open Project (Ctrl+Shift+O) . The Open Project dialog box appears. يظهر مربع Open Project .
- Browse down to
<LAB_UNZIPPED_DIRECTORY>/servletbasics/samples directory. استعرض محتويات الدليل lab_unzipped_directory>/ servletbasics / samples >
- Windows: If you unzipped the 4002_servletbasics.zip file under C:\ directory, the directory to which you want to browse down should be C:\servletbasics\samples. ويندوز : اذا قمت بفك الملف المضغوط 4002_servletbasics.zip في الدليل \ : C فسيكون الملف المعني هو C : \ servletbasics \ samples.
- Solaris/Linux: If you unzipped the 4002_servletbasics.zip file under $HOME directory, the directory to which you want to browse down should be $HOME/servletbasics/samples. سولاريس / لينكس : اذا قمت بفك الملف المضغوط 4002_servletbasics.zip في الدليل الرئيسي HOME$ فسيكون الملف المعني هو HOME / servletbasics / sample$.
- Select hello2 . اختر hello2.
- Click Open Project . The hello2 project node appears under Projects tab window. انقر فوق Open Project. عقدة مشروع hello2 تظهر تحت نافذة Projects.
2 Build and run hello2 project. 2 بناء وتشغيل المشروع hello2.
- Right-click hello2 project and select Run . انقر بالزر الايمن واختر مشروع hello2 ثم إضغط تنفيذ.
- Browser gets displayed. Type your name in the input form field and click Submit button. يظهر المتصفح, اكتب اسمك في مجال المدخلات وانقر على زر Submit.

Figure-1.12: Running hello2 projectالرسم - 1.12 : تشغيل مشروع hello2
(1.2) Modify the application to display hobby (1.2) تعديل تطبيق لعرض الهوايه
In this step, you are going to modify the application to ask a hobby of a user and then redisplay it. في هذه الخطوة، ستقوم بتعديل التطبيق و ذلك بأن تسأل المستخدم عن هوايته وبعد ذلك ستقوم بإعادة تشغيل التطبيق.
1.
Double click GreetingServlet.java under hello2->Source Packages->servlets to open in the source editor. انقر نقرأ مزدوجا فوق greetingservlet.java تحت hello2 -> Source Packages -> Servlets لفتح محرر المصدر. 2.
Modify GreetingServlet.java as shown in Code-1.13 below. تعديل greetingservlet.java على النحو المبين في المصدر - 1.13 ادناه.
package servlets;
import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* This is a simple example of an HTTP Servlet. It responds
to the GET
* method of the HTTP protocol.
*/
public class GreetingServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setBufferSize(8192);
PrintWriter out =
response.getWriter();
// then write the data of
the response
out.println("<html>" +
"<head><title>Hello</title></head>");
// then write the data of
the response
out.println("<body
bgcolor=\"#ffffff\">" +
"<img src=\"duke.waving.gif\" alt=\"Duke waving\">" +
"<h2>Hello,
my name is Duke. My hobby is Golf. What are your name and hobby?</h2>"
+
"<form method=\"get\">" +
"<input type=\"text\" name=\"username\" size=\"25\">" +
"<p></p>" +
"<input
type=\"text\" name=\"hobby\" size=\"25\">" + "<p></p>" +
"<input type=\"submit\" value=\"Submit\">" +
"<input type=\"reset\" value=\"Reset\">" + "</form>");
String username =
request.getParameter("username");
if ((username != null)
&& (username.length() > 0)) {
RequestDispatcher dispatcher =
getServletContext()
.getRequestDispatcher("/response");
if
(dispatcher != null) {
dispatcher.include(request, response);
}
}
out.println("</body></html>");
out.close();
}
public String getServletInfo() {
return "The Hello servlet
says hello.";
}
}
|
Code-1.13: Modified GreetingServlet.java مصدر - 1.13 : تعديل greetingservlet.java 3.
Modify ResponseServlet.java under hello2->Source Packages->servlets as shown in Code-1.14 below. تعديل responseservlet.java تحت hello2 -> Source Packages -> Servlets على النحو المبين في المصدر - 1.14 ادناه.
package servlets;
import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* This is a simple example of an HTTP Servlet. It responds
to the GET
* method of the HTTP protocol.
*/
public class ResponseServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out =
response.getWriter();
// then write the data of
the response
String username =
request.getParameter("username");
if ((username != null)
&& (username.length() > 0)) {
out.println("<h2>Hello, " + username + "!</h2>");
}
String hobby =
request.getParameter("hobby");
if ((hobby != null) && (hobby.length() > 0)) {
out.println("<h2>Your hobby is " + hobby + "!</h2>");
}
}
public String getServletInfo() {
return "The Response servlet
says hello.";
}
}
|
Code-1.14: Modified ResponseServlet.java مصدر - 1.14 : تعديل responseservlet.java 4.
Right-click hello2 project and select Run
. This will compile the servlet code, create a hello2.war file,
deploys it on a deployment platform (GlassFish v2 in this case) and
then pop up a browser to access it. انقر بالزر الايمن واختر مشروع hello2 ثم إضغط على تنفيذ.
فإن هذا الأمر سوف يقوم بتجميع (compile) مصدر Servlet و يقوم بإنشاء ملف hello2.war ثم يقوم بنشره على منصة النشر (deployment platform) (في هذا المثال منصة النشر هي glassfish V2) وبعد ذلك يتم عرضها على المتصفح. 5.
Type in a name and hobby into the blank fields. Clock Submit button. أكتب الاسم و الهوايه في المجالات الفارغه. إضغط على زر Submit 6.
Observe the name and hobby you typed are displayed. لاحظ كيف تم عرض الاسم و الهوايه اللذان قمت بإدخالهما. (Figure-1.15 below) (الشكل ادناه - 1.15)
Figure-1.15: Result of running the applicationالرسم - 1.15 : نتيجة لتشغيل التطبيق (1.3) Display context sensitive Javadoc on Java EE class (1.3) عرض javadoc المتأثر بسياق أفسام J2EE
1.
Right click HttpServlet and select Show Javadoc. انقر بزر الفأرة الايمن على HttpServlet ثم إضغط على Show Javadoc.
Figure-1.31: Show Javadoc الشكل - 1.31 : عرض Javadoc 2.
Observe that the Javadoc of the HttpServlet gets displayed. نلاحظ ظهور Javadoc الخاص ب HttpServlet
Figure-1.32: Javadoc of HttpServletالرسم - 1.32 : Javadoc الخاص ب HttpServlet
Summary خلاصة
In this exercise, you have built and run a simplest possible Web application that contains two servlets. وفي هذه التمرين، قمتم ببناء وتشغيل تطبيق شبكة من أبسط ما يكون و هذا التطبيق يحتوي على two Servlets.
return to the top عودة الى الاعلى
Exercise 2: Build and run "Servlet Examples" sample application تمرين 2 : بناء وتشغيل تطبيق بسيط "Servlet Examples"
In this exercise, you are going to build and run " ServletExamples " sample application that comes with NetBeans. وفي هذه التمرين، سنقوم ببناء وتشغيل تطبيق بسيط "ServletExamples" و الذي يأتي مع Netbeans.
(2.1) Build and run "Servlet Examples" sample application (2.1) بناء وتشغيل تطبيق بسيط "Servlet Examples"
1. Create a new NetBeans project from the sample app that comes with NetBeans انشاء مشروع Netbeans جديد من بين المشاريع البسيطة الموجودة ضمن إصدار Netbeans
- Select File -> New Project (Ctrl+Shift+N) . (Figure-1.10 below) The New Project dialog box appears. اختر File --> New Project (Ctrl+Shift+N). لاحظ ظهور مربع New Project.(الشكل أدناه - 1.10 )
-
Expand Samples under Categories pane. إفتح دليل Samples تحت لوحة Categories.
- Select Web under Categories and Servlet Examples under Projects . اختر Web تحت اطار Categories و Servlet Examples تحت اطار Projects. Click Next . انقر فوق التالي. (Figure-2.10 below) (الشكل ادناه - 2.10)
Figure-2.10: Create a new NetBeans projectالرسم - 2.10 : انشاء مشروع جديد Netbeans 2.
Accept the default project name and other values and click Finish . تقبل إسم المشروع المقترح ثم انقر فوق إنهاء.
Figure-2.11: Give a project nameالرسم - 2.11 : اعطاء اسم للمشروع 3.
Right click ServletExamples project node and select Run . انقر بزر الفأرة الايمن على عقده المشروع ServletExamples ثم اختر تنفيذ. 4.
Observe that the browser gets displayed. نلاحظ ظهور المتصفح. 5.
Click Execute to execute the " Hello World " servlet code. انقر فوق Execute لتنفيذ مصدر servlet "Hello World". (Figure-2.12 below) (الشكل ادناه - 2.12) 6.
Click Source to see the corresponding source code. انقر فوق Source لترى المصدر الخاص به. (Figure-2.12 below) (الشكل ادناه - 2.12)
Figure-2.12: ServletExamples applicationالرسم - 2.12 : تطبيق ServletExamples 7.
Try to execute and see the sources of Request Info , Request Headers and Request Parameters . جرب تنفيذ و رؤية مصدر كل من Request Info و Request Headers و Request Parameters (2.2) Modify "Hello World" part of the application (2.2) تعديل جزء من تطبيق "Hello World"
1.
Modify HelloWorldExample.java under ServletExamples->Source Packages-><default package> as shown in Code-2.20 below. The code fragments that need to be added are highlighted in bold and blue colored font. قم بتعديل HelloWorldExample.java تحت servletexamples -> Source Packages -> <defaultpackage> على النحو المبين في المصدر - 2.20 ادناه. اجزاء المصدر التي تحتاج الى اضافة هي التي تبرز واضحة بالون الازرق.
public class HelloWorldExample
extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException,
ServletException
{
ResourceBundle rb =
ResourceBundle.getBundle("LocalStrings",request.getLocale());
response.setContentType("text/html");
PrintWriter out =
response.getWriter();
out.println("<html>");
out.println("<head>");
String title =
rb.getString("helloworld.title");
out.println("<title>" +
title + "</title>");
out.println("</head>");
out.println("<body
bgcolor=\"white\">");
// note that all links are created to be relative.
this
// ensures that we can move the web application that
this
// servlet belongs to to a different place in the url
// tree and not have any harmful side effects.
// XXX
// making these absolute
till we work out the
// addition of a PathInfo
issue
out.println("<a
href=\"../helloworld.html\">");
out.println("<img
src=\"../images/code.gif\" height=24 " +
"width=24 align=right border=0 alt=\"view code\"></a>");
out.println("<a
href=\"../index.html\">");
out.println("<img
src=\"../images/return.gif\" height=24 " +
"width=24 align=right border=0 alt=\"return\"></a>");
out.println("<h1>" +
title + "</h1>");
out.println("my
own message gets displayed here");
out.println("</body>");
out.println("</html>");
}
}
|
Code-2.20: Modified HelloWorldExample.java مصدر - 2.20 : تعديل HelloWorldExample.java 2.
Right click ServletExamples project node and select Run . انقر بزر الفأرة الايمن على عقده الشروع ServletExamples ثم اختر تنفيذ. 3.
Click Execute to execute the " Hello World " servlet code. انقر فوق Execute لتنفيذ مصدر servlet "Hello World" 4.
Observe that the browser gets displayed as shown in Figure-2.21 below. نلاحظ ظهور المتصفح كما هو مبين في الشكل ادناه - 2.21.
Figure-2.21: Result of running the applicationالرسم - 2.21 : نتيجة تيفيذ التطبيق (2.3) Modify "Request Info" Example part of the application (2.3) تعديل جزء من تطبيق"Request Info"
In this step, you are going to display various information of the HttpRequest object, which reflects Http Request from the client. في هذه الخطوة ، سنقوم بعرض معلومات متنوعة عن الكائن HttpRequest، الامر الذي يعكس بروتوكول انتقال النص المتشعب Http بطلب من العميل. 1. Move your cursor to the HttpServletRequest string and right click and select Show Javadoc . 1. قم بتحريك المؤشر الى عبارة HttpServletRequest وانقر فوقها بزر الفأرة الايمن واختر Show Javadoc. (Figure-2.30 below) (الشكل ادناه - 2.30)
Figure-2.30: Show Javadoc of HttpServletRequest الشكل - 2.30 : عرض Javadoc الخاص ب HttpServletRequest 2.
The JavaDoc of the HttpServletRequest class gets displayed in a browser. ظهور Javadoc الخاص ب HttpServletRequest على المتصفح. (Figure-2.31 below) (الشكل ادناه - 2.31)
Figure-2.31: Javadoc of HttpServletRequestالرسم - 2.31 : Javadoc الخاص ب HttpServletRequest 3.
Modify RequestInfoExample.java under ServletExamples->Source Packages-><default package> as shown in Code-2.32 below. The code fragments that need to be added are highlighted in bold and blue colored font. قم بتعديل RequestInfoExample.java تحت servletexamples -> Source Packages -> <defaultpackage> على النحو المبين في المصدر - 2.32 ادناه. اجزاء المصدر التي تحتاج الى اضافة تبرز واضحة باللون الازرق.
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import util.HTMLFilter;
/**
* Example servlet showing request information.
*
* @author James Duncan Davidson <duncan@eng.sun.com>
*/
public class RequestInfoExample extends HttpServlet {
ResourceBundle rb =
ResourceBundle.getBundle("LocalStrings");
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out =
response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<head>");
String title =
rb.getString("requestinfo.title");
out.println("<title>"
+ title + "</title>");
out.println("</head>");
out.println("<body
bgcolor=\"white\">");
// img stuff not req'd for
source code html showing
// all links relative!
// XXX
// making these absolute
till we work out the
// addition of a PathInfo
issue
out.println("<a
href=\"../reqinfo.html\">");
out.println("<img
src=\"../images/code.gif\" height=24 " +
"width=24 align=right border=0 alt=\"view code\"></a>");
out.println("<a
href=\"../index.html\">");
out.println("<img
src=\"../images/return.gif\" height=24 " +
"width=24 align=right border=0 alt=\"return\"></a>");
out.println("<h3>" +
title + "</h3>");
out.println("<table
border=0><tr><td>");
out.println(rb.getString("requestinfo.label.method"));
out.println("</td><td>");
out.println(request.getMethod());
out.println("</td></tr><tr><td>");
out.println(rb.getString("requestinfo.label.requesturi"));
out.println("</td><td>");
out.println(HTMLFilter.filter(request.getRequestURI()));
out.println("</td></tr><tr><td>");
out.println(rb.getString("requestinfo.label.protocol"));
out.println("</td><td>");
out.println(request.getProtocol());
out.println("</td></tr><tr><td>");
out.println(rb.getString("requestinfo.label.pathinfo"));
out.println("</td><td>");
out.println(HTMLFilter.filter(request.getPathInfo()));
out.println("</td></tr><tr><td>");
out.println(rb.getString("requestinfo.label.remoteaddr"));
String cipherSuite=
(String)request.getAttribute("javax.servlet.request.cipher_suite");
out.println("</td><td>");
out.println(request.getRemoteAddr());
out.println("</table>");
// Display authentication
type
out.println("<h3>
AuthType </h3>");
out.println("AuthType = " +
request.getAuthType());
// Display HTTP method
out.println("<h3> HTTP
Method </h3>");
out.println("HTTP Method = "
+
request.getMethod());
if(cipherSuite!=null){
out.println("</td></tr><tr><td>");
out.println("SSLCipherSuite:");
out.println("</td>");
out.println("<td>");
out.println(request.getAttribute("javax.servlet.request.cipher_suite"));
out.println("</td>");
}
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
doGet(request, response);
}
}
|
Code-2.32: Modified RequestInfoExample.java مصدر - 2.32 : تعديل RequestInfoExample.java 4.
Right click ServletExamples project node and select Run . انقر بزر الفأرة الايمن على عقده المشروع ServletExamples ثم اختر تنفيذ. 5.
Click Execute to execute the " Request Info " servlet code. انقر فوق Execute لتنفيذ مصدر "Request Info" 6.
Observe that the browser gets displayed as shown in Figure-2.33 below. نلاحظ ظهور المتصفح كما هو مبين في الشكل ادناه - 2.33.
Figure-2.33: Result of running the applicationالرسم - 2.33 : نتيجة تنفيذ التطبيق
Summary خلاصة
In this exercise, you have built and run "ServletExampless" sample application. وفي هذا التمرين، قمتم ببناء وتنفيذ تطبيق بسيط "ServletExamples".
return to the top عودة الى الاعلى
Homework Exercise (for people who are taking Sang Shin's "Java EE Programming online course") تمرين الواجب المنزلي (يجب إرساله من قبل المنخرطين في الدورة)
1. 1. The homework is to modify the hello2 project as described below. (You might want to create a new project by copying the hello2 project.) You can name the homework project in any way you want but here I am going to call it Myhello2 . العمل المنزلي يتمثل في تعديل مشروع hello2 على النحو المبين ادناه. (يمكنك إذا أردت انشاء مشروع جديد عن طريق نسخ مشروع hello2 ). يمكنك تسمية مشروع العمل المنزلي بأي إسم شئت ولكن هنا سأقوم بتسميته Myhello2 - Modify GreetingServlet.java and ResponseServlet.java to add another information such as Birth Place . قم بتعديل GreetingServlet.java و ResponseServlet.java بإضافة معلومات اخرى مثل مكان الولادة Birth Place.
2 . 2. Send the following files to j2eehomeworks@sun.com with Subject as J2EEHomework-servletbasics. ارسل الملفات التالية الى j2eehomeworks@sun.com تحت عنوان J2EEHomework-servletbasics. - Zip file of the the Myhello2
NetBeans project. (Someone else should be able to open and run it
as a NetBeans project.) You can use your favorite zip utility or
you can use "jar" utility that comes with JDK as following. قم بضغط ملف مشروع Myhello2
Netbeans (أي شخص آخر يكون قادرا على فتحه وتشغيله بوصفه مشروع
Netbeans) يمكنك استخدام برنامج ضغط الملفات المفضل لديك او
استخدام طريقة "jar" التي تأتي مع Jdk على النحو التالي.
- cd <parent directory that contains Myhello2 directory> (assuming you named your project as Myhello2 )cd <الدليل الأب الذي يحتوي على دليل Myhello2 > (على افتراض انك قمت بتسمية مشروعك Myhello2)
- jar cvf Myhello2.zip Myhello2 ( Myhello2 should contain nbproject directory) jar cvf Myhello2.zip Myhello2 (لا بد أن يكون دليل nbproject موجودا ضمن محتويات دليل Myhello2)
- Captured output screen - name it as J2EEHomework-servletbasics.gif or J2EEHomework-servletbasics .jpg (or J2EEHomework-servletbasics.<whatver graphics format> ) قم بالتقاط صور للشاشه -- قم بتسميتها إما J2EEHomework-servletbasics.gif او J2EEHomework- servletbasics. jpg (او بالإسم ذاته على أي إمتداد أخر)
- Any screen capture that shows that your program is working is good enough. اي صور للشاشه من شأنها أن تبين أن البرنامج الخاص بك يعمل بطريقة جيدة.
- If
you decide to use different IDE other than NetBeans, the zip file
should contain all the files that are needed for rebuilding the project
- war file with necessary source files is OK. اذا قررت استخدام
بيئة تطوير متكاملة اخرى مختلفة عن Netbeans، الملف المضغوط ينبغي ان يتضمن
جميع الملفات التي نحتاجها لاعادة بناء المشروع -- ملف war مع ملفات
المصادر اللازمة.
return to the top عودة الى الاعلى