IntelliJ IDEA:Getting Started with Spring MVC, Hibernate and JSON实践
原文: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> </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 即可。
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 ...
- Intellij IDEA采用Maven+Spring MVC+Hibernate的架构搭建一个java web项目
原文:Java web 项目搭建 Java web 项目搭建 简介 在上一节java web环境搭建中,我们配置了开发java web项目最基本的环境,现在我们将采用Spring MVC+Spring ...
- IntelliJ IDEA上创建maven Spring MVC项目
IntelliJ IDEA上创建Maven Spring MVC项目 各软件版本 利用maven骨架建立一个webapp 建立相应的目录 配置Maven和SpringMVC 配置Maven的pom.x ...
- 使用Intellij IDEA从零使用Spring MVC
原文:使用Intellij IDEA从零使用Spring MVC 使用Intellij IDEA从零使用Spring MVC 黑了Java这么多年, 今天为Java写一篇文章吧. 这篇文章主要是想帮助 ...
- Spring + Spring MVC + Hibernate
Spring + Spring MVC + Hibernate项目开发集成(注解) Posted on 2015-05-09 11:58 沐浴未来的我和你 阅读(307) 评论(0) 编辑 收藏 在自 ...
- Spring + Spring MVC + Hibernate项目开发集成(注解)
在自己从事的项目中都是使用xml配置的方式来进行的,随着项目的越来越大,会发现配置文件会相当的庞大,这个不利于项目的进行和后期的维护.于是考虑使用注解的方式来进行项目的开发,前些日子就抽空学习了一下. ...
- Java 本地开发环境搭建(框架采用 Spring+Spring MVC+Hibernate+Jsp+Gradle+tomcat+mysql5.6)
项目搭建采用技术栈为:Spring+Spring MVC+Hibernate+Jsp+Gradle+tomcat+mysql5.6 搭建环境文档目录结构说明: 使用Intellj Idea 搭建项目过 ...
- spring mvc: Hibernate验证器(字段不能为空,在1-150自己)
spring mvc: Hibernate验证器(字段不能为空,在1-150自己) 准备: 下载Hibernate Validator库 - Hibernate Validator.解压缩hibern ...
- Spring MVC第一课:用IDEA构建一个基于Spring MVC, Hibernate, My SQL的Maven项目
作为一个Spring MVC新手最基本的功夫就是学会如何使用开发工具创建一个完整的Spring MVC项目,本文站在一个新手的角度讲述如何一步一步创建一个基于Spring MVC, Hibernate ...
随机推荐
- 在使用SQLite插入数据时出现乱码的解决办法
在VC++中通过sqlite3.dll接口对sqlite数据库进行操作,包括打开数据库,插入,查询数据库等,如果操作接口输入参数包含中文字符,会导致操作异常.例如调用sqlite3_open打开数 ...
- Java Day 12
包 编译格式 javac -d . **.java 包之间的访问 类找不到: 类名写错,包名.类名 包不存在:指定classpath 其他包的类无法访问:权限 public protected 包导入 ...
- copy-mutableCopy
copy和mutableCopy语法的目的:改变副本的时候,不会影响到源对象:调用Copy产生的对象是不可变的,调用mutableCopy产生的对象是可变的,与调用对象是否可变无关. Copy 需要先 ...
- Leetcode-Construct Binary Tree from inorder and preorder travesal
Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that ...
- VMWare EXSi 添加新磁盘时 报错 HostStorageSystem.ComputeDiskPartitionInfo 的处理
给 VMWare EXSi 添加新磁盘时报错 : Call "HostStorageSystem.ComputeDiskPartitionInfo" for object &quo ...
- cygwin and its host machine
Senario 本来我是想要修改下 machine name 在Ubuntu中的步骤是这样的 1 sudo hostname newMechineName 2 sudo vi /etc/hostnam ...
- 计算器软件的代码实现 (策略模式+asp.net)
一 策略模式代码的编写 using System; using System.Collections.Generic; using System.Linq; using System.Web; /// ...
- 2013ACM/ICPC亚洲区南京站现场赛——题目重现
GPA http://acm.hdu.edu.cn/showproblem.php?pid=4802 签到题,输入两个表,注意细心点就行了. #include<cstdio> #inclu ...
- 【转】Sublime text 3 中文文件名显示方框怎么解决
引用自:http://www.zhihu.com/question/24029280 如图,中文文件名打开全是乱码,内容倒是装了converttoutf8没什么太大的问题. 这个是sublime te ...
- Map:比较新增加日期的和需要删除的日期 使用方法
1.场景描述:根据在日历选择的日期,数据库来保持我们选择日期. 2.方法,硬删除的方法,每次全部删除,然后再重新添加选择的新的日期.这样导致如果需要保存create_time的情况,那么每次操作的都是 ...