Hello Spring 3 Web MVC using Netbeans

6-Nov-2014 –> Please note that a new blog now exists for Spring 4 Web MVC using Maven and Netbeans with Java configuration (no XML at all) here – John

This tutorial will simply detail one correct way to create a simple Spring 3 web application using Netbeans.

Note: The Spring plugin for Netbeans (that is being distributed with Netbeans 7.7.1 and previous) is actually designed for Spring 2 and is therefore somewhat misleading. This tutorial overcomes that giving you the correct way to generate a Spring 3 web project.

A fully working Netbeans project is available for download at the bottom of the page.

Create a new web project in the usual way.

(I’ve used Apache Tomcat 7 for this example but any application server should do for this particular example)

At the point where you’re asked to include Frameworks, avoid the temptation to include the Spring framework. We’ll call the project ‘HelloSpring’.

The project should now look like this:

Spring 3 web MVC using Netbeans – Empty project

At this point, the following simple changes need to be made to configure the project.

Create a new folder called ‘jsp’ (aften called ‘pages’ instead) under the ‘WEB-INF’ folder.

Drag index.jsp into the newly created ‘jsp’ folder

Create a new Java file called ‘DefaultController’ under source packages. Give it a package of com.outbottle.hellospring.controllers

We now need to create two xml files under the ‘WEB-INF’ folder namely, ‘dispatcher-servlet.xml’ and ‘web.xml’ (Yep, there was no web.xml before this!!)The contents of ‘web.xml’ should be as follows:

Note that 1) <context-param> <param-value> points to the location of our dispatcher-servlet.xml file. 2) The <welcome-file> is simply / 3)The <servlet-mapping> <url-pattern> is also / loosly meaning that every http request should go through the defined dispatcher.

<context:component-scan base-package=”com.outbottle” /> tells Spring to look for files in these packages. Spring will expect to find Annotations on various Java files which will tell Spring how to handle those files in terms of dependency-injection, configuration and other stuff.

<mvc:annotation-driven /> is self explanatory for anyone familiar with Spring. Every Spring 3 project should have this. Without it, strange errors and exceptions will occur. So… if you have strange stuff going on and ask about it in a forum, you will automatically be asked immediately if you’ve included <mvc:annotation-driven /> in your ‘application context’.

At this point we need to add a few libraries to our project. Normally it’s best to download the latest versions of the spring distribution rather than using the libraries provided by Netbeans, but for simplicity we’ll use the existing spring libraries for this tutorial. Right click the project’s ‘Libraries’ folder and choose ‘Add Library’. Add the following Libraries: JSTL 1.1, Spring Framework 3.0.6 RELEASE, Spring Web MVC 3.0.6 RELEASE

Next up we need to code up our controller:

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

/*

* To change this template, choose Tools | Templates

* and open the template in the editor.

*/

packagecom.outbottle.hellospring.controllers;

importorg.springframework.stereotype.Controller;

importorg.springframework.ui.ModelMap;

importorg.springframework.web.bind.annotation.RequestMapping;

importorg.springframework.web.bind.annotation.RequestMethod;

@Controller

publicclassDefaultController{

@RequestMapping(value="/",method=RequestMethod.GET)

publicStringindex(ModelMap map){

map.addAttribute("hello","Hello Spring from Netbeans!!");

return"index";

}

}

Points to note here are:

RequestMapping with value of “/” matches our <welcome-file> set in ‘web.xml’. The RequestMethod is type GET meaning a HTTP GET request as opposed to a HTTP POST request.

