https://confluence.jetbrains.com/display/IntelliJIDEA/Getting+Started+with+Spring+MVC,+Hibernate+and+JSON

In this tutorial we will create a simple web application using Spring MVCHibernate 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 SpringMaven and Tomcat plugins are enabled in IntelliJ IDEA Ultimate before you perform this tutorial.

1. Create a project

Open Project Wizard and select Spring MVC in Spring section. If you have already configured the application server, you can select it in theApplication Server field. With IntelliJ IDEA you can deploy applications to TomcatTomEEGlassfishJBossWebSphereJetty,GeronimoResinCloud Foundry and CloudBees.

Change Project name, Project location and Base package if necessary. The IDE will create a "Hello world" project with a simple controller and view.

The new project comes with Maven's pom.xml file. You can manage project dependencies through this file or through the dedicated Maventool window.

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

Besides dependencies, IntelliJ IDEA also imports the artifacts definition from pom.xml. You can check the artifacts settings in the
Project Structure → Artifacts dialog.

The artifacts define the structure of what will be deployed to the application server when you click Run → Run 'Tomcat 7.0'.

2. Create run configuration

If you haven't specified Application server in Project Wizard you can do it now via Run → Edit Configurations....

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

If you have configured at least one run configuration for an application server, IntelliJ IDEA shows the Application Servers 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 Application Servers tool window.

4. Add dependencies

Since we are going to create a database for our application, we need Spring DataHibernate 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 pom.xml file. The IDE will automatically download the corresponding libraries and add to the artifact.

<dependency>
   <groupId>jstl</groupId>
   <artifactId>jstl</artifactId>
   <version>1.2</version>
</dependency>
 
<dependency>
<groupId>org.springframework.data</groupId>
   <artifactId>spring-data-jpa</artifactId>
   <version>1.2.0.RELEASE</version>
</dependency>
 
<dependency>
   <groupId>org.hibernate.javax.persistence</groupId>
   <artifactId>hibernate-jpa-2.0-api</artifactId>
   <version>1.0.0.Final</version>
</dependency>
 
<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>3.6.10.Final</version>
</dependency>
 
<dependency>
   <groupId>org.hsqldb</groupId>
   <artifactId>hsqldb</artifactId>
   <version>2.2.9</version>
</dependency>
 
<dependency>
   <groupId>org.json</groupId>
   <artifactId>json</artifactId>
   <version>20080701</version>
</dependency>

5. Create persistence.xml

Now let's define resources/META-INF/persistence.xml file to initialize Hibernate's entity manager over JPA.

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="defaultPersistenceUnit" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <properties>
            <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="hibernate.hbm2ddl.auto" value="create-drop" />
        </properties>
    </persistence-unit>
</persistence>

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 {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
 
    @Basic
    private String firstName;
 
    @Basic
    private String lastName;
 
    @Basic
    private String email;
 
    public Long getId() {
        return id;
    }
 
    public void setId(Long id) {
        this.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) {
        this.email = email;
    }
}

Define a Spring repository for the user entity.

package com.springapp.mvc;
 
import org.springframework.data.jpa.repository.JpaRepository;
 
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 webapp/WEB-INF/mvc-dispatcher-servlet.xmlfile.

<jpa:repositories base-package="com.springapp.mvc"/>
 
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="defaultPersistenceUnit"/>
</bean>
 
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
 
<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 HelloController to UserController 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;
 
@Controller
public class UserController {
    @Autowired
    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) {
 
        userRepository.save(user);
 
        return "redirect:/";
    }
 
    @RequestMapping("/delete/{userId}")
    public String deleteUser(@PathVariable("userId") Long userId) {
 
        userRepository.delete(userRepository.findOne(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 hello view (and corresponding hello.jsp file) to users (and users.jsp , respectively). If you rename the view name from usage,IntelliJ IDEA applies the corresponding changes to JSP files automatically.

<!doctype html>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 
<html>
<head>
    <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">
 
</head>
 
<body>
 
<div class="container">
    <div class="row">
        <div class="span8 offset2">
            <h1>Users</h1>
            <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>
            </div>
            <div class="control-group">
                <form:label cssClass="control-label" path="lastName">Last Name:</form:label>
                <div class="controls">
                    <form:input path="lastName"/>
                </div>
            </div>
            <div class="control-group">
                <form:label cssClass="control-label" path="email">Email:</form:label>
                <div class="controls">
                    <form:input path="email"/>
                </div>
            </div>
            <div class="control-group">
                <div class="controls">
                    <input type="submit" value="Add User" class="btn"/>
                    </form:form>
                </div>
            </div>
 
            <c:if test="${!empty users}">
                <h3>Users</h3>
                <table class="table table-bordered table-striped">
                    <thead>
                    <tr>
                        <th>Name</th>
                        <th>Email</th>
                        <th>&nbsp;</th>
                    </tr>
                    </thead>
                    <tbody>
                    <c:forEach items="${users}" var="user">
                        <tr>
                            <td>${user.lastName}, ${user.firstName}</td>
                            <td>${user.email}</td>
                            <td>
                                <form action="delete/${user.id}" method="post"><input type="submit" class="btn btn-danger btn-mini" value="Delete"/></form>
                            </td>
                        </tr>
                    </c:forEach>
                    </tbody>
                </table>
            </c:if>
        </div>
    </div>
</div>
 
</body>
</html>

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 Run → Debug 'Tomcat 7.0'....

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)
public
@ResponseBody
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());
        userArray.put(userJSON);
    }
    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.

