MVC was first introduced by Trygve Reenskaug, a Smalltalk developer at the Xerox. The author of this article built this example using the NetBeans Swing GUI. Creating a GUI With Java Swing, also known as The Swing Tutorial, shows.
What Is Model-View-Controller (MVC)?
If you've programmed with graphical user interface (GUI) libraries in the past 10 years or so, you have likely come across the model-view-controller (MVC) design. MVC was first introduced by Trygve Reenskaug, a Smalltalk developer at the Xerox Palo Alto Research Center in 1979, and helps to decouple data access and business logic from the manner in which it is displayed to the user. More precisely, MVC can be broken down into three elements:
- Model - The model represents data and the rules that govern access to and updates of this data. In enterprise software, a model often serves as a software approximation of a real-world process.
- View - The view renders the contents of a model. It specifies exactly how the model data should be presented. If the model data changes, the view must update its presentation as needed. This can be achieved by using a push model, in which the view registers itself with the model for change notifications, or a pull model, in which the view is responsible for calling the model when it needs to retrieve the most current data.
- Controller - The controller translates the user's interactions with the view into actions that the model will perform. In a stand-alone GUI client, user interactions could be button clicks or menu selections, whereas in an enterprise web application, they appear as
GET
andPOST
HTTP requests. Depending on the context, a controller may also select a new view -- for example, a web page of results -- to present back to the user.
Figure1.A Common MVC Implementation
Interaction Between MVC Components
This section will take a closer look at one way to implement Figure 1 in the context of an application in the Java Platform, Standard Edition 6 (Java SE 6). Once the model, view, and controller objects are instantiated, the following occurs:
- The view registers as a listener on the model. Any changes to the underlying data of the model immediately result in a broadcast change notification, which the view receives. This is an example of the push model described earlier. Note that the model is not aware of the view or the controller -- it simply broadcasts change notifications to all interested listeners.
- The controller is bound to the view. This typically means that any user actions that are performed on the view will invoke a registered listener method in the controller class.
- The controller is given a reference to the underlying model.
Once a user interacts with the view, the following actions occur:
- The view recognizes that a GUI action -- for example, pushing a button or dragging a scroll bar -- has occurred, using a listener method that is registered to be called when such an action occurs.
- The view calls the appropriate method on the controller.
- The controller accesses the model, possibly updating it in a way appropriate to the user's action.
- If the model has been altered, it notifies interested listeners, such as the view, of the change. In some architectures, the controller may also be responsible for updating the view. This is common in Java technology-based enterprise applications.
Figure 2 shows this interaction in more detail.
Figure 2.A Java SE Application Using MVC
As this article mentioned earlier, the model does not carry a reference to the view but instead uses an event-notification model to notify interested parties of a change. One of the consequences of this powerful design is that the many views can have the same underlying model. When a change in the data model occurs, each view is notified by a property change event and can update itself accordingly. For example, Figure 3 shows two views that use the same data model.
Figure 3.Multiple Views Using the Same Model
Modifying the MVC Design
A more recent implementation of the MVC design places the controller between the model and the view. This design, which is common in the Apple Cocoa framework, is shown in Figure 4.
Figure 4.An MVC Design Placing the Controller Between the Model and the View
The primary difference between this design and the more traditional version of MVC is that the notifications of state changes in model objects are communicated to the view through the controller. Hence, the controller mediates the flow of data between model and view objects in both directions. View objects, as always, use the controller to translate user actions into property updates on the model. In addition, changes in model state are communicated to view objects through an application's controller objects.
Thus, when all three components are instantiated, the view and the model will both register with the controller. Once a user interacts with the view, the events are nearly identical:
- The view recognizes that a GUI action -- for example, pushing a button or dragging a scroll bar -- has occurred, using a listener method that is registered to be called when such an action occurs.
- The view calls the appropriate method on the controller.
- The controller accesses the model, possibly updating it in a way appropriate to the user's action.
- If the model has been altered, it notifies interested listeners of the change. However, in this case, the change is sent to the controller.
Why adopt this design? Using this modified MVC helps to more completely decouple the model from the view. In this case, the controller can dictate the model properties that it expects to find in one or more models registered with the controller. In addition, it can also provide the methods that effect the model's property changes for one or more views that are registered with it.
Using the Modified MVC
This section of the article shows you how to put this design into practice, starting with the model. Suppose that you want to paint some text using a simple display model with five properties. Code Sample 1 shows a simple component that you can use to create such a model.
Code Sample 1
Note that the rest of the accessors follow the standard JavaBeans model, although they are omitted in Code Sample 1. For reference, Code Sample 2 shows the underlying
AbstractModel
class, which simply uses the javax.beans.PropertyChangeSupport
class to register, deregister, and notify interested listeners of changes to the model.Code Sample 2
The Controller
Between the model and view lies the controller. First, take a look at the code for the abstract controller superclass, as shown in Code Sample 3.
Code Sample 3
The
AbstractController
class contains two ArrayList
objects, which are used to keep track of the models and views that are registered. Note that whenever a model is registered, the controller also registers itself as a property change listener on the model. This way, whenever a model changes its state, the propertyChange()
method is called and the controller will pass this event on to the appropriate views.The final method,
setModelProperty()
, employs some magic to get its work done. In order to keep the models completely decoupled from the controller, the code samples in this article have employed the Java Reflection API. In this case, when this method is called with the desired property name, you hunt through the registered models to determine which one contains the appropriate method. Once you find it, you invoke the method using the new value. If the method is not called, the getMethod()
will throw a NoSuchMethodException
, which the exception handler ignores, allowing the for-
loop to continue.Code Sample 4 shows the source code for the default controller class. This class consists of only property constants and methods called by the GUI event listeners of the view.
Code Sample 4
The View
This example will have two views displaying the data from the model: a property-editor view and a graphical page view. Both of these are implementations of a
JPanel
, inserted into either a JDialog
or JFrame
. The dialog box allows the user to update the values of the model, and the frame panel simply reflects the changes as the final textual display. The author of this article built this example using the NetBeans Swing GUI Builder, formerly referred to as Project Matisse, to design the GUI forms.Code Sample 5 shows the source code for the property-editor view, the more interesting of the two. The first section is simply devoted to initialization of the components, which for the most part was automatically generated by the NetBeans integrated development environment (IDE) in the
initComponents()
method. All of this section is omitted but is present in the downloadable code. Any other initialization that you need to perform -- in this case, creating custom models for JSpinner
and JSlider
objects or adding DocumentListeners
to the JTextField
components -- is handled in the localInitialization()
method.Code Sample 5
Note that the automatically generated NetBeans IDE code folds in the source code so that the developer can collapse each of these sections when it is not needed:
If you're using the NetBeans IDE, this practice is highly recommended.
The second section of the
PropertiesViewPanel
class deals exclusively with the model. In Code Sample 6, a modelPropertyChange()
method is called by the controller whenever the model reports a state change.Code Sample 6
Again, this code sample omits portions of the code that are similar to the sections shown.
The final portion consists of the GUI event listeners. Code Sample 7 contains listeners that are called whenever GUI events occur, such as pushing the
Change Font
button or the Opacity
spinner buttons, or resetting the text in any of the text fields. These are largely event listeners that most Swing developers are already familiar with. If you're using the NetBeans IDE, you'll see that the IDE can automatically generate many of these using the GUI developer.Code Sample 7
Issues With Application Design
Once the application is up and running, you immediately run into a problem. Consider the following chain of events:
- One of the Swing components in the view receives a change, presumably from the user action.
- The appropriate controller method is called.
- The model is updated. It notifies the controller of its property change.
- The view receives a change event from the controller and attempts to reset the value of the appropriate Swing components.
- The appropriate controller method is called, and the model is updated again.
At this point, any of three different scenarios can occur, depending on what Swing component you use and how robust your model is.
- The Swing component that prompted the initial change refuses to update itself the second time, noting that its property state cannot be updated again while it is in the process of notifying listeners of the initial state change. This primarily occurs when you use Swing text components.
- The model notes that the value of the second update matches that of the first, its current value, and refuses to send a change notification. This is always a safe programming practice, and it automatically occurs if you use the
PropertyChangeSupport
class provided in thejava.beans
package. However, it does not keep the model from receiving a redundant update. - No safeguards are in place on either the model or the Swing component, and the program enters an infinite loop.
This issue occurs because the Swing components are autonomous. For example, what happens if the user presses the up arrow of the
JSpinner
component in PropertiesViewPanel
, incrementing the spinner's value by one? After the value is updated, a GUI event listener method that is listening for value changes is called, opacitySpinnerStateChanged()
, which in turn calls the controller and then updates the appropriate property in the model.With a traditional MVC design, the view would still contain the previous value, and the change in the model would update the view to the current value. However, there is no need to update the Swing component because it has already reset itself to the correct value -- it did so before it even passed an event to the controller.
How do you get around this? One way is to write a mechanism that tells the model or the controller not to propagate a change notification under these circumstances, but this is not a good idea. Remember that more than one view may be listening for changes on the model. If you shut down the change notification for the model, no other listeners, including other views, will be notified of the change. In addition, other components in the same view may rely on the property change notification, with a slider and spinner combination, for example.
Ideally, each Swing component would be aware of its current value and the value that the view is trying to set it to. If they match, no change notifications will be sent. However, some Swing components include this logic, and others do not. One possible solution is to check the incoming changed value of the model against the current value stored in the Swing component. If they are identical, there is no need to reset the value of the Swing component.
Code Sample 8 shows an update of the
modelPropertyChange()
method to demonstrate this approach.Code Sample 8
The final example, which uses two delegate views, is shown in Figure 5. The second delegate makes use of the Java 2D libraries to display the text, which is beyond the scope of this article. However, the source code is relatively easy to follow and is included in the downloadable source code.
Figure 5.Both Views Attached to a Single Model
Common Swing Component Listeners
As this article has shown throughout, part of the initialization of each delegate or controller requires you to subscribe to various Swing component events. However, individual Swing components can often generate multiple event types. Table 1 presents some common listener methods.
Event to Monitor | Swing Event Listener Method |
---|---|
JButton pressed; JCheckBox pressed; JRadioButton pressed; JToggleButton toggled. | JButton.addActionListener(java.awt.event.ActionListener) |
JSpinner value changed. | JSpinner.addChangeListener(javax.swing.event.ChangeListener) |
JTextField , JFormattedTextField , JPasswordField or JTextArea character(s) are added, changed, or deleted. | JTextField.getDocument().addDocumentListener(javax.swing.event.DocumentListener) |
JTextField return button is pressed, or focus switches to another component. | JTextField.addActionListener(java.awt.event.ActionListener) |
JComboBox new entry is selected. from list. | JComboBox.addActionListener(java.awt.event.ActionListener) |
JComboBox editor (typically a text field) characters are added, changed, or deleted. | JTextField editor = ((JTextField)comboBox.getEditor().getEditorComponent()); editor.getDocument().addDocumentListener(javax.swing.event.DocumentListener) |
JComboBox return button is pressed. | JComboBox.addActionListener(java.awt.event.ActionListener) |
JComboBox pop-up menu is about to become visible, invisible, or be cancelled without a selection. | JComboBox.addPopupMenuListener(javax.swing.event.PopupMenuListener) |
JList new entry is selected. | JList.addListSelectionListener(javax.swing.event.ListSelectionListener) |
JTabbedPane new tab is selected. | JTabbedPane.addChangeListener(javax.swing.event.ChangeListener) |
JScrollBar adjustment is made. | JScrollBar.addAdjustmentListener(java.awt.event.AdjustmentListener) |
JScrollPane adjustment is made. | JScrollPane.getHorizontalScrollBar().addAdjustmentListener(java.awt.event.AdjustmentListener) JScrollPane.getVerticalScrollBar().addAdjustmentListener(java.awt.event.AdjustmentListener) |
JPopupMenu is about to become visible, invisible, or be cancelled without a selection. | JPopupMenu.addPopupMenuListener(javax.swing.event.PopupMenuListener) |
JMenu is about to be become visible or invisible, or be cancelled without a selection. | JMenu.addMenuListener(javax.swing.event.MenuListener) |
JMenuItem (in standard or pop-up menu) is selected. | JMenuItem.addActionListener(java.awt.event.ActionListener) |
JSlider value is changed. | JSlider.addChangeListener(javax.swing.event.ChangeListener) |
Conclusion
MVC is one of the staples of any GUI programmer's toolkit. This article has shown how to implement a variation of the MVC design using Java SE and the Swing libraries. In addition, it has demonstrated some common issues that programmers may face when using MVC, as well as listed common Swing component events that any Java platform programmer can use when creating a view.
For More Information
- Creating a GUI With Java Swing, also known as The Swing Tutorial, shows you how to get started using the Java Swing components.
- A Swing Architecture Overview gives the inside story on how Swing uses a variant of MVC.
- If you are curious as to how the textual portion of the Java 2D libraries work, take a look at this article.
This document shows you how to construct a simple web MVC application using the Spring Framework. The application enables a user to enter her name in a text field, and upon clicking OK, the name is returned and displayed on a second page with a welcome greeting.
The Spring Framework is a popular open source application framework that can make Java EE development easier. It consists of a container, a framework for managing components, and a set of snap-in services for web user interfaces, transactions, and persistence. A part of the Spring Framework is Spring Web MVC, an extensible MVC framework for creating web applications.
The IDE provides built-in support for Spring Framework 4.x and 3.x. Framework libraries are packaged with the IDE and are automatically added to the project classpath when the framework is selected. Configuration settings are provided, such as naming and mapping of the Spring Web MVC
DispatcherServlet
. The JSTL library can optionally be registered upon project creation. Support for Spring XML bean configuration files is also provided, including the following functionality:- Code completion. Invoked in Spring XML configuration files for Java classes as well as bean references.
- Navigation. Hyperlinking of Java classes and properties mentioned in Spring bean definitions, as well as hyperlinking to other Spring bean references.
- Refactoring. Renaming of references to Java classes in Spring XML configuration files.
For more information on the Spring Framework, visit http://www.springsource.org/. For a more fine-grained explanation of how Spring Framework artifacts behave and interact with other objects in an application, see the official Spring Framework Reference Documentation, or consult the Spring Framework API documentation.
Contents
- Setting up a New Project with Spring Web MVC Support
To complete this tutorial, you need the following software and resources.
Software or Resource | Version Required |
---|---|
NetBeans IDE | 7.2, 7.3, 7.4, 8.0, Java EE |
Java Development Kit (JDK) | version 7 or 8 |
GlassFish server | 3.x, 4.x |
![Modelo Modelo](/uploads/1/2/6/2/126266032/263970030.png)
Notes:
- The Java installation of the IDE enables you to optionally install and register the GlassFish server with the IDE.
- If you need to compare your project with a working solution, you can download the sample application.
Setting up a New Project with Spring Web MVC Support
Creating a Spring Web MVC Skeleton Project
Start by creating a new project for a web application using the Spring Framework.
- Choose New Project (Ctrl-Shift-N; ⌘-Shift-N on Mac) from the IDE's File menu. Select the Java Web category, then under Projects select Web Application. Click Next.
- In Project Name, type in HelloSpring. Click Next.
- In Step 3: Server and Settings, deselect the Enable Contexts and Dependency Injection option, as you are not working with the JSR-299 specification in this tutorial.
- Confirm that the GlassFish server is selected in the Server drop-down list. Click Next. The Java EE version depends upon the version of the server that is selected. The default Java EE version is Java EE 7 Web when the selected server is GlassFish Server 4.0.
- In Step 4, the Frameworks panel, select Spring Web MVC.
- Select Spring Framework 3.x in the Spring Library drop-down list. Note that the IDE enables you to add the Spring 4.x library to your project, but for this tutorial you will use SimpleFormController that is not supported in Spring 4.x. Also, when you select Spring Web MVC, note that the JSTL (JavaServer Pages Standard Tag Library) library is added to the classpath during project creation by default. Deselect this option (as in the above screenshot), since you do not require JSTL for this tutorial.
- Click the Configuration tab and note that the wizard enables you to specify the name and mapping of the Spring Dispatcher servlet.
- Click Finish. The IDE creates a project for the entire application, including all metadata, as well as the project's Ant build script which you can inspect from the Files window (Ctrl-2; ⌘-2 on Mac). You can view the template structure from the Projects window (Ctrl-1; ⌘-1 on Mac). Also note that four files open by default in the IDE's editor:
dispatcher-servlet.xml
,applicationContext.xml
,redirect.jsp
, andindex.jsp
. - In the Projects window, expand the new project's Libraries node and note that the Spring JARs are included in the project's classpath.
Running the Skeleton Project
Before making any changes to project files, try running the new project in the IDE:
- Click the Run Project ( ) in the IDE's main toolbar. The IDE automatically starts the GlassFish server if it is not already running, compiles the project, then deploys it to the server. Note any output displayed in the IDE's Output window (Ctrl-4; ⌘-4 on Mac). The generated output completes with a
BUILD SUCCESSFUL
message.
The IDE's default browser starts up, and you see content from the welcome page view (/WEB-INF/jsp/index.jsp
).
When you run your project in the IDE, the project is compiled and deployed to the server, and then opens in your default browser. Furthermore, the IDE provides a Deploy on Save feature, which is activated by default for web projects. When you save files in the editor, your project is automatically recompiled and deployed to the server. To view changes, you can simply refresh pages in your browser.
In order to understand what just took place, start by examining the project's deployment descriptor (
web.xml
). To open this file in the Source Editor, right-click the WEB-INF
> web.xml
node in the Projects window and choose Edit. The default entry point for the application is redirect.jsp
:Within
redirect.jsp
, there is a redirect statement that points all requests to index.htm
:In the deployment descriptor, note that all requests for URL patterns that match
*.htm
are mapped to Spring's DispatcherServlet
.The fully qualified name of the dispatcher servlet, as shown above, is
org.springframework.web.servlet.DispatcherServlet
. This class is contained in the Spring library, which was added to the project classpath when the project was created. You can verify this in the Projects window by drilling down from the Libraries node. Locate the spring-webmvc-3.1.1.RELEASE.jar
, then expand it to find org.springframework.web.servlet
> DispatcherServlet
.The
DispatcherServlet
handles incoming requests based on configuration settings found in dispatcher-servlet.xml
. Open dispatcher-servlet.xml
by clicking on its tab in the editor. Note the following code.Three beans are defined in this file:
indexController
, viewResolver
, and urlMapping
. When the DispatcherServlet
receives a request that matches *.htm
such as index.htm
, it looks for a controller within urlMapping
that can accommodate the request. Above, you see that there is a mappings
property that links /index.htm
to indexController
.The runtime environment then searches for the definition of a bean named
indexController
, which is conveniently provided by the skeleton project. Note that indexController
extends ParameterizableViewController
. This is another class provided by Spring, which simply returns a view. Above, note that p:viewName='index'
specifies the logical view name, which is resolved using the viewResolver
by prepending /WEB-INF/jsp/
and appending .jsp
to it. This allows the runtime to locate the file within the application directory, and respond with the welcome page view (/WEB-INF/jsp/index.jsp
).Overview of the Application
The application you create is comprised of two JSP pages (which can be referred to as views in MVC terminology). The first view contains an HTML form with an input field asking for the user's name. The second view is a page that simply displays a hello message containing the user's name.
The views are managed by a controller, which receives requests to the application and decides which views to return. It also passes to the views any information that they need to display (this is called a model). This application's controller is named
HelloController
.In a complex web application, the business logic is not contained directly in the controller. Instead, another entity, named a service, is used by the controller whenever it needs to perform some business logic. In our application, the business logic is limited to the act of processing the hello message, and for this purpose you create a
HelloService
. Implementing a Service
Now that you are sure your environment is set up properly, you can begin extending the skeleton project according to your needs. Start by creating the
HelloService
class.- Click the New File ( ) button in the IDE's toolbar. (Alternatively, press Ctrl-N; ⌘-N on Mac.)
- Select the Java category, then select Java Class and click Next.
- In the New Java Class wizard that displays, type in HelloService for Class Name, and enter service for Package Name to create a new package for the class.
- Click Finish. The IDE creates the new class and opens it in the editor.
The
HelloService
class performs a very simple service. It takes a name as a parameter, and prepares and returns a String
that includes the name. In the editor, create the following sayHello()
method for the class (changes in bold).Implementing the Controller and Model
![Modelo vista controlador java netbeans tutorial pdf Modelo vista controlador java netbeans tutorial pdf](http://i.imgur.com/eCuptyU.png)
You can use a
SimpleFormController
to handle user data and determine which view to return.Note: SimpleFormController is deprecated in Spring 3.x. It is used in this tutorial for demonstration purposes. However, annotated controllers should be used instead of XML files.
- Open the New File wizard by pressing Ctrl-N (⌘-N on Mac). Under Categories select Spring Framework; under File Types select Simple Form Controller.
NetBeans IDE provides templates for various Spring artifacts, including the Spring XML Configuration File, theAbstractController
, and theSimpleFormController
. - Click Next.
- Name the class HelloController and create a new package for it by typing controller in the Package text field. Click Finish. The IDE creates the new class and opens it in the editor.
- Specify controller properties by uncommenting the setter methods that display by default in the class template. To uncomment the code snippet, highlight the code as in the image below, then press Ctrl-/ (⌘-/ on Mac).
Pressing Ctrl-/ (⌘-/ on Mac) toggles comments in the editor. - Make changes as follows (shown in bold). Setting the
FormView
enables you to set the name of the view that is used to display the form. This is the page that contains the text field allowing users to enter their name. Setting theSuccessView
likewise lets you set the name of the view that should display upon a successful submit. When you set theCommandName
you define the name of the command in the model. In this case, the command is the form object with request parameters bound onto it. Setting theCommandClass
allows you set the name of the command class. An instance of this class gets populated and validated upon each request.Note that an error is flagged forName
in thesetCommandClass()
method:You now need to create theName
class as a simple bean to hold information for each request. - In the Projects window, right-click on the project node and choose New > Java Class. The New Java Class wizard displays.
- Enter Name for the Class Name, and for Package select controller from the drop-down list.
- Click Finish. The
Name
class is created and opens in the editor. - For the
Name
class, create a field namedvalue
, then create accessor methods (i.e., getter and setter methods) for this field. Start by declaring thevalue
field:To quickly type out 'private
' you can type 'pr
' then press Tab. The 'private
' access modifier is automatically added to the line. This is an example of using the editor's code templates. For a full list of code templates, choose Help > Keyboard Shortcuts Card.
The IDE can create accessor methods for you. In the editor, right-click onvalue
and choose Insert Code (or press Alt-Insert; Ctrl-I on Mac). In the popup menu, choose Getter and Setter. - In the dialog that displays, select the
value : String
option, then click OK. ThegetValue()
andsetValue()
methods are added to theName
class: - Press Ctrl-Tab and choose
HelloController
to switch back to theHelloController
class. Note that the previous error badge has disappeared since theName
class now exists. - Delete the
doSubmitAction()
method and uncomment theonSubmit()
method. TheonSubmit()
method enables you to create your ownModelAndView
, which is what is required here. Make the following changes: As indicated above, thecommand
is recast as aName
object. An instance ofModelAndView
is created, and the success view is obtained using a getter inSimpleFormController
. Finally, the model is populated with data. The only item in our model is the hello message obtained from theHelloService
created earlier. You use theaddObject()
method to add the hello message to the model under the namehelloMessage
. - Fix import errors by right-clicking in the editor and choosing Fix Imports (Ctrl-Shift-I; ⌘-Shift-I on Mac). Note. Confirm that org.springframework.validation.BindException and org.springframework.web.servlet.ModelAndView are selected in the Fix All Imports dialog box.
- Click OK. The following import statement is added to the top of the file: As stated in the API documentation, this class 'represents a model and view returned by a handler, to be resolved by a
DispatcherServlet
. The view can take the form of aString
view name which will need to be resolved by aViewResolver
object; alternatively aView
object can be specified directly. The model is aMap
, allowing the use of multiple objects keyed by name.'
Note that at this stage, not all errors are fixed because the class still cannot identify theHelloService
class, nor make use of itssayHello()
method. - Within
HelloController
, declare a private field namedHelloService
: Then create a public setter method for the field: Finally, right-click in the editor and choose Fix Imports (Ctrl-Shift-I; ⌘-Shift-I on Mac). The following statement is added to the top of the file: All errors should now be fixed. - Register
HelloService
inapplicationContext.xml
. OpenapplicationContext.xml
in the editor and enter the following bean declaration:Spring support in the IDE includes code completion within XML configuration files for Java classes as well as bean references. To invoke code completion, press Ctrl-Space when working in the editor: - Register
HelloController
indispatcher-servlet.xml
. Opendispatcher-servlet.xml
in the editor and enter the following bean declaration:
Implementing the Views
To implement the view for this project, you need to create two JSP pages. The first, which you will call
nameView.jsp
, serves as the welcome page and allows users to input a name. The other page, helloView.jsp
, displays a greeting message that includes the input name. Begin by creating helloView.jsp
.- In the Projects window, right-click the WEB-INF >
jsp
node and choose New > JSP. The New JSP File wizard opens. Name the file helloView. - Click Finish. The new JSP page is created in the
jsp
folder and opens in the editor. - In the editor, change the file's title to
Hello
, and change the output message to retrieve thehelloMessage
of theModelandView
object that is created inHelloController
. - Create another JSP page in the same manner as above, but name it
nameView
. - In the editor, add the following Spring tag library declaration to
nameView.jsp
. This imports the Spring tag library, which contains tags useful when implementing views as JSP pages. - Change the contents of the
<title>
and<h1>
tags to read:Enter Your Name
. - Enter the following code beneath the
<h1>
tags: spring:bind allows you to bind a bean property. The bind tag provides a bind status and value, which you use as the name and value of the input field. This way, when the form is submitted, Spring will know how to extract the submitted value. Here, our command class (controller.Name
) has avalue
property, therefore you set thepath
tovalue
.
spring:nestedPath enables you to prepend a specified path to a bean. So, when used withspring:bind
as shown above, the path to the bean becomes:name.value
. As you recall, the command name ofHelloController
isname
. Therefore, this path refers to thevalue
property of a bean namedname
in the page scope. - Change the relative entry point for the application. Currently, the project entry point is still
index.htm
which, as described in Running the Skeleton Project above, redirects toWEB-INF/jsp/index.jsp
. You can specify an entry point for the project when it is deployed and run. In the Projects window, right-click the project node and choose Properties. The Project Properties dialog displays. Under Categories select Run. In the Relative URL field, type in/hello.htm
, then click OK.
At this moment you may wonder where the mapping ofhello.htm
toHelloController
is located. You have not added a mapping to theurlMapping
bean, as is the case forindex.htm
, the skeleton project's welcome page. This is possible with a bit of Spring magic provided by the following bean definition indispatcher-servlet.xml
: This bean is responsible for automatically creating an URL mapping for all controllers registered in the file. It takes the fully-qualified class name of the controller (in our case,controller.HelloController
) and strips the package name andController
suffix, then uses the result as a URL mapping. Therefore, forHelloController
it creates ahello.htm
mapping. This magic however does not work for controllers that are included in the Spring Framework, such asParameterizableViewController
. They require an explicit mapping. - In the Projects window right-click the project node and choose Run. This compiles, deploys and runs the project. Your default browser opens, displaying
hello.htm
as the project'snameView
:
Enter your name in the text field and click enter. ThehelloView
displays with a greeting message:
See Also
This concludes the Introduction to the Spring Framework in NetBeans IDE. This document demonstrated how to construct a simple web MVC application in the NetBeans IDE using the Spring Framework, and introduced you to the IDE's interface for developing web applications.
You are encouraged to continue learning about the Spring Framework by working through other tutorials in NetBeans IDE, such as Developing a Spring Framework MVC Application Step-by-Step using NetBeans and the GlassFish server. This is the official Spring Framework tutorial by Thomas Risberg which has been adapted for NetBeans IDE by Arulazi Dhesiaseelan.
Many of the Spring NetBeans Module capabilities can also be applied to non-web based Spring framework applications.
For other related tutorials, see the following resources:
- Adding Support for a Web Framework. A basic guide describing how to add support by installing a web framework plugin using the NetBeans Update Center.
- Introduction to JavaServer Faces 2.0. Demonstrates how to add JSF 2.0 support to an existing project, wire managed beans, and take advantage of Facelets templating.