In this tutorial we will create a simple web application using Spring MVC, Hibernate and JSON. We will use Maven to manage dependencies and IntelliJ IDEA to create, run and debug an application on local Tomcat application server.


Make sure that Spring, Maven and Tomcat plugins are enabled in IntelliJ IDEA Ultimate before you perform this tutorial.

1. Create a project


{span:class=shortcut}Project Wizard{span}
and select
{span:class=id}Spring MVC{span}
{span:class=id}Spring section{span}
. If you have already configured the application server, you can select it in the
{span:class=id}Application Server{span}
field. With IntelliJ IDEA you can deploy applications to Tomcat, TomEE, Glassfish, JBoss, WebSphere, Jetty, Geronimo, Resin, Cloud Foundry and CloudBees.


{span:class=id}Project name{span}
{span:class=id}Project location{span}
{span:class=id}Base package{span}
if necessary. The IDE will create a
{span:class=id}"Hello world"{span}
project with a simple controller and view.

The new project comes with Maven's

file. You can manage project dependencies through this file or through the dedicated
tool window.

When you change Maven's dependencies, IntelliJ IDEA applies the corresponding changes to the project automatically. You can check it in the

{span:class=shortcut}Project Structure → Modules{span}

Besides dependencies, IntelliJ IDEA also imports the artifacts definition from

. You can check the artifacts settings in the
{span:class=shortcut}Project Structure → Artifacts{span}

The artifacts define the structure of what will be deployed to the application server when you click

{span:class=shortcut}Run → Run 'Tomcat 7.0'{span}

2. Create run configuration

If you haven't specified

{span:class=id}Application server{span}
{span:class=shortcut}Project Wizard{span}
you can do it now via
{span:class=shortcut}Run → Edit Configurations...{span}

Don't forget to specify the artifacts to deploy for this run configuration via the


If you have configured at least one run configuration for an application server, IntelliJ IDEA shows the

{span:class=shortcut}Application Servers{span}
tool window to manage the application state on the application server. You can see the list of application servers, start or stop servers, see deployed applications, manage artifacts to deploy, and manage the application state.

3. Run the application

After the artifacts and run configurations are defined, you can deploy the application by simply running your configuration or via a shortcut right from the

{span:class=shortcut}Application Servers{span}
tool window.

4. Add dependencies

Since we are going to create a database for our application, we need Spring Data, Hibernate and HSQLDB libraries. In order to implement JSON API for our application we need JSON library. Finally, we will need JSTL library to use in application's view.

We have to define all these dependencies in our

file. The IDE will automatically download the corresponding libraries and add to the artifact.







5. Create persistence.xml

Now let's define

file to initialize Hibernate's entity manager over JPA.

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="" xmlns:xsi="" xsi:schemaLocation="">
    <persistence-unit name="defaultPersistenceUnit" transaction-type="RESOURCE_LOCAL">
            <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
            <property name="hibernate.connection.url" value="jdbc:hsqldb:mem:spring" />
            <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver" />
            <property name="hibernate.connection.username" value="sa" />
            <property name="hibernate.connection.password" value="" />
            <property name="" value="create-drop" />

6. Define model classes

Define a model class for user entity using JPA annotations.

package com.springapp.mvc;

import javax.persistence.*;

@Entity(name = "account")
public class User {
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String firstName;

    private String lastName;

    private String email;

    public Long getId() {
        return id;

    public void setId(Long id) { = id;

    public String getFirstName() {
        return firstName;

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

    public String getLastName() {
        return lastName;

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

    public String getEmail() {
        return email;

    public void setEmail(String email) { = email;

Define a Spring repository for the user entity.

package com.springapp.mvc;


public interface UserRepository extends JpaRepository<User, Long> {

7. Register repository, entity manager factory and transaction manager

Now we have to register the user repository, an entity manager factory and a transaction manager in


<jpa:repositories base-package="com.springapp.mvc"/>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="defaultPersistenceUnit"/>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />

<tx:annotation-driven transaction-manager="transactionManager"/>

The model for our application is ready, so we can implement the controller.

8. Define controller

Let's rename

and add the following code:

package com.springapp.mvc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

public class UserController {
    private UserRepository userRepository;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String listUsers(ModelMap model) {
        model.addAttribute("user", new User());
        model.addAttribute("users", userRepository.findAll());
        return "users";

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addUser(@ModelAttribute("user") User user, BindingResult result) {;

        return "redirect:/";

    public String deleteUser(@PathVariable("userId") Long userId) {


        return "redirect:/";

As you can see, we have defined three methods for listing, adding and deleting user entities. The methods are mapped to the corresponding URLs.

9. Define view

Let's rename

view (and corresponding
file) to
, respectively). If you rename the view name from usage, IntelliJ IDEA applies the corresponding changes to JSP files automatically.

<!doctype html>
<%@taglib uri="" prefix="spring" %>
<%@taglib uri="" prefix="form" %>
<%@taglib uri="" prefix="c" %>

    <meta charset="utf-8">
    <title>Spring MVC Application</title>

    <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="" rel="stylesheet">
    <link href="" rel="stylesheet">


<div class="container">
    <div class="row">
        <div class="span8 offset2">
            <form:form method="post" action="add" commandName="user" class="form-horizontal">
            <div class="control-group">
                <form:label cssClass="control-label" path="firstName">First Name:</form:label>
                <div class="controls">
                    <form:input path="firstName"/>
            <div class="control-group">
                <form:label cssClass="control-label" path="lastName">Last Name:</form:label>
                <div class="controls">
                    <form:input path="lastName"/>
            <div class="control-group">
                <form:label cssClass="control-label" path="email">Email:</form:label>
                <div class="controls">
                    <form:input path="email"/>
            <div class="control-group">
                <div class="controls">
                    <input type="submit" value="Add User" class="btn"/>

            <c:if test="${!empty users}">
                <table class="table table-bordered table-striped">
                    <c:forEach items="${users}" var="user">
                            <td>${user.lastName}, ${user.firstName}</td>
                                <form action="delete/${}" method="post"><input type="submit" class="btn btn-danger btn-mini" value="Delete"/></form>


10. Run the application

The application should be ready now.

11. Debug application

If you need to debug your application, just add a breakpoint and re-run the application in debug mode via

{span:class=shortcut}Run → Debug 'Tomcat 7.0'...{span}

12. Add JSON API

Finally, let's output the created users via JSON by implementing this simple Controller's method:

@RequestMapping(value = "/api/users", method = RequestMethod.GET)
String listUsersJson(ModelMap model) throws JSONException {
    JSONArray userArray = new JSONArray();
    for (User user : userRepository.findAll()) {
        JSONObject userJSON = new JSONObject();
        userJSON.put("id", user.getId());
        userJSON.put("firstName", user.getFirstName());
        userJSON.put("lastName", user.getLastName());
        userJSON.put("email", user.getEmail());
    return userArray.toString();

Run the application and open http://localhost:8080/api/users.

Download the final code and IntelliJ IDEA's project files from GitHub.