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

Spring 3 web MVC using Netbeans – Empty project

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

  1. Create a new folder called ‘jsp’ (aften called ‘pages’ instead) under the ‘WEB-INF’ folder.
  2. Drag index.jsp into the newly created ‘jsp’ folder
  3. Create a new Java file called ‘DefaultController’ under source packages. Give it a package of com.outbottle.hellospring.controllers
  4. 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.

    The content of the ‘dispatcher-servlet.xml’ file should be this:

    Important things to note here are:

    1. <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.
    2. <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’.
  5.  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
  6. Next up we need to code up our controller:

    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.

  7. 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:

  8. The project should now look like this:
    Netbeans Spring 3 Hello World
  9. Run it and see it in action:
    Java Spring 3 hello world using netbeans
  10. Next and finally, we’ll demonstrate linking to a second page and passing in an object to it.
    1. 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]):

    2. Create a new method in DefaultController called ‘demo’ as so:

      Note now, that the url to access this method is /viewdemo (http://localhost:8084/HelloSpring/viewdemo).

      A new Person object is instantiated, populated and inserted into the ModelMap where it can be retrieved in the view.

    3. Create a new page called demo.jsp in the same location as index.jsp (/WEB-INF/jsp/demo.jsp). This page will render the Person object and the ‘helloAgain’ message:

    4. Add a link to the index.jsp page that links the demo page (via the controller)

  11. Run the project…. Click the ‘Demo’ link on the index page to see the demo page: Netbeans Spring 3 tutorial hello world

That concludes this particular tutorial on getting a Java Spring 3 Web MVC application up and running correctly using Netbeans.

Please feel free to look through other tutorials in this category for further information.

Hope it was helpful…..

Download the Netbeans Project. Ready to run, out-of-the-box, all libraries included, no dependencies:  HelloSpring

 

 

45 Comments

  • 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..

  • i can’t do it ,,please have me this the error
    HTTP Status 500 – type Exception reportmessage description The server encountered an internal error () that prevented it from fulfilling this request.exception javax.servlet.ServletException: Servlet.init() for servlet dispatcher threw exception
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
    java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    java.lang.Thread.run(Thread.java:619)
    root cause org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 10 in XML document from ServletContext resource [/WEB-INF/dispatcher-servlet.xml] is invalid; nested exception is org.xml.sax.SAXParseException: The prefix “context” for element “context:annotation-config” is not bound.
    org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396)
    org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
    org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
    org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)
    org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)
    org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
    org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
    org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
    org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:131)
    org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:522)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:436)
    org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
    javax.servlet.GenericServlet.init(GenericServlet.java:160)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
    java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    java.lang.Thread.run(Thread.java:619)
    root cause org.xml.sax.SAXParseException: The prefix “context” for element “context:annotation-config” is not bound.
    com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
    com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:174)
    com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:388)
    com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:318)
    com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:310)
    com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2755)
    com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
    com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140)
    com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
    com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
    com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
    com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:235)
    com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:284)
    org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:75)
    org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:388)
    org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
    org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
    org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)
    org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)
    org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
    org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
    org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
    org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:131)
    org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:522)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:436)
    org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
    javax.servlet.GenericServlet.init(GenericServlet.java:160)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
    java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    java.lang.Thread.run(Thread.java:619)
    note The full stack trace of the root cause is available in the Apache Tomcat/7.0.27 logs.Apache Tomcat/7.0.27

  • Pingback: viagra
  • That!…. was freakin awesome! Other examples on the web over complicate the basics. Yours was to the point and you explained what needed to be noticed and explained. Nice job. Much appreciated.

  • Pingback: cialis
  • init:

    deps-module-jar:

    deps-ear-jar:

    deps-jar:

    library-inclusion-in-archive:

    library-inclusion-in-manifest:

    compile:

    compile-jsps:

    In-place deployment at C:UserskaviDocumentsNetBeansProjectsSpringbuildweb

    Initializing…

    deploy?DEFAULT=C:UserskaviDocumentsNetBeansProjectsSpringbuildweb&name=Spring&contextroot=/Spring&force=true failed on GlassFish Server 3.1.2

    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…

    • 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.

  • 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

    /*

    * To change this template, choose Tools | Templates

    * and open the template in the editor.

    */

    package com.outbottle.hellospring.controllers;

    import com.outbottle.hellospring.entities.person;

    import org.springframework.stereotype.Controller;

    import org.springframework.ui.ModelMap;

    import org.springframework.web.bind.annotation.RequestMapping;

    import org.springframework.web.bind.annotation.RequestMethod;

    /**

    *

    * @author kavi

    */

    @Controller

    public class DefaultController {

    @RequestMapping(value=”/viewdemo.htm”, method= RequestMethod.GET)

    public String demo(ModelMap map) {

    person person = new person();

    person.setName(“Jack”);

    person.setAge(52);

    map.put(“personObject”, person);

    map.addAttribute(“helloAgain”, “Hello (Again) Spring from Netbeans!!”);

    return “demo”;

    }

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

    public String index(ModelMap map) {

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

    person person = new person();

    person.setName(“Jack”);

    person.setAge(52);

    map.put(“personObject”, person);

    map.addAttribute(“helloAgain”, “Hello (Again) Spring from Netbeans!!”);

    return “index”;

    }

    }

    and my demo.jsp in WEB-INF/jsp/ like that

    JSP Page

    normal parameter:

    ${helloAgain}

    Person

    Name: ${personObject.name}

    Age: ${personObject.age}

    can u help me please

    • Hi kaviyarasu

      In your controller you’ve got:
      @RequestMapping(value=”/viewdemo.htm”, method= RequestMethod.GET)

      Going by the tutorial steps above it needs to be:
      @RequestMapping(value=”/viewdemo”, method= RequestMethod.GET)

      FYI, this particular url stuff is determined in web.xml.
      <servlet-mapping>
      <servlet-name>dispatcher</servlet-name>
      <url-pattern>*.htm</url-pattern>
      </servlet-mapping>

      versus
      (as per the tutorial)
      <servlet-mapping>
      <servlet-name>dispatcher</servlet-name>
      <url-pattern>/</url-pattern>
      </servlet-mapping>

      Let me know if that solves the problem!

  • 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)

    • 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

  • 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?

    • 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 1:
      <a href="<%= request.getContextPath() %>/viewdemo">Link</a>

      Option 2:
      <%@ taglib uri="http://java.sun.com/jsp/jstl/core&quot; prefix="c" %> (put this at the top of the page)

      <a href="<c:url value="/" />viewdemo">Link</a>

      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)

      <c:set var="cp" value="${pageContext.request.servletContext.contextPath}" scope="session" />

      <a href="{cp}/viewdemo">Link</a>

      That will solve your problem.
      Probably best to user option 3 always.

      Let me know if any further issues.

  • 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.

  • 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.

  • 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

  • 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.

    Thanks