How to develop Spring Framework MVC application in NetBeans?

SHARE & COMMENT :

This is a step-by-step guide on how to develop a Spring Framework MVC application from scratch using NetBeans.Spring is basically a technology committed to enabling you to build applications using Plain Old Java Objects (POJOs). It enables you to develop components as POJOs containing only our business logic, while the framework takes care of the many value adds you need to build enterprise applications — even in areas that you may not have considered when initially authoring the application. This objective requires a complicated framework, which conceals much difficulty from the developer. Because your business logic is abstracted from infrastructure concerns, it’s also likely to enjoy a longer existence, improving the return on investment of writing it. Business logic should change at the pace of your business; only if it is abstracted from infrastructure concerns can the impact on your code base of expected infrastructure change (such as selecting the application server) be reduced.

also read:

1. Create web project in Eclipse

Prerequisite software

  • Java SDK 1.5/1.6
  • NetBeans 5.0 and above
  • Spring Framework 2.0
  • MySQL

For Creating Web application project using NetBeans, please do the follwoing steps

  1. Choose File > New Project (Ctrl-Shift-N) from the main menu. Under Categories select Java Web (If you are using NetBeans 6.0 or 6.1, select Web); under Projects select Web Application. Click Next.
  2. In Project Name, enter SpringDemo. From the Server drop-down list, select the server you plan to work with. Leave all other settings at their defaults and click Next.
  3. Select a Spring framework 2.5 checkbox. When you reach the final panel of the wizard, click Finish.

2. Download Spring Framework 2.5.1

To download the Spring Frame work click on “Download” link. Then select “spring-framework-2.5.1-with-dependencies.zip” link. This download contains all the dependencies required to run the spring framework. Save the downloaded file onto your favorite directory. Now extract the downloaded file (spring-framework-2.5.1-with-dependencies.zip) into your favorite directory.

The dist directory of the spring framework contains the spring modules (modules directory) library files. We are mostly concern with these jar files. We will copy these jar files later into our development environment. These jar files are:

  • spring-aop.jar
  • spring-beans.jar
  • spring-context.jar
  • spring-context-support.jar
  • spring-core.jar
  • spring-jdbc.jar
  • spring-jms.jar
  • spring-orm.jar
  • spring-test.jar
  • spring-tx.jar
  • spring-web.jar
  • spring-webmvc.jar
  • spring-webmvc-portlet.jar
  • spring-webmvc-struts.jar

3. Configure web.xml

Go to the ‘springdemo/WEB-INF’ directory. Modify the minimal ‘web.xml’ file to suit our needs. We define a DispatcherServlet that is going to control where all our request are routed based on information we will enter at a later point. It also has a standard servlet-mapping entry that maps to the url patterns that we will be using. Let any url with an ‘.htm’ extension be routed to the ‘springdemo’ dispatcher.

Code:

<context-param>
		 <param-name>contextConfigLocation</param-name>
		 <param-value>/WEB-INF/springDemo-servlet.xml</param-value>
	 </context-param>

	 <servlet>
		<servlet-name>context</servlet-name>
		<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	 </servlet>

	 <servlet>
		<servlet-name>springDemo</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	 </servlet>

	 <servlet-mapping>
		<servlet-name>springDemo</servlet-name>
		<url-pattern>*.htm<url-pattern>
	 </servlet-mapping>

Next, create a file called ‘springdemo-servlet.xml’ in the springdemo/WEB-INF directory. This is the file where definitions used by the DispatcherServlet should be entered. It is named based on the servlet-name from web.xml with ‘-servlet’ appended. This is a standard naming convention used in the Spring Framework.

4. Copy jars to “WEB-INF/lib”

Then, from the Spring distribution, copy spring.jar (spring-framework-2.5.1/dist/spring.jar) to the new WEB-INF/lib directory. Also copy commons-logging jars to the WEB-INF/lib directory (spring-framework-2.5.1/lib/jakarta-commons/commons-logging.jar). These jars will be deployed to the server and they are also used during the build process.

5. Configuration of database

Download “hibernate 3.0″ jar from http://www.hibernate.org/ and add the jar to the WEB-INF/lib directory. Add “mysql-connector-java-5.0.3-bin” to the WEB-INF/lib directory. (optional step if you are not having Netbeans 6 and above version installed in you system)

6. Create database and tables in MySQL

  • Create database by name “springdemo”.
  • Create a table by name “user” under “springdemo” database.

