Java程序辅导

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

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
CSCI399 “Laboratory Manual” 
 
Lab setup 
The NetBeans IDE will be used for both PHP and Java development in CSCI399.  You 
should have previous experience with NetBeans from CSCI110, and maybe also CSCI222.  
The version for Session 1 2015 is 8.02 (screenshots in this document will be from this version 
and from earlier versions). 
The Glassfish appserver has been installed along with NetBeans.  This will be used to run 
servlets in the Java component of the subject.   
Most of the assignments require database access. MySQL is the standard database for 
CSCI399, and you will have MySQL accounts on the laboratory machines.   But you can use 
other databases such as Oracle if you have an account on wraith (or even Derby or Postgres; 
if you install all the software on Windows, you can use SQLServer but not Microsoft 
Access).  The arrangements for using MySQL are the same as in CSCI110.  Each laboratory 
computer is running its own instance of MySQL; the MySQL engine creates databases on the 
local hard disk.  This means that if you create tables on one computer, they will not be 
available to you if you move to another computer.  Remember also that there is no backup; if 
the software on a computer is refreshed, your data tables will vanish.  So whichever database 
you choose, you should keep the scripts that create your tables and the scripts that populate 
tables with initial data.  (Oracle will not be an option for PHP projects; I no longer configure 
the Apache/PHP system with an Oracle client; there should be an Oracle .jar file in /share/cs-
pub/399 that you can use for accessing Oracle from Java.) 
MySQL’s Workbench application is installed on the laboratory machines (there are tutorials 
for Workbench at the MySQL site).  You can use Workbench to connect to the local MySQL 
engine and create tables.  Alternatively, you can work from the “Services/Databases” tab in 
NetBeans where you can run SQL scripts or individual SQL commands. 
There is a standard Apache running at port 80 on each machine.  This has been configured to 
allow “user directories”.  It runs in single thread mode because it includes the PHP 
interpreter.  The PHP interpreter has been configured with modules for MySQL (mysqli), and 
has the GD graphics libraries installed. 
The arrangements for user directories are the same as in CSCI110.  You should create a 
“public_html” directory in your home directory and allocate “execute” permission to 
“others”.  Your home directory on Linux usually has permissions drwx------; these 
permissions prevent other students from looking at your work, but also prevent the Apache 
web server from accessing your public_html directory.  As in CSCI110, you should change 
the permissions on your home directory to maybe drwx-----x. 
The PHP environment in NetBeans should include the Zend framework (1.11) and the Smarty 
(3) template engine.  The installed PHP libraries include the ADOdb ORM package as well as 
GD graphics. 
When you first use NetBeans (or maybe every time you start NetBeans) you may get 
challenged for a “Keyring password”.  This is a feature of the Linux system and its gnome 
window manger; it depends on how your account has been set up whether or not you get this 
challenge.  If you cannot remember your Keyring password, you should remove all files from 
the directory .gnome2/keyrings and then try again. 
If you have used NetBeans previously, you may have a set of directories such as .netbeans, 
.netbeans-derby, .netbeans-registration, “mydomain” and others.  (You will also probably 
have a NetBeansProjects directory.)  Data in these directories may relate to older versions of 
the NetBeans system and can under some circumstances prevent you from starting NetBeans.  
If you have problems, delete any old NetBeans directories to give it a clean start. 
Reasonably current versions of Firefox and Chrome have been installed on both Linux and 
Windows OSs.  These should support fairly substantial subsets of HTML5. 
The Apache logs are in /var/logs/apache2 – but you cannot access these directly.  There 
should be two locally defined commands – apacheerrortail, and apacheaccesstail – that let 
you see recent entries in these logs.  The data in the logs can be useful for debugging or for 
providing evidence for your reports, i.e. evidence showing that your version runs.  
Starting in the laboratory 
It will probably be best if in the first week of session you set up your laboratory environment 
– both the PHP parts and the Java parts.  You should also reprise work that you have done 
previously on creating and using tables in MySQL. 
1 Directory setup 
Create a public_html directory in your home directory.  Assign appropriate access 
permissions to both your home directory and the public_html subdirectory.  If you cannot 
remember how to do that, go and look at the CSCI110 exercises.  Create a text file 
“helloworld.html” containing the text: 
 
 
 
  Directory test 
 
 

Hello!

Hello your user identifier here

