Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439

This laboratory exercise involves developing a Hello World servlet,step by step. It is a long process, but each step should be simpleenough. Take careful note of what you are doing at each step, andthe commands you need to run. It gets easier once you've workedout the process - your first servlet will be your hardest!

Level of Difficulty: 1 (easy)
Estimated time: 30 minutes
Pre-requisites:


A HelloWorld servlet

There are 2 main ways of creating a servlet

Manually creating a servlet

Before the days of Integrated Development Environments, programmers had to develop servlets much like any other Java package (eg: Applets). The steps involved were

  1. Create a development directory structure (typically a source code, build and deployment directory).
  2. Create a java class file which imports the relevant javax.servlet.* package (plus any other utility packages you might need such as java.io.*)
  3. This class needs to extend javax.servlet.http.HttpServlet and implements the doGet() (and possibly doPost() )methods
  4. You then compile this class into the build directory into the WEB-INF/classes directory
  5. You then create & edit a deployment descriptor (WEB-INF/web.xml) with the relevant servlet details
  6. Add any extra files like graphics, html and .properties files into the top of the build directory.
  7. You then use the jar cvf HelloWorldApp.war command to  archive the entire build directory into a single WAR file
  8. You then deploy (copy) this .war file following the instructions of your particular web application server.

You can optionally attempt this later by looking at the "tutorial: creating war files manually".

Using Eclipse to create a servlet

In this lab we will use Eclipse (Workshop for Weblogic) to create our first servlet.

This exercise will lead you step by step through writing and deployingyour first Java servlet.

  1. We will re-use the existing lab project from the previous module.

  2. Now to create a servlet, highlight the project name (labs) and use the RIGHT mouse button to select New -→ Servlet

  3. In the Create Servlet wizard window, enter the Class name for the servlet - ie: HelloWorldServlet.
  4. We finish by entering information about the servlet deployment descriptor.
  5. Eclipse now creates a skeleton of the Servlet code.

  6. Go to the doGet() method code body.


    • Replace this comment with the following code fragment:

      FOR THE MOMENT, PLEASE DON'T CUT AND PASTE THE CODE.

      We will experiment with Eclipse's Code assist features to help you enter the correct code as you type!
    response.setContentType("text/html");PrintWriter out = response.getWriter();out.println("<html><head>");out.println("<title>Hello, World response</title></head><body>");out.println("<h1>Hi, this is from a servlet</h1>");out.println("doesnt do much so far.");out.println("</body></html>");

    As you type resp, you can press Ctrl-spacebar to ask Eclipse to show you the valid candidates which you can legally enter in the Java class that start with the letters resp. Try it...


  7. Pressing Enter will insert the whole string response for you. Now if we press the . key to continue, Eclipse will pop up a list of valid methods for this object - we can type-ahead to narrow this list down. Try the first 4 letters setc to get the list down to setContentType. The really neat thing about Eclipse is it also describes what the method does. This even works for your own custom built methods. However, you do need to use Javadoc /** descriptors before your methods for this to work...

    Pressing Enter will insert the template for this method. You simply replace the highlighted string with your own code.

  8. Finish typing in the rest of the code now. In later labs you are welcome to cut and paste the code directly into Eclipse, but for the moment, just get used to the Eclipse code editor by typing it in by hand....


 


Packaging your servlet 1: directory structure

Java servlets execute as part of a web server. You cannot run or testthem from the command line. The web server you will use to run yourservlet is the web server built in to the application server (WebLogic).To "run" your servlet, you will access a URL in your webbrowser. This is quite similar to running a CGI program, or runninga PHP script.

Before you can install your servlet into the application server,it needs to be packaged properly. Servlets are part of what Java EEcalls 'web applications', and web applications should be packaged ina Web Application Archive file, or WAR file.

A WAR file is basically a compressed zip file that contains all parts of your web application. The parts may include:

When you package your application as a WAR file, itmust follow a particular directory structure like the following.



Packaging your servlet 2: deployment descriptor

As mentioned above, a WAR file contains static HTML (etc) files,Java servlet classes, and a deployment descriptor.The next step is for you to create a deployment descriptor.

A deployment descriptor is an XML file describing the propertiesof your 'web application'. When your web application includes servlets,the deployment descriptor file describes the name of each servlet, andwhat URL should be used to invoke the servlet.

In the case of web applications, the deployment descriptor is contained ina file called web.xml, and it must be placed in theWEB-INF directory.

The Eclipse Servlet wizard automatically updates and generates this web.xml file.

Points to note:


Packaging your servlet 3: static HTML files

Your WAR file can also include static HTML files, as well as images(GIF, JPEG), style sheets (CSS), and any other static files you wouldexpect to find on a web server.

In the WAR file, these files must be placed outside theWEB-INF directory. Any files not in the WEB-INFdirectory can be accessed through the web browser. Any files that areinside the WEB-INF directory (including your web.xmldeployment descriptor, and your servlet class files) will be protected, and are not accessible to users over the web.

You can create subdirectories visible to the user by selecting WebContent and Right Mouse clicking and selecting New -> Folder.

CAUTION: Any subdirectory created OUTSIDE of WebContent will not be accessible to web users - this includes any file placed in WEB-INF!!

You should already have a static HTML file called index.html from the previous lab. Modify this file to link to your new servlet.

<h1>My first WAR file</h1>    <P>Run my <A HREF="HW">Hello World servlet</A>.</P>

NOTE: Notice that our HREF refers to HW not /HW or HelloWorldServlet

This is because a putting a / in front of a reference will make the browser look for the absolute URL at the root context (ie: / ) of the web site, not the relative sub-context (ie: /labs ) which we will be deployed as. So putting a /HW will force the web browser to look for http://localhost:7001/HW instead of http://localhost:7001/labs/HW

Here is a rough mapping of how your Eclipse/Workshop project maps to a WAR file.



Packaging your servlet 4: create the WAR file

When testing using Eclipse/Workshop we have been running under what's called an "exploded war directory", ie. the war file has not been archived. While this isn't specified in the Java Enterprise standard, most vendors including Weblogic allow you to specify a directory instead of a WAR file to deploy. This is great for application development and testing. If you are curious about where this directory is located when developing using Eclipse, look at the Weblogic console for a deployment module called "_auto_generated_ear_" file.

Let's now create a war file which we can distribute and deploy seperately.

  1. CAUTION: Oracle Enterprise Pack for Eclipse (OEPE) [which is installed as the eclipse-all-in-one version on the lab workstations]also creates a weblogic.xml file.
    This hardcodes the URL (see the wls:context-root entry) to /HW.
    Remove this entry BEFORE you export, otherwise you may get deployment problems as this is what Weblogic uses as a hardcoded URL for your war file.
  2. Step 1: Select the project you wish to create (in our case, labs ) and press Right mouse button. Select Export -> WAR file


  3. Next , choose the destination file - let's call this helloWorldApp.war. You should put this into your own directory (I created a local directory called aip to put these files in)
    Note: Normally you don't include source files, but when developing I tend to do this so when I debug I can view which version of the source code I used.
    You must export the source files when submitting assignments though, so let's Select "Export Source Files" now..
    You may also have to select "Overwrite existing file" if helloWorldApp.war exists already.

    Also note that the META-INF directory and the MANIFEST.MF file are automatically added by Eclipse.You can ignore them for the moment.


Deploying your web application

Now that you have a WAR file, you can "deploy" it tothe web server. Deployment is the process of installing an application.

In WebLogic, there are a variety of ways you can deploy an application.The simplest is just to copy your WAR file into your WebLogic server's"autodeploy" directory.

  cp helloWorldApp.war ~/weblogic/autodeploy

You can do this when the server is running. The server checks thecontents of the autodeploy directory every few seconds,and when it sees a new WAR file, or one with an updated timestamp,it automatically deploys (or redeploys) it.

Note: if you don't have a weblogic.xml file with a wls:context-root entry in it, weblogic will use the name of the war file as the context-root.

So in our case, the context-root will be helloWorldApp

NOTE: URL's in Java Enterprise are case sensitive!!! So if you type in /HelloWorldApp or /helloworldapp on the browser, you will get a 404 Not Found error!!


Testing your web application

If you have followed the steps above exactly, try accessing your application through the following URL:

  http://localhost:7001/helloWorldApp/

It should show you the contents of your index.htmlfile. If you click on the link to your servlet, it shouldexecute your servlet and display the servlet's "Hello World"message.

Note that when you deployed your WAR file into WebLogic, it created a virtual directory under the root of your web server with the same name as your WAR file. So the name you choose for your WAR filesis important, because the WAR filename will become part of the URL.



Exploring the WebLogic console

  1. Open the weblogic console (hint: http://localhost:7001/console) and enter the usual administrator userid and password (recall: we set this to weblogic and weblogic! respectively??)
  2. On the left hand menu (Domain Structure menu) is a choice called deployments. Select this and you should see the
    Summary of Deployments" screen like:
  3. (this may not be exactly the same as yours)

  4. You should see a module called _appsdir_helloWorldApp_war (autodeployed) module.
  5. Click on this to see the Settings for this deployed war file.
  6. You can see that the path is where the actual WAR file resides in our ~/autodeploy directory.

    Also note that the console will display any sub-modules of your deployed module.

    In our case, there is a Web Application called _appsdir_helloWorldApp_war (autodeployed) which if clicked, returns to this very same page!!
    (this is more useful when we have an Enterprise Archive (EAR) file which may contain many sub-modules.

  7. Click on the Testing tab at the top. This allows you to check what Weblogic thinks the URL to this application should be.
    If it is something other than "http://127.0.0.1" just ignore that for the moment.
    (technically this is because Weblogic binds to all the available network addresses of the host. So it could be something like http://138.25.16.222 or some other weird number).
  8. For the moment, the only important item we want to observe here is the URL and note that the default URL is something like http://xxx.xxx.xxx.xxx/helloWorldApp

As mentioned earlier, note that there is a Deployment module called "_auto_generated_ear_".
This is the application generated by Eclipse, and is used to run the various modules you will be developing in this course.

If you select this you could also click on this to see the labs web module, and do the same exploring we did the the helloWorldApp module..

Try this now. If you select auto_generated_ear_ then you can see the path is something like /home/chw/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/weblogic/_auto_generated_ear_ which is where the code generated by Eclipse lives.


Reflection

This exercise took you through the steps to to create a Servlet using Eclipse (Workshop for Weblogic). Certainly it is possible to create a WAR file by creating a directory structure much like a WAR file, creating web.xml/weblogic.xml by hand, creating Servlet java files and compiling them by hand (or with a build script like Makefile or Ant) and finally generating a WAR file using the jar cvf command.

Using tools like Eclipse improve programmer efficiency by allowing you to incrementally build and test and using wizards to generate & "instantly" test your application.

Note what steps you took, and don't forget to ask your tutor for assistance as necessary.

Furthur labs will not be as detailed as this one, so you must be comfortable using the Eclipse IDE as we go on further.