NetBeans IDE 4.0  Web Application Starter kit

Recommended NetBeans reading!
This web application is heavily influenced by Jayson falkner & Kevin R Jones most excellent book: "Servlets and JSP the J2EE Web Tier."

If you are interested in the book you can pick it up at
Amazon.com:
http://www.amazon.com/exec/obidos/ASIN/0321136497/102-1831065-4468902

Introduction

This tutorial intent to walk you through the basic of using netbeans 4.0 to develop a model view control web application for you to build on further. we will start off by designing a POJO object as our model, a set of view files and a controller. when this is done we will extend the project to use JDBC to  interact wit a underlaying MyQL datastore

Download Files & Sources


Starting up


Creating a new  web application

  1. Choose File > New Project. Under Categories, select Web. Under Projects, select Web Application and click Next.
Wizard2
  1. Under Project Name, enter Netbeans4Tutorial.

Wizard1
  1. Leave the Set as Main Project checkbox selected. Notice that the Context Path is /Netbeans4Tutorial.
  2. notice that Servlet specification 2.4 is described in the Description panel, this is a reqirement for us since we are going to make extencive use of EL (expresion language) in this project
  3. Click Finish. The IDE creates the $PROJECTHOME/Netbeans4Tutorial project folder. The project folder contains all of your sources and project metadata, such as the project Ant script. The HelloWeb project opens in the IDE. You can view its logical structure in the Projects window and its file structure in the Files window.

Creating our POJO Model


Creating the Model

  1. Expand the  project node and the Source Packages node. Note the Source Packages node only contains an empty default package node.
  2. Right-click the Source Packages node and choose New > java class.
  3. Enter StarterModel in the Class Name text box and enter org.netbeans.starttutorial.model in the Package combo box.
  4. Click Finish.
StarterModel

Adding fields and metodes

  1. Now that netbeans has generated an empty class definition for us, it is time to populate it with some field names.
  2. Type or copy these field names to you mode.
  3. Right click on the field names and select encapsulate from the Refactoring menu
  4. private int id;
    private String authour;
    private String summary;
    private String story;
    private String topic;
    private java.sql.Timestamp date;
  5. It should look like this. enable all checkboxes, and press "next >"
encapsulate.jpg

The figure shows us selecting all fields to generate accsessors and mutators for these fields.

metodes.jpg


And finally add the import statements and the to metodes below to your starterModel class to complete it
import java.util.ArrayList;
import java.util.List;




public List getpopulateStarterModelArray ()
{

List starterModelarray = new ArrayList ();
StarterModel s =
getModel (1, "Hello World ", "The First part of ", "the tutorial is ", "over",new java.util.Date ());


StarterModel st =
getModel (2, "now ", "it is ", "time to ", "add some more pages ",new java.util.Date ());

StarterModel stu =
getModel (3, "But first we have ", "to discuss", "what actually", "happened here dont you think",new java.util.Date ());

starterModelarray.add (s);
starterModelarray.add (st);
starterModelarray.add (stu);
return starterModelarray;
}

private StarterModel getModel (int a, String b,String c,String d,String e,java.util.Date f )
{
StarterModel sModel = new StarterModel ();
sModel.setId (a);
sModel.setAuthour (b);
sModel.setStory (c);
sModel.setTopic (d);
sModel.setSummary (e);
sModel.setDate (new java.sql.Timestamp (new java.util.Date ().getTime ()));
return sModel;
}

Making The Controller


Renaming a field

  1. Expand the  project node and the Source Packages node. Note the Source Packages node only contains an empty default package node.
  2. Right-click the Source Packages node and choose New > java class.
  3. Enter "FrontControllerFilter" in the Class Name text box, and enter org.netbeans.starttutorial.controller in the Package combo box.
  4. Click Finish.

