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

最近把编辑器换成IntelliJ IDEA,主要是Eclipse中处理Maven项目很不方便,很早就听说IntelliJ IDEA的大名了,但是一直没机会试试。最近终于下载安装了,由于是新手,决定尝试个Tutorials,最终找了个熟悉点的项目,就是Getting Started with Spring MVC, Hibernate and JSON(http://confluence.jetbrains.com/display/IntelliJIDEA/Getting+Started+with+Spring+MVC%2C+Hibernate+and+JSON)。废话不多说了, 下面是我的实践过程:

在实践之前,有个问题首先要明确下,在IntelliJ IDEA中project相当于Eclipse中的workspace,module相当于Eclipse中的project。

1.创建Project。具体的过程我就不详述了,可以在官方的Tutorials中查看。下面是我的project structure截图

2.配置Tomcat,这步很简单,没什么可说的。配置完成后,将步骤1中建立的项目deployed到Tomcat上运行,等Tomcat启动完成后,就会启动你默认的浏览器,如果上面的步骤没什么错误的话,你就可以在你的浏览器中看到Hello World!了。

3.添加依赖。因为要使用数据库,Hibernate,JPA等。所以需要在pom文件中添加对应的依赖。等你添加完成后,IntelliJ IDEA会自动引入或下载所需的包。

4.接下来是创建持久化的配置文件。这个地方需要注意路径的问题。具体的路径可以查看project structure截图。这个配置文件中都是数据库的配置信息。数据库使用的是hsqldb,如果不想使用,可以改成自己想用的数据库,但是要注意修改相应的jar包。

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

5.配置Model类,使用的技术为JPA。

package com.springapp.mvc;

import javax.persistence.*;

/**
 * Created by yul on 2014/12/18.
 */
@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 String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setId(Long id) {
        this.id = id;
    }

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

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

    public void setEmail(String email) {
        this.email = email;
    }
}

定义service,这里官方的示例代码中没有@Repository注解,需要添加上

package com.springapp.mvc;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

/**
 * Created by yul on 2014/12/18.
 */
@Repository
public interface UserRepository extends JpaRepository<User, Long> {

}

6.注册bean。包括repository, entity manager factory and transaction manager

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="com.springapp.mvc"/>

    <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"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

7.定义Controller。

package com.springapp.mvc;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.*;

/**
 * Created by yul on 2014/12/18.
 */
@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(value = "/delete/{userId}")
    public String deleteUser(@PathVariable("userId") Long userId) {
        userRepository.delete(userRepository.findOne(userId));
        return "redirect:/";
    }

    @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();
    }

}

我把后面返回JSON数据的方法也加上了。

8.定义view。官方提供的Bootstrap的CDN不好用,估计是GFW的问题,可以换成国内的。如果对于Bootstrap有兴趣,可以去这个网址http://www.bootcss.com/看看

<!doctype html>
<%@taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<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">

    <!-- 新 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css">
    <%--<link href="http://twitter.github.io/bootstrap/assets/css/bootstrap.css" rel="stylesheet">--%>
    <%--<link href="http://twitter.github.io/bootstrap/assets/css/bootstrap-responsive.css" rel="stylesheet">--%>
</head>
<body>

<div class="container">
    <div class="row">
        <div class="span8 offset2">
            <h1>User</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" />
                    </div>
                </div>
            </form:form>

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

到了这里,基本任务就算完成了。

下面就是测试了。在Tomcat中运行起你的项目。就可以在浏览器中看到效果了.

如果想查看返回的JSON数据。在浏览器中输入http://localhost:8080/api/users 即可。

时间: 2024-08-08 01:18:20

IntelliJ IDEA:Getting Started with Spring MVC, Hibernate and JSON实践的相关文章

IntelliJIDEA Getting+Started+with+Spring+MVC,+Hibernate+and+JSON

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 MVC, Hibernate and JSON. We will use Maven to manage dependencies and Inte

Spring MVC + Hibernate + Maven: Crud操作示例

Alexey是一个在使用Java,TestNG 和Selenium的自动化WEB应用程序中有丰富经验的测试开发者.他如此的喜欢QA以至于在下班后他为初级QA工程师提供培训课程. 在这篇文章中我想介绍一个Spring MVC + Hibernate + Maven例子.这组技术主要涉及一些基础知识,我想在每一个必要的地方详细解释它.本篇话题范围以外的更多资源,我会提供链接方便你阅读.在文章的最后,我将发布一个GitHub的链接. 目标 示例web应用程序是基于Spring MVC, Hiberna

spring mvc+hibernate的基本配置

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p&

使用Intellij IDEA从零使用Spring MVC

原文:使用Intellij IDEA从零使用Spring MVC 使用Intellij IDEA从零使用Spring MVC 黑了Java这么多年, 今天为Java写一篇文章吧. 这篇文章主要是想帮助那些刚接触到Java, 同时想从事Java WEB GUI开发的人. 对我而言, 我很早就有想尝试用Java写WEB的想法, 可是没有一次成功过, 不管是用struts, 还是纯JSP, 总是配置不好, tomcat不能正确的运行我的程序. 自打那以后, 我一直在抱怨Java的application

Spring+Spring MVC+Hibernate环境搭配

Spring+Spring MVC+Hibernate简称"SSH".Spring容器是Spring的核心,该 容器负责管理spring中的java组件.Spring的核心机制:依赖注入.Hibernate是一个不错的ORM(关系对象映射)框架.Spring+Spring MVC+Hibernate环境搭配步骤: 1.搭建Spring+Hibernate环境(跟ssh搭建步骤一致) (1)加入Spring+Hibernate的架包. 2.搭建SpringMVC环境( 1)添加Sprin

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

在自己从事的项目中都是使用xml配置的方式来进行的,随着项目的越来越大,会发现配置文件会相当的庞大,这个不利于项目的进行和后期的维护.于是考虑使用注解的方式来进行项目的开发,前些日子就抽空学习了一下.在网上也查询了很多使用注解来搭建开发框架的文章,但是有一个问题就是,使用更新的软件版本会出错.这里我将使用最新的Spring,Hibernate来进行框架的搭建,经过测试,顺利运行.分享旨在与大家一起分享学习,共同进步,有不足之处,望不吝赐教,谢谢! 本项目使用maven构建,采用Spring +

搭建基于全注解的Spring+Spring MVC+Hibernate框架

以实例讲解Spring+Spring MVC+Hibernate框架搭建步骤: 一.配置web.xml Xml代码   <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XML

Spring + Spring MVC + Hibernate

Spring + Spring MVC + Hibernate项目开发集成(注解) Posted on 2015-05-09 11:58 沐浴未来的我和你 阅读(307) 评论(0) 编辑 收藏 在自己从事的项目中都是使用xml配置的方式来进行的,随着项目的越来越大,会发现配置文件会相当的庞大,这个不利于项目的进行和后期的维护.于是考虑使用注解的方式来进行项目的开发,前些日子就抽空学习了一下.在网上也查询了很多使用注解来搭建开发框架的文章,但是有一个问题就是,使用更新的软件版本会出错.这里我将使

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

使用Spring+Spring MVC+Hibernate做增删改查开发效率真的很高.使用Hibernate简化了JDBC连接数据库的的重复性代码.下面根据自己做的一个简单的增加和查询,把一些难点分析出来: 首先项目目录结构:(Hibernate持久化数据连接信息交给Spring进行管理:别忘了加入Hibernate和Spring相关的架包.jar) 第一步:弄个用户实体类(配置Users.hbm.xml映射文件): 1 package com.ssh.SpringMVC.enity; 2 3