码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-12-18 22:05:21      阅读:471      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   ar   io   color   os   使用   sp   

最近把编辑器换成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截图

bubuko.com,布布扣

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中运行起你的项目。就可以在浏览器中看到效果了.

bubuko.com,布布扣

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

 

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

标签:style   blog   http   ar   io   color   os   使用   sp   

原文地址:http://www.cnblogs.com/dreamfree/p/4172674.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!