Generating getter and setter methods

  1. The  FrontControllerFilter class  is listed here for your convinience to copy
     package org.netbeans.starttutorial.controller;

    import java.io.*;

    import javax.servlet.*;
    import javax.servlet.http.*;
    import org.netbeans.starttutorial.interfaces.PageProcessImplementation;
  2. public class FrontControllerFilter implements Filter
    {
    protected FilterConfig config = null;

    public void init (FilterConfig filterConfig)
    {
    config = filterConfig;
    }

    public void doFilter ( ServletRequest req, ServletResponse res,
    FilterChain chain ) throws IOException, ServletException
    {
    if (!(req instanceof HttpServletRequest))
    {
    throw new ServletException ("Filter requires a HTTP request.");
    }


    HttpServletRequest request = (HttpServletRequest)req;
    HttpServletResponse response = (HttpServletResponse)res;
    String uri = request.getRequestURI ();


    int begin = uri.lastIndexOf ("/")+1;
    int end = uri.lastIndexOf (".");

    String name = "pageholder";
    if (begin < end)
    {
    name = uri.substring (begin, end);
    }

    boolean doFilter = true;

    // try to load and run an implicit MVC control component.
    try
    {
    Object o = Class.forName ("org.netbeans.starttutorial.viewimplementation."+name).newInstance ();
    if (!(o instanceof PageProcessImplementation))
    {
    throw new ServletException ("no interface");
    }

    PageProcessImplementation control = (PageProcessImplementation)o;
    doFilter = control.processPageRequest (request, response);
    }
    catch (ClassNotFoundException e)
    {
    System.out.print ("\nClassNotFoundException \n" + e);
    }
    catch (InstantiationException e)
    {
    System.out.print ("\nInstantiationException \n" + e);
    }
    catch (IllegalAccessException e)
    {
    System.out.print ("\nIllegalAccessException \n" + e);
    }

    if (doFilter)
    {
    chain.doFilter (request, response);
    }
    }

    public void destroy ()
    {
    }
    }

Notice that we got an import statment error here. Thats because we have not created this perticular interface yet, thats next
error


Make a new java class with package name  and  class name like the one below
package org.netbeans.starttutorial.interfaces;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import javax.servlet.ServletException;


/**
* a public interfaqce for everyone to use
* todays task: See controller to figure out why we use this interface in the first plase
*/
public interface PageProcessImplementation
{
public boolean processPageRequest (HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException;
}

Creating a view page


Editing the default JavaServer Pages File and creating the code behind class

  1. Expand the  project node and the Web Pages node. Note the IDE has created a default JavaServer Pages page, index.jsp, for you. We are not going to use this one
  2. Right-click the web pages node and choose New > jsp.
  3. Enter "pageholder" in the jsp File_Name text box, and enter view in the folder field.
  4. Click Finish.
  5. pageholder
  6. paste or type inn so the pageholder.jsp file looks like this.

    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>

    <%--
    The taglib directive below imports the JSTL library. If you uncomment it,
    you must also add the JSTL library to the project. In the project properties
    choose Build -> Compiling sources and use the Add Libray... button to add
    the JSTL 1.1 library.
    --%>

    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>


    <html>
    <body>
    <c:forEach var="starterModel" begin="0" items="${arrayofstarterobjects}">
    <c:out value="${starterModel.id}" />
    <br>
    <c:out value="${starterModel.authour}" />
    <c:out value="${starterModel.story}" />
    <c:out value="${starterModel.summary}" />
    <c:out value="${starterModel.topic}" />
    <p>
    </c:forEach>

    Lets print out todays date to:
    <c:forEach var="starterModel" begin="0" end ="0" items="${arrayofstarterobjects}">
    ${starterModel.date}
    </c:forEach>
    </body>
    </html>

  1. Expand the  project node and the source Packages node.
  2. Right-click the web pages node and choose New > jsp.
  3. Enter "pageholder" in the jsp File_Name text box, and enter view in the folder field.
  4. Click Finish.

  5. pageholder.jpg
  6. package org.netbeans.starttutorial.viewimplementation;

    import java.io.IOException;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.netbeans.starttutorial.controller.*;
    import org.netbeans.starttutorial.model.*;
    import org.netbeans.starttutorial.interfaces.PageProcessImplementation;


    /**
    *
    * @author
    */
    public class pageholder implements PageProcessImplementation
    {
    public boolean processPageRequest (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
    ServletContext sc = request.getSession ().getServletContext ();
    try
    {
    StarterModel starterModel = new StarterModel ();

    request.setAttribute ("arrayofstarterobjects", starterModel.getpopulateStarterModelArray ());
    }
    catch(Exception e)
    {
    System.out.print ("Exception in class pageholder");
    }
    return true;
    }
    }

Changes to the web.xml  file

