CSCI399
Autumn Session, 2011

Exercise 4

This exercise covers some preliminary work that you should attempt before you start Assignment 4. The tasks for this exercise test the correct working of NetBeans/AppServer.  (Some details of the use of NetBeans differ between versions; mainly it’s a matter of minor changes in dialogs.  The examples here should match the version that we have deployed in the laboratory; if you have a different version on your own machine, you may see differences.)

  1. Start the NetBeans IDE.
  2. Check that you can access the Oracle database (see Exercise 3); if you cannot, then delete any records shown for Connection and Driver and recreate them.  If that still doesn’t work you will have to delete those .netbeans directories from your home directory and let NetBeans re-initialize itself.  You will then have to repeat the steps needed to add a database driver and connection.
  3. Switch to the Project pane and pick File/New Project. Select "Java Application" as the project type. Put it in the NetBeansProjects directory, not in your public_html directory.
    As this will be the first Java project that you work on, NetBeans will spend a few moments linking in the required modules.

    The project name can be "Hello". Accept its being set as the "main project".
    NetBeans will generate an ant build file (equivalent to a "makefile") and all the other infrastructure. It will also generate an empty application with a public static void main(String[]) mainline.
    Edit the generated Java code so that it will print a greeting to System.out.
    Select the Hello project in the projects panel and right-click pick "Build" and then "Run main project". It should print your greeting in the "Ouput" pane at the bottom of the NetBeans window.
    Hello NetBeans
    When satisfied the basic Java applications can be built, close the Hello project.

  4. Again pick File/New Project, but this time pick "Web Application".


    Put it in your NetBeansProjects directory.


    You then have to specify the application server (i.e. servlet container) that is to be used.

    We will be using the “Glassfish” server – it’s needed to support JPA in assignment 5.



    (Of the servers listed, probably only Glassfish V3 and Tomcat 6 are installed; it’s possible that the Google appserver might also be installed, but for CSCI399 we want Glassfish.)

You have to specify the server location (it’s going to try to default to a private copy of the complete server application installed into your own directory – don’t use that default because it entails a large download that would consume your web quota and the application would consume your disk quota).  You need to find the master copy already installed in /usr/local:



There are many configuration files associated with the appserver – things like database drivers, lists of users and passwords, and extra library modules that you may select.  These data are stored in a number of different configuration directories that are grouped into a “domain” directory.

There is a “domain” associated with the glassfish installation in /usr/local – but it belongs to ‘root’ and you cannot modify it.



You have to let NetBeans create a “domain” in your home directory.  You will have to supply a complete path name to the directory where your configuration files are to be saved:



(If your user id was ead432, your path would be something like /home/ug/e/ead432/mydomain – just use pwd to find the path to your home directory.)

NetBeans will configure a personalized version of the Glassfish appserver for you, and store the configuration data in your “domain” directory.  It will pick some arbitrary port numbers for you – best to remember these!



NetBeans will show the server in its Services pane:



(NetBeans used to incorrectly include a reference to root’s server in /usr/local – the configuration that you cannot use.  It would then frequently put up an alert notifying you that you couldn’t use this second server version.  If by chance you do get this reference added, you will need to remove it to suppress those alerts.)

  1. NetBeans creates “Web Applications” with a dummy index.jsp page supplied – it’s just a “Hello World” application:



  2. You can test things out at this point.  Pick the project in the projects pane, right-click select “Clean and Build”, then “Deploy”, and then “Run”.

    The Run action on the project should start a session of your default browser, using it to access the “Welcome Page” for this web-app (the index.jsp page).

    (Your server will very likely be using a different port.  Port numbers are picked randomly when the appserver components are first initialized.)



  1. Servlet classes and JSPs (especially JSPs) should not be defined in the "default package"; so define your own Java package for your code.  (Right click on the project, select new Java package, dialog lets you assign a name – I tend to choose “mystuff” or “web”


  2. Select the project, and right-click "New servlet" and define your "HelloServlet".



    The second dialog lets you define the URL for the servlet – defaulting to the servlet’s class name, I often give them simpler names (be careful to start the name with /). REMEMBER TO CHECK THE  Add information to web.xml” checkbox.




  3. NetBeans generates some servlet code. This has doGet and doPost methods that both call the same processRequest function. (The doGet and doPost methods are hidden in the editor-fold; you can open the fold to view them. Usually you will get rid of "processRequest" and define a doGet that composes a HTML form and a doPost that handles data from that form).
    The generated processRequest has some output statements (initially commented out). Edit these to get a servlet that will print the usual HelloWorld greeting.
     



  4. Edit the servlet code.
    Select the project - right-click "Build".
    Right-click "Deploy".
    Aim your browser at your at your new servlet – it should be http://localhost:?????/WebApplication1/Hello.



  5. Create another servlet in your WebApplication1. This should be "SoccerServlet".  When defining it, remember to add it to the web.xml file.  I gave mine the URL /Soccer; remember the URL that you do choose as you will need to enter it in the browser address line (or in a form page maybe) or if you want to add security constraints.
    For this simple test, you can use a very bad coding style and have all the code in a single function - just edit the generated processRequest function.
    The code is to open a connection to the database and read all rows from the "soccerleague" table that you created previously. These data are to be printed in the servlet's response page.
 
 
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
       response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
           
            out.println("<html>");
            out.println("<head>");
            out.println("<title<Servlet SoccerServlet</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet SoccerServlet at " + request.getContextPath () + "</h1>");
 
            Connection dbcon = null;
            
            try {
                String userName= "homer";
               String password = "doh";
                String driverName = "oracle.jdbc.driver.OracleDriver";
                String dbURL = "jdbc:oracle:thin:@wraith:1521:csci";
                
                Class.forName(driverName);
                dbcon = DriverManager.getConnection(dbURL,userName, password);
               
                Statement stmnt = dbcon.createStatement();
                ResultSet rs = stmnt.executeQuery("select * from soccerleague");
                
                while(rs.next()) {
                    out.println(rs.getString("TEAM1") + "  " +
                            rs.getString("TEAM2") + " " +
                            rs.getString("SCORE1") + " " +
                            rs.getString("SCORE2") + "<br>");
                }
                
            }
            catch(SQLException sqle) {
               out.println("Problems " + sqle);
           }
            catch(Exception e) {
                out.println("Unusual problems " + e);
            }
            finally {
                if(dbcon!=null) try { dbcon.close(); } catch(Exception e) {}
            }
            
            
            
            out.println("</body>");
            out.println("</html>");
 
        } finally { 
            out.close();
        }
    } 
 


Use "Source/Fix imports" to add the Java include directives. Pick the right inclusions - there are Statement classes in java.sql and javax.bean packages. You want the java.sql.Statement.

  1. You then need to add the Oracle JDBC drivers to the application. Select the "libraries" branch of the project tree - then right-click to add a .jar file.



  2.  Build the WebApplication



  3. Deploy

  4. Aim your browser at http://localhost:????/WebApplication1/SoccerServlet; view the Oracle error message.

  5. Edit the code to use your database account instead of Homer's; build, deploy, test, view league results in HTML response page.

  6. You will typically be defining real implementations for doGet() and doPost() in your servlets.  doGet() will supply a form, doPost() will accept form input.  You should remember to get rid of the auto-generated processRequest function; you don’t want dead code cluttering your files.
     

 

  1. You decide to restrict use of the SoccerServlet to registered users.
    First, you must define some users and passwords for your AppServer.

  2. Log on to your AppServer as administrator.  NetBeans configures the AppServer to allow anonymous login as administrator.  I didn’t like this.  So after logging in the first time, before creating users in the “file” realm (as needed for this exercise), I first created some “admin” users with assigned passwords.  I logged out from “anonymous” – logged back in using one of my name/password admin accounts and deleted the anonymous account.  I suggest you do the same.  It don’t matter too much for the exercises but you should get into the habit of ALWAYS removing default accounts and “no-password” login accounts from any server that you deploy.

    To login, in the services pane select the servers part of the tree.  Right-click on the Glassfish server entry and pick View Admin Console.



    The Admin login screen will open in a browser window (it is a bit slow the first time as the JSP pages needed have to be compiled etc).  This allows anonymous login.  (Follow my advice and change that when you can.)

  3. In the left frame of the administrator page, select the "Configuration/Security" branch of the tree.  (Pick the admin-realm if you want to add admin users, pick the file realm if adding users for your servlet)





  4. Create a few users and their passwords. This shot shows some already added:



    Just use “New” to create a new user and assign them to one or more groups.  (Individual users, and groups, can later be assigned to “roles” – roles control access to servlets.)

    New User
    These users can be in group "soccer".

  5. Next you need to edit the web.xml and sun-web.xml files.
    Select the web.xml file in the Web/WEB-INF part of the project tree and open the file and select the “Security” tab.



  6. Several sections need to be completed – login configuration, security roles, security constraints etc.

    The login configurations that you will use in CSCI399 will either be “basic” or “form”.  They don’t differ very much.  In both, the browser displays some kind of data entry form requiring name and password that get returned to the server.  The “basic” configuration just uses the standard HTTP challenge dialog implemented in the browser – something that will look like:



    (Don’t try testing that yet!  You still have to complete the definitions of roles and constraints.)

    With “Form”, you provide your own variants of a standard servlet/jsp defined form (the minimum HTML is illustrated in the lecture notes, the fields for user-name and password must have specified names and the action clause of the form must reference the standard servlet that checks names and passwords).  The idea for “Form” is that you offer a customized login page (like that for the Appserver Admin) which looks more professional than the default browser dialog.

    For this exercise, just use “Basic” configuration; you have to make up some name for the “Realm”

  7. Next, define a role.  Roles express rights to use particular servlets (or specific features of particular servlets).  Here, one needs a “role” that permits viewing of soccer results.



  8. Then define the constraints – the sections that actually specify which servlets are controlled.  (If you think that this is tiresome, then imagine the old time fun when you had to do all this by writing out the XML data structure yourself.)

    Here, need to control access to the SoccerServlet, so add a constraint (you can give it a meaningful name rather than just “constraint-x”).  And fill in details of a “Web Resource Collection” – supplying a Resource name that you make up, and the URL.




  9. Next, you need to add the requirement for authentication of users – you specify the role that the users must be in (so this should match a role name that you defined).




  10. It is worth looking at the web.xml file as XML – you can then see exactly how deployment and control data are defined:



  11. The web.xml file is generic.  Each implementation of the servlet engine will have a different mechanism for mapping relations between users (or groups) and roles.  Tomcat has its very simple tomcat users xml file (it also supports more realistic schemes where user names and passwords are held in a database rather than a plain text file).  With the Appserver, the name, passwords and groups are defined in tables owned by the appserver (you created these earlier).  All that remains is to define a mapping from roles to users/groups.  This mapping is in another configuration file – the sun-web.xml file.

    You now need to edit this – adding a mapping from the role soccerviewer to users and groups.






  12. Note: when saving some of these xml configuration files, you will be challenged for a name and password.  You need to enter a name/password combination for an admin user of your glassfish server (the code that is checking your configuration files needs to look at the users table in glassfish).  If you left anonymous access allowed, you may not get this challenge.

  13. Finally, start over in your browser and again enter the URL for your soccer results service.  This time, you should be challenged for a user name and password before the system will release results.






When you have completed those exercises you can start on Assignment 4.