When the url / (http://localhost:8084/HelloSpring/) is accessed, the method ‘index(ModelMap map)’ is accessed first. This method returns a String ‘index’ which equates to index.jsp due to the the ‘jspViewResolver’ configuration in ‘dispatcher-servlet.xml’ (prefixes ‘/WEB-INF/jsp’ and appends ‘.jsp’ to “index”)

ModelMap is one of several Objects that Spring can send to the method. Another example is HttpServletRequest. You just have to add them as parameters to the method and Spring will get the idea and pass them in for you.

Note that in the controller method ‘index()’, we’ve added an attribute to the ModelMap. Lets render this in our view. Edit index.jsp to this:

XHTML

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type"content="text/html; charset=UTF-8">

<title>JSP Page</title>

</head>

<body>

<h1>Hello Spring</h1>

<p>

This was passed in from the controller thus showing that

the controller was accessed before the page was rendered.

This is MVC (Model View Controller) in action.

</p>

<p>

Simple values can be rendered as so \${} i.e. here's the value from the controller: <blockquote>${hello}</blockquote>

</p>

</body>

</html>

The project should now look like this:

Run it and see it in action:

Next and finally, we’ll demonstrate linking to a second page and passing in an object to it.

Create a new bean class called ‘Person’ in packge ‘com.outbottle.hellospring.entities’. Give it two member variables as per below. Add a setter and getter for each member (by pressing [alt]+[insert]):

Thank God! A tutorial that works! I mean, I am a little teary eyed right now. I always need a starting point to learn something new. I have spent a WEEK looking for a blasted Spring MVC starting point tutorial – that works! 30 seconds… and it works. I am going to rename my firstborn child after you… I am also going to start a rating site.. .like verisign.. THIS WORKS and THIS CRAP DONT WORK.. Thanks again.. it works… thanks again..

William

Oh dude! You’re a lifesaver thank you thank you thank you!

Ashwin

Finally ….. thanks for posting …… yes it was very much helpful 🙂

Rani Agrawal

really it is helping for me……nice explanation.. thanks for posting. 🙂 🙂

Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 1 in XML document from ServletContext resource [/WEB-INF/dispatcher-servlet.xml] is invalid; nested exception is org.xml.sax.SAXParseException: Content is not allowed in prolog.. Please see server.log for more details.

C:UserskaviDocumentsNetBeansProjectsSpringnbprojectbuild-impl.xml:726: The module has not been deployed.

See the server log for details.

BUILD FAILED (total time: 8 seconds)

it comes like this help me…

NameNotTaken

Hmmm, sounds like something is wrong with /WEB-INF/dispatcher-servlet.xml. Perhaps compare it to the code provided here and see what might be causing the issue. (On the other hand it could be a more complex issue). Feel free to post a link to a project demonstrating the problem, I can take a look.

kaviyarasu

that demo hyper link is not working.on click it shows request resource is not available().my IDE is Netbeans 7.1.2 i wrote the controller as

Thank you very much John. I didn’t expect that NetBeans had templates for Spring 2 Web MVC. Your tutorial have been of very much help to me. Thank you again!

muhit

WOW great!!!

thodoris

I am trying to debug this app in order to see the flow, but i get this message:

Attaching to tomcat_shared_memory_id
shmemBase_attach failed: The system cannot find the file specified

and the debugger never opens (tomcat 7, netbeans 7.1)

NameNotTaken

Hi Thodoris. I’ve just made a Netbeans project available for download, linked at the bottom of the blog. The project has no dependencies, it works out-of-the-box. Just open it with Netbeans and run it.

I guess I should have made the download available a long time ago!

Anyway, it’s there now, hope it helps in resolving your issues.

John

Tanumita

Thank you so much for such a nice demonstration. Very helpful for Spring beginners.

Wildcard

Thanks man. It works. 🙂 I have been searching an spring example program that works for a couple of days. Thanks again.

joe

This is a great tutorial. I have been able to replicate the same using Eclipse, the set-up differed a little. I am having only one minor problem. When I select the hyperlink to View Demo – the project is dropped from the url and the link is no good. The url I should see is http:127.0.0.1:8080/HelloSpring/viewdemo but instead I have http:127.0.0.1:8080/viewdemo. If I manually correct it the demo.jsp appears correctly. How is this bug overcome?

NameNotTaken

Hi Joe

You can use this for all links to ensure they are absolute rater than relative relative. The same applies to <form> action attributes.

Option 3: (Best option in my opion because option 2 has issues with appending ";jsessionid=blahblah" onto the end of the url)
<%@ taglib uri="http://java.sun.com/jsp/jstl/core&quot; prefix="c" %> (put this at the top of the page)

Thank you. Just a minor fix. Removed servletContext from the property of value..

ghaffari el mehdi

thank you so much for such an awesome tutorial , itt was really helpful ^^

morpheous

This is by far, the most concise and informative tutorial for getting started with Spring. Very well done for this brilliant article. It is articles like this that make the internet a great place to learn from.

I would sincerely urge everyone who has found this article useful (which should be the vast majority of readers), to bookmark this page on sites like delicious etc and promote it to other developers; it is the very least we can do to help the author, and I am sure he will appreciate the gesture.

Sunset Dreamer

Thank you for this great tutorial I am looking forward to going through the other ones. This was invaluable in my learning spring. You boiled everything down to the simplest terms and have removed my confusion with spring.

Umesh

Very good tutorial,this helps me.
thanks alot

RIcardo

Thank you so much man, you really helped me, I have been looking for some like this for days, regards from Mexico 🙂

right_now

Nice tutorial! There’s a great RAD tool out called Jigy Generator that automatically spits you out a fully configured spring project which can already connect to your database, authenticate users, handle file uploads, etc. It even creates dao’s, domain objects and validators in your project by reverse engineering your database. This way you don’t have to get mired in the low level details of spring and hibernate… It Just Works! You can download the project at http://www.getjigy.com

Cozy

At long last.

Our industry seems to want to mystify stuff……This tutorial makes teh simple … well simple! Oh and it works. Nice change from other stuff I have found.