Java程序辅导

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

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
Advanced Internet Programming - Servlets - Lab exercise - Hello World Servlet 31242/32549/ Java EEAdvanced Internet Programming INFO: What's New FAQ Software Machines Oracle Assignments MODULES: 00 Admin 01 Intro 02 Architecture 03 Servlets 04 JSP 05 JDBC 06 RMI 06 JNDI 07 EJB 08 XML 08 Web Services 09 Security 10 Transactions 11 Legacy 12 Review 99 Design LINKS: START page Faculty of IT UTS Module: Servlets Lab exercise - Hello World Servlet This laboratory exercise involves developing a Hello World servlet, step by step. It is a long process, but each step should be simple enough. Take careful note of what you are doing at each step, and the commands you need to run. It gets easier once you've worked out the process - your first servlet will be your hardest! Level of Difficulty: 1 (easy) Estimated time: 30 minutes Pre-requisites: Familiarisation labs You have a dynamic web project called "labs" 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 Create a development directory structure (typically a source code, build and deployment directory). Create a java class file which imports the relevant javax.servlet.* package (plus any other utility packages you might need such as java.io.*) This class needs to extend javax.servlet.http.HttpServlet and implements the doGet() (and possibly doPost() )methods You then compile this class into the build directory into the WEB-INF/classes directory You then create & edit a deployment descriptor (WEB-INF/web.xml) with the relevant servlet details Add any extra files like graphics, html and .properties files into the top of the build directory. You then use the jar cvf HelloWorldApp.war command to  archive the entire build directory into a single WAR file 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 deploying your first Java servlet. We will re-use the existing lab project from the previous module. Now to create a servlet, highlight the project name (labs) and use the RIGHT mouse button to select New -→ Servlet In the Create Servlet wizard window, enter the Class name for the servlet - ie: HelloWorldServlet. You can optionally enter a Java Package name, but it is always good to have a proper package name. (e.g. au.edu.uts.aip.labs) Press Next to continue. We finish by entering information about the servlet deployment descriptor. the name defaults to HelloWorldServlet, but change this to HelloWorld. Enter a description as well. Finally, change the URL mapping (the default is /HelloWorldServlet). To do this, highlight the URL mapping and click Edit. Change this to: /HW Press Finish to create the Servlet. Eclipse now creates a skeleton of the Servlet code. Eclipse tags the places where you enter your own code with the commment: // TODO: Auto Generated Method Stub i.e.: 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(""); out.println("Hello, World response"); out.println("

Hi, this is from a servlet

"); out.println("doesnt do much so far."); out.println(""); 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... 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. 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.... Now you can run this servlet. Click Right Mouse Button → Run As → Run on Server Note that the browser panel opens up with a url of http://localhost:7001/labs/HW This is because we mapped the URL /HW to run HelloWorldServlet   Packaging your servlet 1: directory structure Java servlets execute as part of a web server. You cannot run or test them from the command line. The web server you will use to run your servlet is the web server built in to the application server (WebLogic). To "run" your servlet, you will access a URL in your web browser. This is quite similar to running a CGI program, or running a PHP script. Before you can install your servlet into the application server, it needs to be packaged properly. Servlets are part of what Java EE calls 'web applications', and web applications should be packaged in a 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: static web site files (HTML, GIF, JPEG, CSS, etc) Java servlets a deployment descriptor (described later) When you package your application as a WAR file, it must 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 properties of your 'web application'. When your web application includes servlets, the deployment descriptor file describes the name of each servlet, and what URL should be used to invoke the servlet. In the case of web applications, the deployment descriptor is contained in a file called web.xml, and it must be placed in the WEB-INF directory. The Eclipse Servlet wizard automatically updates and generates this web.xml file. To view this file, check the double click the Deployment Descriptor in the project explorer. NOTE: if your dynamic web project is set to "Dynamic Web Module 2.5" in the project facets, then this won't appear since Deployment Descriptors are now optional in Servlet Specification 2.5. Instead, look at the Web Content/WEB-INF/web.xml file: Points to note: servlet-name can be any name you choose. It does not have to be the same as the filename in which the servlet class is stored. Every servlet referenced in your web.xml must have a unique servlet-name within that one web.xml file. servlet-class specifies the name of the Java class file containing the compiled servlet code. url-pattern specifies the URL by which you want users to be able to execute your servlet. In the example shown above, the url-pattern is "/HW", so the URL that will be used to invoke the servlet will look like http://hostname:7001/labs/HW 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 would expect to find on a web server. In the WAR file, these files must be placed outside the WEB-INF directory. Any files not in the WEB-INF directory can be accessed through the web browser. Any files that are inside the WEB-INF directory (including your web.xml deployment 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.

My first WAR file

Run my Hello World servlet.

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. 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. Step 1: Select the project you wish to create (in our case, labs ) and press Right mouse button. Select Export -> WAR file 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 to the 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 the contents 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.html file. If you click on the link to your servlet, it should execute 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 files is important, because the WAR filename will become part of the URL. Exploring the WebLogic console 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??) 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: (this may not be exactly the same as yours) You should see a module called _appsdir_helloWorldApp_war (autodeployed) module. Click on this to see the Settings for this deployed war file. 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. 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). 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 So if you are trying to debug your web application and can't seem to start, use this to find out what the default URL should be. 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.       © 2008 University of Technology, Sydney. All Rights Reserved. Redistribution without permission prohibited.