“user” table consists of the following fields:

  1. USER_ID integer
  2. FIRST_NAME varchar(45)
  3. LAST_NAME varchar(45)
  4. COMPANY varchar(45)
  5. COMMENTS varchar(200)

Since we are using hibernate we have to create a OR mapping file. The mapping file for “user” is created as an xml file by name “User.hbm” under com.simpleweb.user.bean directory under Source Packages directory.

Code:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
 <class name="com.simpleweb.user.bean.User" table="user" lazy="false" >
	 <id name="userId" column="USER_ID" type="java.lang.Integer">
		 <generator/>
	 </id>
	 <property name="firstName" column="FIRST_NAME" type="java.lang.String" />
	 <property name="lastName" column="LAST_NAME" type="java.lang.String" />
	 <property name="company" column="COMPANY" type="java.lang.String" />
	 <property name="comments" column="COMMENTS" type="java.lang.String" />
 </class>
</hibernate-mapping>

Configure database configurations by adding the following code in “springdemo-servlet.xml”

Code:

<!-- DataSource Property -->
<bean id="userDataSource">
	 <property name="driverClassName"><value>com.mysql.jdbc.Driver</value>
	 </property><property name="url"><value>jdbc:mysql:///springdemo</value>
	 </property><property name="username"><value>root</value></property>
	 <property name="password"><value>mysql</value></property>
</bean>

 <!-- Database Property -->
<bean id="userHibernateProperties">
	 <property name="properties">
		 <props>
			 <prop key="hibernate.hbm2ddl.auto">update</prop>
			 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.query.substitutions">true 'T', false 'F'</prop>
			 <prop key="hibernate.show_sql">true</prop>
			 <prop key="hibernate.c3p0.minPoolSize">5</prop>
			 <prop key="hibernate.c3p0.maxPoolSize">20</prop>
			 <prop key="hibernate.c3p0.timeout">600</prop>
			 <prop key="hibernate.c3p0.max_statement">50</prop>
			 <prop key="hibernate.c3p0.testConnectionOnCheckout">false</prop>
		 </props>
	 </property>
</bean>

   <!-- Hibernate SessionFactory -->
<bean id="userSessionFactory">
	 <property name="dataSource"><ref local="userDataSource"/></property>
	 <property name="hibernateProperties"><ref bean="userHibernateProperties" /></property>

	 <!--  OR mapping files. -->
	 <property name="mappingResources">
		 <list>
			 <value>com/simpleweb/user/hibernate/User.hbm.xml</value>
		 </list>
	 </property>
</bean>

7. Modify index.jsp

Open the index.jsp in WEB-INF folder and do the following changes in the code:

Code:

<%@page contentType="text/html"%>
<%@page 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>User Registration</title>
    </head>
    <body>
        <jsp:forward page="addedituser.htm"/>
    </body>
</html>

8. Creating the Controller

Create your Controller and name as AddEditUserController.java and place it in the springdemo/source packages/ directory.

Code:

	package com.simpleweb.user.controller;

import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

public class AddEditUserController implements Controller {

 }

This is as basic a Controller as you can use. We will be expanding this later on, and we will also later on extend some provided abstract base implementations. The Controller handles the request and returns a ModelAndView.

Now, add a bean entry named addEditUserController in springdemo-servlet.xml and make the class AddEditUserController. This defines the controller that our application will be using. We also need to add a URL mapping so the DispatcherServlet knows which controller should be invoked for different URL’s.

Code:

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

 <!--
   - Application context definition for "springdemo" DispatcherServlet.
   -->

 <beans>
     <bean id="addEditUserController"/>

     <bean id="urlMapping">
         <property name="mappings">
             <props>
                 <prop key ="/addedituser.htm">addEditUserController</prop>
             </props>
         </property>
     </bean>
 </beans>

9. Decouple the view and controller

Right now the controller specifies the full path of the view, which creates an unnecessary dependency between the controller and the view. Ideally we would like to map to the view using a logical name, allowing us to switch the view without having to change the controller. You can set this mapping in a properties file if you like using a ResourceBundleViewResolver and a SimpleUrlHandlerMapping class. If your mapping needs are simple it is easier to just set a prefix and a suffix on the InternalResourceViewResolver. The latter approach is the one that we will implement now, so modify the springapp-servlet.xml and include this viewResolver entry. We have elected to use a JstlView which will enable us to use JSTL.

Add the following to your existing “springdemo-servlet.xml”

Code:

<bean id="viewResolver" class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
	 <property name="viewClass"><value>org.springframework.web.servlet.view.JstlView</value></property>
	 <property name ="prefix"><value>/com/simpleweb/user/pages/</value></property>
	 <property name ="suffix"><value>.jsp</value></property>