  1. Expand the  project node and the Web-INF node.
  2. Dobble click the web.xml file to bring it up in the editor
  3. paste or type inn so the web.xml file looks like this.
  4.      <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
    <filter>
    <filter-name>ControlFilter</filter-name>
    <filter-class>org.netbeans.starttutorial.controller.FrontControllerFilter</filter-class>
    </filter>
    <filter-mapping>
    <filter-name>ControlFilter</filter-name>
    <url-pattern>/view/*</url-pattern>
    </filter-mapping>
    <session-config>
    <session-timeout>30</session-timeout>
    </session-config>
    <welcome-file-list>
    <welcome-file>
    index.html
    </welcome-file>
    <welcome-file>
    index.htm
    </welcome-file>
    <welcome-file>
    view/pageholder.jsp
    </welcome-file>
    </welcome-file-list>
    </web-app>

Compiling and Running the Project


Adding required libraries

  • Right-click the project node and choose properties.
  • Select Build | compiling Sources
  • click Add Library
  • select JSTL 1.1 and click add library
  • click OK

  • libs.jpg

Building a project

  • Choose Build > Build Main Project (F11). The  project is built.

Running the main project

  • Choose Run > Run Main Project (F6) from the Run menu. Double-click the Output window's titlebar to maximize it so you can see all the output. Note that Ant builds Netbeans4Tutorial.war first and then compiles Netbeans4Tutorial using it. Finally, it deploys the web application using your default server. Double-click the Output window's titlebar again to minimize it.
  • Select the Files window and expand the HelloWeb project node. The build class files are in the build folder. The build WAR file is in the dist folder.
  • Press F6 to run the program again. Nothing new needs to be compiled, but the program is run.

  • run

PART 2 - ADDING A DATABASE


Creatin a data/base/store

  1. You need to install MySQL database if you have not done so allready.
  2. Make sure you have downloaded the newest mysql jdbc connector from: http://dev.mysql.com/downloads/connector/j/3.1.html
  3. Start up mysql
  4. open the runtime tab in Netbeans expand the database and Drivers node.
  5. right click and select Add Driver
  6. locate your mysql_connector.jar file and select add
  7. finish by pressing OK
  8. Now select the newly created mysql node, right click and choose connect using
  9. choose the mysql connection just created
  10. Enter jdbc:mysql://localhost/ as the database URL and supply your database username and password as approprate. press ok
  11. Right click the jdbc:mysql/localhost node  select execute command,  and insert this command CREATE DATABASE nbstarterkit and execute it. You have now created your own litte database
  12. Now disconect and delete the mysql node.
  13. repeat step 8 to 10 but using this URL instead: jdbc:mysql://localhost/nbstarterkit
  14. execute this command to make a table: CREATE TABLE `content` (
      `id` int(11) NOT NULL auto_increment,
      `author` varchar(50) default NULL,
      `summary` text,
      `story` text,
      `topic` varchar(50) default NULL,
      `date` datetime default NULL,
      PRIMARY KEY  (`id`)
    ) TYPE=MyISAM;
  15. and this one to populate it

    INSERT INTO `content` (`id`,`author`,`summary`,`story`,`topic`,`date`) VALUES ("1","Jan John Jullion-Ceccarelli","This guide is designed to help you transition your applications and IDE settings from NetBeans IDE 3.6 to NetBeans IDE 4.0, and to show you how to be even more productive with the new NetBeans IDE projects system.","This guide is designed to help you transition your applications and IDE settings from NetBeans IDE 3.6 to NetBeans IDE 4.0, and to show you how to be even more productive with the new NetBeans IDE projects system.","NEWS","2005-01-30 21:39:39");

Running the full JDBC enabled project

  1. make sure that  MySQL is up and running
  2. Add the mysql-connector.jar to your project
  3. Choose Run > Run Main Project (F6) from the Run menu. Double-click the Output window's titlebar to maximize it so you can see all the output. Note that Ant builds Netbeans4Tutorial.war first and then compiles Netbeans4Tutorial using it. Finally, it deploys the web application using your default server. Double-click the Output window's titlebar again to minimize it.
  4. Select the Files window and expand the HelloWeb project node. The build class files are in the build folder. The build WAR file is in the dist folder.
  5. Press F6 to run the program again. Nothing new needs to be compiled, but the program is run.
final.jpg
By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2013, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo