CSCI399
Autumn Session, 2009

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.

  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. Start your AppServer - pick the "Glassfish" entry in the “Servers” entry within the “Services” pane and right-click "Start". It should be running before you do things like deploy servlets.

    Start engines

    (It will list the ports that it is using in the output window.  Note the ports that it picks for the HTTP listeners; these are picked pseudo randomly.  In the example output shown, there are three listeners – two of which you use, so you need to remember the port numbers.  It picked port 8120 as its main HTTP port – this will be the port number that gets used in URLs for accessing servlet based applications.  Port 4948 is used for the “admin console”.)
  4. Switch to the Project pane and pick File/New Project. Select "Java Application" as the project type. 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.
  5. Again pick File/New Project, but this time pick "Web Application".
    New web application
    The WebApp should be configured for Sun's AppServer (not the Tomcat server that is also available).
    Build for AppServer

    NetBeans generates a number of files, including a default JSP welcome page and a web.xml deployment file (inside "Web Pages/WEB-INF".
    Servlet classes and JSPs (especially JSPs) should not be defined in the "default package"; so define your own Java package for your code.

    You need a package

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

    Hello servlets

    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.
     
    Get it to say something

    Edit the servlet code.
    Select the project - right-click "Build".
    Right-click "Deploy-Undeploy".
    Aim your browser at your AppServer (you do know which port its using don't you?). http://localhost:???? will show a standard "Your server is running page". http://localhost:????/WebApplication1/HelloServlet should get you a greeting from your servlet.

    Greetings from your servlet

  6. Create another servlet in your WebApplication1. This should be "SoccerServlet".
    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 sql.Statement.
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. The full path will have to be entered - /usr/local/instantclient_10_2/ojdbc14.jar.
Build the WebApplication


Deploy
Aim your browser at http://localhost:????/WebApplication1/SoccerServlet; view the Oracle error message.
Edit the code to use your database account instead of Homer's; build, deploy, test, view league results in HTML response page.
 

  1. You decide to restrict use of the SoccerServlet to registered users.
    First, you must define some users and passwords for your AppServer.
    In the "Services" pane select the Servers part of the tree. Right-click on the Glassfish server and pick view Admin Console. A browser window will open that has a login page.
    The AppServer is initialized with an administration user called "admin" whose password is "adminadmin". Login as admin. (It’s your server, you can change the admin password if you wish.)
    In the left frame of the administrator page, select the "Configuration/Security" branch of the tree.

    Administering security

    Then select the "File realm" subtree and "Manage users".

    Edit realm

    Create a few users and their passwords.

    New User
    These users can be in group "soccer".
    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.

    Web.xml 'wizard'

    Switch to the "Security" tab in the wizard editor. You will have to add security roles and constraints, and set the login control
    Start by defining a rolename:

    Security options
    To specify a constraint you pick the "resource" that is constrained; its the SoccerServlet really:
    What gets secured?

    (That URL pattern should be /SoccerServlet - you will get a deployment error if it doesn't start with /.)


    The constraint is that authentication is required for the soccerresults "resource".

    Authenticate the users
    You have to specify the authentication mechanism. One can be ambitious and have client and server certificates! You can simply rely on HTTP authentication - defining a "realm" and having the browser display a simple "login to realm" dialog:
    Use simple HTTP authenticate
    Here it will be sufficient to use the "Basic" HTTP authentication mechanism and rely on the standard prompt.
    Get the usual realm prompt
    Generally, it is better if you use customized versions of a login page (and error page). These allow you to present a login request that relates specifically to your controlled web site.
    Finally, you have to relate the users and groups defined in the AppServer to the roles defined in the servlet deployment document. This involves editing the sun-web.xml file:
    Map users/groups to role
    Rebuild and redeploy the application. You should be prompted to login before you can use the SoccerServlet. Use one of the username/password combinations that you defined in AppServer.

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