</bean>

So now I can remove the prefix and suffix from the view name in the controller.

10. Add some classes for business logic

We would like to add a little bit of business logic in form of a User class and a class that will manage all the users. In order to separate the web dependent logic from the business logic I will create separate packages for the Java source com.simpleweb.user.controller, com.simpleweb.user.bean, com.simpleweb.user.services and com.simpleweb.user.dao. The User class is implemented as a JavaBean and it has the default constructor (automatically provided if we don’t specify any constructors) and getters and setters for the instance variables userId, firstName, lastName, company and comments. I also make it Serializable to pass this class between different application layers.

Code:

package com.simpleweb.user.bean;

import java.io.Serializable;

public class User implements Serializable {

	/** Creates a new instance of User */
	public User() {
	}

	private Integer userId;
	private String firstName;
	private String lastName;
	private String company;
	private String comments;

	public String getFirstName() {
	return firstName;
	}

	public void setFirstName(String firstName) {
	 this.firstName = firstName;
	}

	public String getLastName() {
	 return lastName;
	}

	public void setLastName(String lastName) {
	 this.lastName = lastName;
	}

	public String getCompany() {
	 return company;
	}

	public void setCompany(String company) {
	 this.company = company;
	}

	public String getComments() {
	 return comments;
	}

	public void setComments(String comments) {
	 this.comments = comments;
	}

	public Integer getUserId() {
	 return userId;
	}

	public void setUserId(Integer userId) {
	 this.userId = userId;
	}
}

Create a “Transfer Object” as UserTO under com.simpleweb.user.bean package.

Code:

package com.simpleweb.user.bean;

import java.io.Serializable;

public class UserTO extends User implements Serializable {

	/** Creates a new instance of UserTO */
	public UserTO() {
	}
}

Now, I modify the above created Controller “AddEditUserController” class as shown below to hold a reference of this “UserTO” object

Code:

package com.simpleweb.user.controller;

import com.simpleweb.user.bean.UserTO;
import com.simpleweb.user.services.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class AddEditUserController extends SimpleFormController {

	/** Creates a new instance of AddEditUserController */
	public AddEditUserController() {
	}

	protected Object formBackingObject(HttpServletRequest request) throws ServletException {
	 UserTO userTO = new UserTO();
	 return userTO;
	}
}

11. Creating a View

Now it is time to create our view. We will use a JSP page that we decided to name user.jsp. We’ll put it in the WebPages directory under com/simpleweb/user/pages directory.

Code:

<%@page contentType="text/html"%>
 <%@page pageEncoding="UTF-8"%>
 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>

 <!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>User Page</title>
</head>
<body>
<form name="userTO"  method="POST" action="addedituser.htm">
	<table style="width: 500px;"  border="0" align="center">
		<tbody>
			<tr>
				<td colspan="2" style="width: 100px;" align="center"><H3>User Registration</H3></td>
			</tr>
			<tr>
				<td style="width: 100px;" >First Name</td>
				<td >
					<spring:bind path="userTO.firstName">
						<input type="text" name="${status.expression}"  maxlength="50" style="width:128px;" value="<c:out value='${status.value}' escapeXml='true'/>" >
					</spring:bind>
				</td>
			</tr>

			<tr>
				<td style="width: 100px;" >Last Name</td>
				<td >
					<spring:bind path="userTO.lastName">
						<input type="text" name="${status.expression}"  maxlength="50" style="width:128px;" value="<c:out value='${status.value}' escapeXml='true'/>" >
					</spring:bind>
				</td>
			</tr>

			<tr>
				<td style="width: 100px;" >Company</td>
				<td >
					<spring:bind path="userTO.company">
						<input type="text" name="${status.expression}"  maxlength="50" style="width:128px;" value="<c:out value='${status.value}' escapeXml='true'/>" >
					</spring:bind>
				</td>
			</tr>

			<tr>
				<td style="width: 100px;" >Comments</td>
				<td >
					<spring:bind path="userTO.comments">
						<textarea name="${status.expression}" id="comments" style="width:400px;" rows="5"><c:out value='${status.value}' escapeXml='true'/></textarea>
					</spring:bind>
				</td>
			</tr>

			<tr>
				<td colspan="2" align="center">
					<input type="submit" name="submit" value="Submit">
					<input type="reset" name="reset" value="Reset">
				</td>
			</tr>
		</tbody>
	</table>
</form>
</body>
 </html>

This form uses a tag library named “spring” that is provided with the Spring Framework. We have to copy this file from the Spring distribution spring-framework-2.5.1/dist/spring.tld to the springdemo/WEB-INF directory. Now we must also add a <taglib> entry to web.xml.

Code:

<taglib>
	<taglib-uri>/spring</taglib-uri>
	<taglib-location>/WEB-INF/spring.tld</taglib-location>
</taglib>

We also have to declare this taglib in a page directive in the jsp file. We declare a form the normal way with a <form> tag and an <input> text field and a submit button.

When the user enters record information it has to be handled by the controller and the business logic will be handles by the service object and data by dao layer.

Create “UserServiceImpl.java” under com.simpleweb.user.services package.

Code:

package com.simpleweb.user.services;

public class UserServiceImpl {

	/** Creates a new instance of UserServiceImpl */
	public UserServiceImpl() {
	}

}

Create “UserDAOImpl.java” under com.simpleweb.user.dao package.

Code:

package com.simpleweb.user.dao;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class UserDAOImpl extends HibernateDaoSupport {

	/** Creates a new instance of UserDAOImpl */
	public UserDAOImpl() {
	}
}

Add the following code as shown below to “AddEditUserController.java”:

Code:

public ModelAndView onSubmit(Object command) throws Exception{
	try {
		UserTO userTO = (UserTO) command;
		userService.register(userTO);
		return new ModelAndView(getSuccessView(),"userTO",userTO);
	} catch (Exception e) {
		return new ModelAndView(getSuccessView(),"error",e.toString());
	}
 }

 private UserServiceImpl userService;

 public UserServiceImpl getUserService() {
	 return userService;
 }

 public void setUserService(UserServiceImpl userService) {
	 this.userService = userService;
 }

“OnSubmit()” handles the fom submission by retrieving the details from the form and sent to service layer and inturn to data layer for persistence.

Configure “UserDAOImpl.java” and “UserServiceImpl.java” in “springdemo-servlet.xml” as shown below:

Code:

<bean id="userDAO">
	<property name="sessionFactory" ref="userSessionFactory" />
</bean>

<bean id="userService">
	<property name="userDAO" ref="userDAO" />
</bean>

Add the following code as shown below to “UserServiceImpl.java”:

Code:

private UserDAOImpl userDAO;

public void register(UserTO userTO) {

	try {
		User user = new User();
		BeanUtils.copyProperties(userTO, user);
		userDAO.register(user);

	} catch (Exception exp) {
		hrow new RuntimeException(exp.toString());
	}
}

public UserDAOImpl getUserDAO() {
	return userDAO;
}

public void setUserDAO(UserDAOImpl userDAO) {
	this.userDAO = userDAO;
}

Add the following code as shown below to “UserDAOImpl.java”:

Code:

public void register(User user) {
	try {
		getHibernateTemplate().save(user);
	} catch (Exception e) {
		throw new RuntimeException(e.toString());
	}
}

12. Deploying and Running the Project

Whether you are using the GlassFish application server or Tomcat, the process for deploying your project is the same. If you installed GlassFish or Tomcat through the IDE download, your server is already registered in the IDE. If you need to make any changes to server settings, or would like to register a different server with the IDE, choose Tools > Servers from the main menu to open the Server Manager.

To deploy the SpringDemo project to the server:

  • From the Projects window, right-click the project node and choose Deploy (If you are using NetBeans 6.0 or 6.1, choose Undeploy and Deploy). The IDE compiles the project, starts the server, then deploys the project to it. You can see any output generated in the Output window. The output should complete with a BUILD SUCCESSFUL message.To check that the application has indeed been deployed to the server, open the Services window (Ctrl-5) and expand the Servers node. All servers that are registered in the IDE are listed here. For GlassFish, expand Applications > Web Applications to view the application. For Tomcat, expand Web Applications to view the SpringDemo application.

To run the application:

  • In the Projects window, right-click the SpringDemo project node and choose Run. The index.jsp page opens in the IDE’s default browser.

also read:

13. Summary

This article concludes, creating a Simple Spring Framework Web application in NetBeans IDE with the database hit using Hibernate.

Note: Netbeans 6 and above has a plugin for various frameworks including Spring framework. With the plug-in, we can avoid boiler plate configuration to get it started.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Trackbacks

  1. […] support in Spring FrameworkAccessing objects in JNDI using SpringDeveloping a Spring Framework MVC application step-by-step using NetBeansHow to send EMail using Spring Framework?Transaction Management in Spring […]

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better