Make sure that this file has “read” permission for others. Aim a browser at http://localhost/~youruserid/helloworld.html. You should get a greeting delivered via the local Apache web server. (Don’t open the file by double clicking on it! That has it delivered by the local file system – not the web server.) 2 NetBeans Start NetBeans. If you are challenged for a “Keyring password” get that sorted out and try again. NetBeans will typically display a “start page” (you can turn off this feature). If you configure your NetBeans (in Tools/Options/General) you can set your name and password so allowing NetBeans to access the Internet via the University’s proxy; if Internet access is available, the start page will include news from netbeans.org. Close the start page and get to the standard tab pane view. 2.1 New PHP project Create a new PHP project (right-click in Projects tab and select new). The first time you create a project of any particular kind (Java, Java Web, PHP, …) NetBeans will have to run some “activation” code to initialize configuration data. This first project is a basic PHP project (PHP version 5.5 with namespace support): No frameworks needed yet: Write the code: What do you mean “I can’t read that”? OK, here is the code again – It should run: 2.2 Activate Java Next create a Java project (nothing to do with the web, just checking that all parts are working!). Since this is the first Java action, the Java components must be “activated” Activation can take a little time Fill in all those dialogs: Implement your Java “Standard Edition” hello-world program: What do you mean “I can’t read that”? OK, here is the code again – Now run it: 2.3 Activate Web and Enterprise Java Create another project – this time the type is Java Web. There is a lot more “activation” work – this is the point where NetBeans must create a lot of extra configuration data for the Glassfish appserver. At some stage in the activation process it will ask which server you wish: It will default to creating a complete copy of all server code in a hidden sub-directory in your home directory. This wastes too much of your limited disk quota (it is fine if you are working on your own computer). Instead, set the server as the installation in /usr/local/glassfish. It is still going to use a lot of your filespace (but not quite as much). It always has to create many “preferences” files, and history files recording your use of the server. It will also let you install additional plugins – extra NetBeans features that you may wish. (The idea is that the /usr/local/glassfish installation has the components that every user will use, but each individual user has a customised instance of the server with the extras that they wish.) It will create a “personal domain” – a subdirectory with your own preferences and extra plugins. It will print details of the ports that it has set for your server (port numbers will change if any of the default ports were in use when you create your personal domain). (Some error messages will appear during this process. Some of these relate to an out-of-date security certificate – this has been complained about since at least 2008; there must be some reason why they don’t fix it.) Note that PHP projects (that will be served via the Apache/PHP system) go in your public_html directory but Java web applications that run on Glassfish go in subdirectories of your NetBeansProjects directory. You should eventually get an empty web app with just a HTML page (index.html) (in some versions of NetBeans, you get a JSP page index.jsp instead). Edit the HTML code so that it will produce some output. Just select the project in the projects tab, and right-click and select “Run”. It gets exciting. (?) NetBeans has to 1. If necessary, compile the JSP page (converting it into a servlet that prints output) – this isn’t required if a HTML page was created. 2. Prepare it for deployment. 3. Start servers (Derby database and glassfish). 4. Deploy the application onto the server. Start a browser. 5. Aim the browser at the new Java Web application. (If you have followed instructions from elsewhere – like some of the lecture notes – and you have already set an administrator password on your glassfish, you will be prompted to enter this password at some point during the deployment operation. You really should set an administrator password – see later.) Derby database starts, and glassfish starts – reports appear in the output logs shown in NetBeans: It does actually have quite a lot of work to do to get the appserver up and running: Eventually we get there: I don’t know why it creates two entries in your “servers” table: Right-click on the running server (the one with the green marker) to get controls for restarting and setting properties. Since we don’t use Derby, this database process is just extra overhead. You might as well switch off the automatic start of Derby. The “HTTP Monitor” option may help debugging; it provides additional log data about the requests that your server received. 2.4 Check out database connections Do this once you have got your database password and identifier. The lecturer will send mail with the identifier and password for MySQL – it will be something like student13/V1hJ4kuio. You may not get passwords until the second week of session. You should be able to use MySQL workbench. There is a little file – babynames.sql – in /share/cs-pub/399 on banshee. Get this file. Connect to your MySQL account using Workbench: (Use the password that you were sent, and the username – username gets used as connectionname, username, and default schema name.) Create the table: (The data are the most popular names for boys and girls as based on “Birth Announcement” data in some USA newspapers in 2012. The idbabynames field is one of those terrible surrogate keys – the only reason that it’s there is a later exercise will use a simple ORM (object relational mapping system) that requires primary keys and has a very very strong preference for simple integer primary keys with names starting ‘id’.) Then in NetBeans, check the Services/databases tab, it should show provision for connections to a variety of databases, and will probably also have an entry for administering the local MySQL (which you cannot use as I’m not telling you the administrator password) and for using Derby (which you don’t particularly want to use – I suppose you could use it if you have some deeply held conviction that MySQL was not right for you). It sets the wrong schema as the default – find your own schema and right click to set it as your default. (You should change that JDBC URL something easier like student13connection or, as for this example, mcleodconnection.) 2.5 Check the data table 2.5 Using the databases from PHP Create a new PHP web application that simply displays the contents of the babynames table: /home/mcleod/public_html/Babynames1/index.php Database tests

