IntelliJ IDEA: Getting Started with Spring MVC, Hibernate and JSON practices, intellijjson
Recently, I changed the editor to IntelliJ IDEA. It is inconvenient to process Maven projects in Eclipse. I have heard of IntelliJ IDEA for a long time, but I have never had a chance to try it. Recently downloaded and installed, because it is a newbie, decided to try a Tutorials, eventually found a familiar point of the project, is Getting Started with Spring MVC, Hibernate and JSON (http://confluence.jetbrains.com/display/IntelliJIDEA/Getting+Started+with+Spring+MVC%2C+Hibernate+and+JSON ). The following is my practice process:
Before practice, make it clear that in IntelliJ IDEA, a project is equivalent to a workspace in Eclipse, and a module is equivalent to a project in Eclipse.
1. Create a Project. I will not elaborate on the specific process. You can view it in the official Tutorials. Below is my project structure
2. Configure Tomcat. This step is very simple and there is nothing to say. After the configuration is complete, run the project deployed created in step 1 on Tomcat. After Tomcat is started, your default browser will be started. If there is no error in the above steps, you can see Hello World in your browser! .
3. Add dependency. Because you need to use databases, Hibernate, JPA, and so on. Therefore, you need to add the corresponding dependency to the pom file. After the package is added, IntelliJ IDEA automatically introduces or downloads the required package.
4. Create a persistent configuration file. In this case, you need to pay attention to the path issue. You can view the project structure in the specific path. This configuration file contains database configuration information. The database uses hsqldb. If you do not want to use it, you can change it to the database you want to use, but you must modify the corresponding jar package.
<?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. Configure the Model class. The technology used is 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; }}
Define the service. The official Sample Code does not contain the @ Repository annotation.
package com.springapp.mvc;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.stereotype.Repository;/** * Created by yul on 2014/12/18. */@Repositorypublic interface UserRepository extends JpaRepository<User, Long> {}
6. register the bean. Including 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. Define the 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. */@Controllerpublic 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(); } }
I added the method for returning JSON data later.
8. Define view. The official Bootstrap CDN is not easy to use. It is estimated that it is a problem with GFW. It can be replaced by a domestic one. If you are interested in Bootstrap, visit 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" %>
Now, the basic task is complete.
The following is the test. Run your project in Tomcat. You can see the effect in the browser.
If you want to view the returned JSON data. Enter http: // localhost: 8080/api/users in the browser.