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)。廢話很少說了, 下面是個人實踐過程:
css

在實踐以前,有個問題首先要明確下,在IntelliJ IDEA中project至關於Eclipse中的workspace,module至關於Eclipse中的project。html

1.建立Project。具體的過程我就不詳述了,能夠在官方的Tutorials中查看。下面是個人project structure截圖java

2.配置Tomcat,這步很簡單,沒什麼可說的。配置完成後,將步驟1中創建的項目deployed到Tomcat上運行,等Tomcat啓動完成後,就會啓動你默認的瀏覽器,若是上面的步驟沒什麼錯誤的話,你就能夠在你的瀏覽器中看到Hello World!了。git

 

3.添加依賴。由於要使用數據庫,Hibernate,JPA等。因此須要在pom文件中添加對應的依賴。等你添加完成後,IntelliJ IDEA會自動引入或下載所需的包。github

4.接下來是建立持久化的配置文件。這個地方須要注意路徑的問題。具體的路徑能夠查看project structure截圖。這個配置文件中都是數據庫的配置信息。數據庫使用的是hsqldb,若是不想使用,能夠改爲本身想用的數據庫,可是要注意修改相應的jar包。web

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

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註解,須要添加上sql

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 managerchrome

<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 便可。

相關文章
相關標籤/搜索