IntelliJIDEA Getting+Started+with+Spring+MVC,+Hibernate+and+JSON的更多相关文章

  1. IntelliJ IDEA:Getting Started with Spring MVC, Hibernate and JSON实践

    原文:IntelliJ IDEA:Getting Started with Spring MVC, Hibernate and JSON实践 最近把编辑器换成IntelliJ IDEA,主要是Ecli ...

  2. Spring + Spring MVC + Hibernate

    Spring + Spring MVC + Hibernate项目开发集成(注解) Posted on 2015-05-09 11:58 沐浴未来的我和你 阅读(307) 评论(0) 编辑 收藏 在自 ...

  3. Spring + Spring MVC + Hibernate项目开发集成(注解)

    在自己从事的项目中都是使用xml配置的方式来进行的,随着项目的越来越大,会发现配置文件会相当的庞大,这个不利于项目的进行和后期的维护.于是考虑使用注解的方式来进行项目的开发,前些日子就抽空学习了一下. ...

  4. Java 本地开发环境搭建(框架采用 Spring+Spring MVC+Hibernate+Jsp+Gradle+tomcat+mysql5.6)

    项目搭建采用技术栈为:Spring+Spring MVC+Hibernate+Jsp+Gradle+tomcat+mysql5.6 搭建环境文档目录结构说明: 使用Intellj Idea 搭建项目过 ...

  5. spring mvc: Hibernate验证器(字段不能为空,在1-150自己)

    spring mvc: Hibernate验证器(字段不能为空,在1-150自己) 准备: 下载Hibernate Validator库 - Hibernate Validator.解压缩hibern ...

  6. Spring MVC第一课:用IDEA构建一个基于Spring MVC, Hibernate, My SQL的Maven项目

    作为一个Spring MVC新手最基本的功夫就是学会如何使用开发工具创建一个完整的Spring MVC项目,本文站在一个新手的角度讲述如何一步一步创建一个基于Spring MVC, Hibernate ...

  7. Spring MVC Hibernate MySQL Integration(集成) CRUD Example Tutorial【摘】

    Spring MVC Hibernate MySQL Integration(集成) CRUD Example Tutorial We learned how to integrate Spring ...

  8. Spring mvc+hibernate+freemarker(实战)

    Spring mvc+hibernate+freemarker(实战) 博客分类: Spring Spring mvchibernatefreemarkerwebjava  今天我为大家做了一个 sp ...

  9. Spring+Spring MVC+Hibernate增查(使用注解)

    使用Spring+Spring MVC+Hibernate做增删改查开发效率真的很高.使用Hibernate简化了JDBC连接数据库的的重复性代码.下面根据自己做的一个简单的增加和查询,把一些难点分析 ...

随机推荐

  1. Spark 1.0.0版本发布

    前言 如今Spark终于迈出了里程碑一步,1.0.0标记的版本号出版物Spark1.0时代.1.0.0版本号不仅增加了非常多新特性.而且提供了更好的API支持.Spark SQL作为一个新的组件增加. ...

  2. poj2112 Optimal Milking --- 最大流量,二分法

    nx一个挤奶器,ny奶牛,每个挤奶罐为最m奶牛使用. 现在给nx+ny在矩阵之间的距离.要求使所有奶牛挤奶到挤奶正在旅程,最小的个体奶牛步行距离的最大值. 始感觉这个类似二分图匹配,不同之处在于挤奶器 ...

  3. SQLSERVER PRINT语句的换行

    原文:SQLSERVER PRINT语句的换行 SQLSERVER  PRINT语句的换行 想在输出的PRINT语句里面换行,可以这样做 /* SQL的换行 制表符 CHAR(9) 换行符 CHAR( ...

  4. php方法综述除去换行符(PHP_EOL使用变量)

    一个小包裹,事实上,不同的平台具有不同的实现.为什么要这样.它可以是一个世界是多样的. 最初unix与世界把它包/n取代,但windows为了体现自己的不同.要使用/r/n,更有意思的是,mac随着/ ...

  5. Android获取本机IP地址

    一.概述 习惯了Linux下的网络编程,在还没用智能机之前就一直想知道怎么得到手机的IP地址(玩智能机之前我是不搞手机应用的).好了,得知Android是基于Linux内核的,那么不就可以利用之前学的 ...

  6. Objective-C语法简记学习

    開始学习iPhone开发了,尽管如今已经有了Swift,但我还是老老实实地学习Objective-C,鄙人入门的程序语言是C,后来学习了C#和Java,如今来学Objective-C,这篇仅仅是一些非 ...

  7. jquery ui tab跳转

    1.tabs_iframe.jsp <%-- Document : tabs Created on : 2015-2-28, 14:44:02 Author : liyulin lyl01099 ...

  8. lsblk请参阅块设备

    lsblk可以查看分区和挂载的磁盘使用情况 lsblk全部的參数 -a, --all            显示全部设备  -b, --bytes          以bytes方式显示设备大小  - ...

  9. UVa 10012 - How Big Is It? 堆球问题 全排列+坐标模拟 数据

    题意:给出几个圆的半径,贴着底下排放在一个长方形里面,求出如何摆放能使长方形底下长度最短. 由于球的个数不会超过8, 所以用全排列一个一个计算底下的长度,然后记录最短就行了. 全排列用next_per ...

  10. android控件 下拉刷新pulltorefresh

    外国人写的下拉刷新控件,我把他下载下来放在网盘,有时候訪问不了github 支持各种控件下拉刷新 ListView.ViewPager.WevView.ExpandableListView.GridV ...