MySQL

Connect to local mysql, list all in babynames table

prepare("select idbabynames, name, gender from babynames"); $stmt2->execute(); $stmt2->bind_result($id, $name, $gender); print ""; while ($stmt2->fetch()) { print ""; print ""; print ""; print ""; } print "
" . $name . "" . $gender . "
"; ?> It should work (of course, you did remember to change the user-name and password). 2.6 Getting smart There is a demonstration PHP/Smarty project in /share/cs-pub/399/A3. Fetch it, and unpack into your public_html folder: (Of course, you log in to banshee using your user id and password, not mine!) This project has the standard smarty structure with sub-directories for “cache”, “configs”, “templates”, and templates_c. (The sub-directories for “cache” and “templates_c” need permissions that let the Apache web server write files.) The example has a form and PHP response page for Rasmus’s “Name/Age” example, and another PHP script that gets data from a simple table. Both the demo and showpeople PHP scripts use smarty templates for their output. You need to create and populate the table with details of Rasmus’s friends. The index.php page is just Rasmus’s form: The data entered in the form are picked up by the PHP script, set as attributes in an instance of class Smarty, and this smarty object is then used to output a HTML response page using the rasmus.tpl Smarty template: That part should run: The showpeople.php script fetches data from the peopletable that you created; packs required data into an array structure; and finally passes this array of data to a smarty object that will display the data using the showpeople.tpl template. This part should also run (yes, you do need to first change the username and password in the connection request.) 2.7 Setting up Zend You can leave this part of the exercise until you are about to start Assignment 4. The Zend framework is introduced in the “Still More PHP” segment of the subject. First, you should add the Zend library to the global include path used by NetBeans for PHP (this is under the Tools/Options menu): (The library is currently in /usr/share/php/libzend-framework-php.) Adding this directory allows NetBeans to check calls to methods of Zend classes. The Zend libraries must also be added to your Apache configuration (this has been done in the laboratory, but it is something that you would have to do if trying to configure similar software on your own computer). You must also “register” a command supplier: (Again if you are creating a version of the software on your own computer, you will have additional work to do. There is a file NetBeansCommandSupplier.php (or something like that) among your NetBeans IDE files; this has to be copied to the directory with the Zend PHP files.) You should now create a new PHP project, this time specifying the use of the Zend framework. NetBeans will run Zend’s script and create a project with the elaborate structure required by Zend, along with a few files. This project directory is created in your public_html directory. The Zend install script actually gives you a running application – one that displays an advertisement for the framework: (Note the URL - ~youruserid/Projectname/public. It runs the index.php script there. This odd URL relates to the simple way of setting up Zend. The proper way to setup Zend involves many additional steps creating “virtual hosts” in your Apache, modifying DNS records, reconfiguring browsers and proxies.) You edit the files of the script generated application to create your own application. Initially, just change the default output. This is defined in the file application/views/ scripts/index/index.phtml. It has the same role as a Smarty template. As initially generated it has a CSS style section and the HTML with the links back to Zend that produce the output shown above. Change it to something like: This should result in an advert free starting page. Another thing that you should do at this point is add extra information to the .htaccess file that Zend generated (the one with the rewrite rules for Apache). This change relates to the simple way of configuring Zend. There has to be a line specifying where the Zend project’s public directory is relative to your public_html directory: Add a “RewriteBase” entry: 2.8 Zend handles babynames Your Zend installation needs a few more tests to check that all is working correctly, so create another version of the babynames application. The default output from your updated babynames Zend application should be a HTML page showing the babynames records from your MySQL database. This will involve: 1. Adding a database adapter to your project. Details of your database, password etc should be added to the application/configs/application.ini file. This can be done using a Zend command script (in NetBeans, this works with dialogs). Most commands are best done using the scripts and dialogs – but it is actually easier to just edit the application.ini file when adding an adapter. 2. Create a “model” with a data table class related to the babynames table in the database. (Should definitely be done using the Zend script). 3. Modifying the code of the “indexAction” method in the “indexController” to use a data table object to retrieve the data. (Does this sound confusing? Just magical incantations? Of course. But all will be explained in lectures.) 4. Changing the index.phtml view template to output the data. In NetBeans, you can run Zend commands by right-clicking the project and selecting Zend/Run Command. The configure db-adapter command can be used; you must specify host, adapter, port, username, etc. It is easier to copy and paste the information directly into the application.ini file! This specifies use of the PDO_MYSQL. The host is localhost etc. (Create appropriate resource.db.* entries for username and password). Next create a Zend db-table class (and the rest of the “model”). Here, you should use the Zend command and its NetBeans dialog: You pick a name for the class – BabynamesTable – and identify the table – babynames. The Zend script creates a set of directories for the model and a file with the class definition: This is the class used to access the table: No code? Magic? Of course it is a form of magic – it is an auto-generated “Object-Relational-Mapping” class. All details of accessing the table and retrieving data will be handled for you. Our new application is to use an instance of this class to retrieve the data from the babynames table as part of its default “indexAction” of the IndexController. The auto-generated code will have an empty body for indexAction(), i.e. public function indexAction() { } Replace the empty body for indexAction. We want to create a table access object. Then use it to retrieve all records. We add these to the associated view (very similar to passing the data to a Smarty object). We also have to edit the view object (that index.phtml file again). Zend uses standard PHP for scripting (it doesn’t have a special view scripting language like Smarty): It should run: 2.9 Configuring admin and users for Glassfish You can leave this part of the exercise until you are about to start Assignment 5. Connect to the administrator console for your Glassfish server (this is a right-click option on your server in the Service/servers tab in NetBeans): You need to configure the “admin-realm” and later, when adding users and roles for authentication and authorization, you need to configure the “file-realm”. These are both parts of the Configurations/server-config/Security section of common tasks. You will need the “Manage Users” option in this section: There should be an existing entry in the users for “admin” – create a new entry with a password for your userid and set passwords: Logout from the admin console, then log back in using an account with a password: While logged in as an administrator, create some users in the “file-realm”. With an application server like glassfish, user authentication and authorization is handled by the server – not by the individual applications. With GlassFish, you have users and groups (for authentication), and roles (for authorization). The authentication data are configured using the admin console of the server. Roles tend to be application specific. When creating an application you specify the roles, and provide a mapping between roles and users/groups. Group names should be chosen to be meaningful – but that is kind of organization dependent so here I’m just going to use “group1” etc. Select the security/file realm option, then pick “manage users” and create users, making them members of various groups: You should create a few users assigned to various combinations of groups. (In a real world context, the groups would be things like “developer”, “manager”, “tech-support”, “privileged user”, “user”). Those users and groups will get referenced in a later example where restrictions are placed on the use of web applications. 2.10 Checking database access from Java You can probably omit this task and get straight on with the web-application in the next section. But it could help identify configuration problems if there are any. The task is to use database drivers from a Java Standard Edition application (command line Java program). Create a new project in your NetBeans projects directory – a Java SE project. Add the database driver code. MySQL is considered standard, so you use “Add Library” and pick an entry for the list. If you were to use a different database such as Oracle, you would use “Add Jar file” and find the .jar file with the database driver. It should run: 2.11 A babynames servlet What else? In Netbeans, create another Java Web Application – “Babynames”. NetBeans creates the project with an empty index.html page (well that depends on version of NetBeans, some versions create an empty index.jsp). In more complex cases, you will discard this; but for simple applications you can use it as a “Welcome” page that will provide links to servlets and JSP pages. All code for servlets (and JSPs) must be part of defined packages, and not in the default package. So, your first task is to add a new Java package – e.g. “mystuff”. Then, add a servlet to the project, making its code part of the new package. Servlets require deployment data that are used by the application engine – Glassfish, Tomcat, Oracle Application Server etc. Traditionally, all deployment data were held in a “web.xml” file. Since “Servlets 3”, an alternative scheme has existed where deployment data are defined in “annotations” in the source code. The “annotations” approach is supposedly easier for the developer (I haven’t found it that helpful) while the web.xml approach is better for “production” environments. When you create a servlet, you have the option of adding its details to web.xml – select this for now (you can try the annotations approach some other time). NetBeans generates an outline for your servlet. This generated outline has definitions for doGet() and doPost() (the methods that you are most likely to need for the typical servlet). The code supplied for both methods invokes a NetBeans defined processRequest() function that prints some predefined text when either Get or Post is invoked. This processRequest function exists simply to help you test whether the servlet system has been set up correctly (its code shows how to open and write to the servlet output stream – a useful model that you can copy into your own functions). Once you have tested the setup, you should remove processRequest() and define effective methods for doGet (get a form) and doPost (process a submission). It is best to start by running a quick test using this default processRequest() function. This lets you confirm that you can successfully deploy the web application. Edit the index.html page so that it will display some content including a link that can be used to activate the servlet: If you right-click on the project and select run, NetBeans will deploy the web app (if not already deployed) and cause the default browser to open the index.html file in the project. Use the link, you should get the output from supplied processRequest() function: Next edit the servlet to include some real code! You should remove the “editor fold”, and define meaningful methods for doGet(), doPost(), and getServletInfo(). Remove the doPost method entirely (an attempt to post to this servlet will then fail, generating a standard error response). Copy the content of processRequest into doGet and remove the processRequest function. Copy code from your database checking exercise into the revised doGet function: NetBeans will help sort out the “includes” – just right-click in the editing window and pick the “fix up include files” option. There could be several Java classes with the same name, e.g. “Statement” – NetBeans offers a list, it is your responsibility to pick the right one: Add the MySQL driver to the project! Run: I had enabled the HTTP Monitor for my glassfish, so I got a log of the requests: 2.12 Application engine applied access control The application of security constraints can be illustrated by restricting access to the babynames servlet to a subset of the users defined earlier. Part of this security configuration is common to all servlet environments, and part is implementation specific. The common part defines roles and privileges – you specify the roles allowed access to the servlet (you can be more specific and define things like GET being available to two roles, POST only available to one). The implementation specific part is the bit that maps users (or groups) to roles – this is implementation specific because obviously Glassfish stores its user data differently from Tomcat or the Oracle Web Server. You can refine things further by having the code of the servlet check the role of the current user. This is illustrated in the worker/manager/boss servlet example in the lectures. There any worker (and managers are themselves workers) can use a servlet that lets them see the number of hours that they have recorded as working; but when used by a manager, the same servlet allows that manager to also view the hours worked by any of the people that he or she manages. The babynames application doesn’t require such refinements. Select the project’s web.xml file and pick the security tab: There are several sections in the security tab. First you must select the “Login Configuration”. We will normally use “Form Configuration” but for this baby example we run with “Basic”. Basic simply uses the “realm” prompt in the browser to get name and password. This is OK for a test, but shouldn’t be used in a real environment where all logins should be customised. The Realm name has to be supplied – it will appear in the login dialog presented by the browser. Next add a security “role” along with a description. Parents-to-be are the ones likely to be interested in babynames so have a role “newparent”. Then add some constraints. What is constrained? Access to all methods of the babynames servlet: What kind of constraint? An authentication constraint – access only allowed to persons authenticated to be in the “newparent” role. (The user data constraint allows you to specify extras like use of SSL or message digests to increase the security of communications.) It’s worth looking at the source of the web.xml file to see how these constraints are actually expressed. Once the generic controls have been defined, you must set up the implementation specific controls. Select the project and pick “New File/Other”. The new file has to be a “Glassfish descriptor”: Need to add a Security constraint to the glassfish-web.xml file: This constraint essential says that persons in group1 can take the role of “newparent” and use this servlet. Redeploy the web application and restart your browser. When you attempt to access the servlet you should see a standard browser challenge for name and password: If you use the name and password of a person not in group1, you will get a rejection response. (It seems that it leaves a “logged in as …” cookie on your browser that prevents you from trying again. You have to restart your browser to try with another user name.) Restart your browser and enter the name and password of a group1 member: You should once again be able to see the names: 2.13 Customised login form “Basic” authorization, using the browser dialog for access to a “realm”, is only for development tests. A real application should have at least “form” authorization with a customized login page. This page obviously should use site-wide styling from CSS stylesheets, and be customized to the organisation. But it also has to follow a standard structure defined by the servlet specifications. The name and password fields must have specific names and its action is to “post” to a built-in component within the application server. The security checked babynames application can be extended with a minimal version of the required form and login pages. Add HTML pages – loginpage.html and errorpage.html – to the project. Then re-configure the “login” section of the web.xml file: An attempt to access the servlet will now bring up the login page (which obviously needs “prettying”): If an invalid user-name/password combination is entered, the error page gets displayed: But if the user-name and password correspond to a user who does not have the right to access the resource the standard HTTP “access denied” response gets sent: 2.13 Using a DataSource The direct use of a JDBC driver to connect to a database was “deprecated” years ago. (Of course, most of us still do things that way.) Instead you are supposed to use a “DataSource”. A “DataSource” is an initialized object that contains the information needed to connect to a database – which driver, what URL, which user, what password etc. Your program is supposed to load in a DataSource object and ask it for the connection. But this means that somehow you have to 1. create an instance of a “DataSource” object with all the right data; 2. Store it somewhere in the filespace; 3. Have your program load this object from filespace. This is a little inconvenient if you are writing a simple stand-alone Java SE application. But it isn’t too difficult if you are using servlets deployed into an application server. In addition, the current environments are likely to work with a connection pool – so you get a reusable connection. When you dutifully close a reusable connection, it goes back into the pool. This can improve performance as database connections are not being repeatedly opened and closed. An environment like NetBeans can provide a “wizard” that helps you build a valid DataSource object for your chosen database. The Glassfish server provides facilities for storing such objects and retrieving them by name. So the next improvement to the babynames project should be use of a DataSource. Add a new “Glassfish/JDBC Resource” to the Babynames project: You have to give the resource a name; something like jdbc/localmysql NetBeans can correctly initialize such a resource using data from the database connections that you previously created. The details of the new DataSource object will be stored in Glassfish when you next deploy the application. You must rewrite the code to use the DataSource rather than a JDBC driver when getting a connection: The revised program should work. 2.14 Using Java Persistence (JPA) Create a new Java Web Project – Babynames2; add a Java package (“mystuff”). This version of the project will need to use a library that implements the JPA specification. There are now several versions available; the versions from the Hibernate project or the Eclipse project seem to be those preferred for use with Glassfish 3. You need to add a JPA implementation library to the libraries for the Babynames2 project (this is “Add Library” rather than “Add JAR/Folder”). You will need a JPA implementation library and also the Persistence Library. Then you will want NetBeans to generate an “entity class” based on the meta-data that the database has describing its tables: In the dialog, select the datasource – use your MySQL data source. NetBeans will retrieve the meta-data on all your tables and list them as “Available Tables” (if an entry is greyed out, it is a table without a primary key). Pick the table and add it to the “Selected Tables” (NetBeans will use foreign key relations and identify any “related tables” that would also have to be added – obviously there are none for the babynames example). NetBeans generates an EntityClass – which is a simple Java class with fields for the different columns in the database, get/set access/mutator methods for the fields, and a few extra methods like toString(). The MySQL meta-data is easy to interpret and NetBeans has been able to pick up the fact that the babynames table has an auto-increment primary key field. You usually change the generated implementation of toString to one that gives a string with summary data about the record (more than just the primary key): NetBeans has also created some “NamedQuery” objects that embody simple queries (these are expressed in the Java Persistence Query Language which is similar to but not identical to SQL). At run-time, the code is going to need the data that specify that this record is in your MySQL database. These data are created in a “persistence.xml” file associated with the project. NetBeans will offer to create this at the same time as you create the entity classes from the database (or you can create it at a later stage). The persistence.xml file contains an identifier that will be used later in the program when it needs use the configuration data. Note the “Table Generation Strategies”– you will usually have already created the tables and filled them with data so you will want “None”. If creating the persistence.xml file manually, you will need to specify the Persistence Provider and the data source. By default it will include the Entity Classes that are defined in the project. (In more complex examples, the entity classes may well be part of a separate “Java library” project – in that case you have to add them manually.) You should note the Persistence Unit Name. Use NetBeans to create a new BabynamesServlet – as before remove doPost() and processRequest() and edit doGet(). This BabynamesServlet will be using a connection to a database as defined in the persistence.xml file. Here, “code injection” is being used. (“Code injection” is another form of magic that will be explained in the lectures!). The servlet will need to use an “EntityManager” to handle its connection to a database and the storage and retrieval of entities. (EntityManagers are not thread safe so they are created as local variables of functions – therefore in thread storage). EntityManagers are created using an EntityManagerFactory which interprets the persistence.xml file. An EntityManagerFactory is thread safe and should be created as an instance member of the servlet. The @PersistenceUnit annotation provides a mechanism for automatically initializing the EntityManagerFactory with data defining a particular persistence unit – the one whose name you remembered earlier – in the persistence.xml file. The new version of doGet() 1. uses the factory to create an EntityManager 2. uses the EntityManager to create an instance of the “findAll” NamedQuery 3. uses this query to retrieve a collection of matching records 4. loops through the records generating HTML markup (It is all much tidier and simpler than the code using JDBC connections, statements, resultsets etc.) Many libraries will need to be imported for Query, List etc. Pick the appropriate ones (there are at least 5 different List classes to choose from). If you look at the project, you will see that numerous .jar files have been added to support Persistence and JPA implementation: You will need a index.html file to invoke this new sevlet (note that servlet name is the same as that earlier – that is ok as they exist in different projects, they can both be deployed onto the same server without confusion). It should run: 2.15 Using Java Server Pages (JSPs) to display results Those out.println() statements in servlets are so clumsy – they are like “echo” statements scattered though a PHP script. JSPs were invented long ago (~1999) to provide a better approach to dynamic content presentation. It is possible to do the actual work of an application in a JSP, possible but really not that convenient. Servlets and helper classes provide a better environment for “coding” issues. Although JSPs are intended to be more general, it is easiest if you simply use them in the same way as you used Smarty templates with PHP. The overall approach is very similar to PHP+Smarty. Work is done in the servlet. Results are collected. The servlet passes the collections of results to a JSP (just as a PHP script passed its results to a Smarty object). The JSP has standard markup along with sections that extract required data from the result objects and slot them into HTML constructs. Originally, JSPs had HTML markup and static text with the dynamic content created by little fragments of embedded Java code (“scriptlets”). The style was similar to the contemporary approaches like ASP and PHP. Subsequently, embedded Java was “deprecated”. Instead, dynamic data were displayed using XML like “action tags”. These action tags are really a bit like macros – small parameterized templates that get expanded to much more code. “Tag libraries” exist with different sets of macros that permit different ways of selecting result data and incorporating them into the HTML page. We will be using only the Java Standard Tag Library JSTL. You will need a new Java Web Project – Babynames3. This will have a servlet that retrieves all names from one of the databases (using JPA). The servlet will forward the collection of names to a JSP. The JSP will create the report page using JSTL action tags to format the dynamic parts of the response page. Babynames3 project: 1. Create the project 2. Add the EclipseLink persistence library 3. Add a persistence.xml file specifying use of a MySQL connection. 4. Create a Babynames “entity class” from the table in your MySQL database. 5. Add a Babynames servlet; take the definitions from the last example as the starting point (a doGet method using an EntityManagerFactory to create an EntityManager etc) Add the JSTL library to the project: Add a JSP: Just get a standard JSP in default location (WebPages). NetBeans generates the JSP with the standard “Hello World” content: Edit the servlet. Its code can be simplified. It just retrieves the records, adds the record collection to the request, and forwards everything to the DisplayResults.jsp. Define the JSP: Note: 1. It’s using the JSTL tag library (actually, just the “core” module of JSTL) so add the taglib annotation. 2. It’s generating a list; the list delimiters
    and
can be put into the text. 3. It is to loop through the collection of results outputting each as an item in the HTML list; so it uses the “forEach” action from the JSTL core module (c:forEach). 4. This forEach loop needs a working variable – name it “record”. 5. The forEach loop is working with the forwarded collection of name records; it is going to find them attached as the extra attribute “babynamelist” on the request object – this is specified by the expression ${requestScope.babynamelist}. (The expression language used is derived from Javascript.) 6. Each “record” will have a “name” member and a “gender” member. These should be output using the “out” action defined in the JSTL core. It should work: (If you have a problem deploying – e.g. complaints about wrong class for mysql driver, it might be due to glassfish tidying up and removing the datasource definition that you added in step 2.13. Redeploy that project again, or add a similar datasource definition to the current project.) End When you have completed all those steps you should have experienced most of the technologies that will be used in this year’s version of CSCI399.