This article will introduce you from one of the most basic Java projects, to Web engineering, to integrated spring, SPRINGMVC, and Springdatajpa+hibernate.
Usually we can build a project from a template, or directly import a project, and this article chose to start with the most basic Java project, to show more principles.
Of course, we started with one of the most basic MAVEN projects, in fact, the common non-MAVEN project, the construction process is almost the same, but the jar package requires us to manually add to the project, and the MAVEN project is only to modify the configuration file.
The following is officially started.
1, based on MAVEN (if not using Maven can also use traditional engineering) to create the most basic Java engineering
New project, select Maven Project,next:
Check it out as a simple project (Create a Simplicity project), Next:
Group ID for your domain name reverse order, usually with the project source of the package name, artifact ID for this group ID in the project's unique name, according to your hobby, how to fill all the lines, and then finish:
This is the resulting engineering directory structure that is like this:
Pom.xml is the core document of Maven.
2, the project is set as a Dynamic Web page mode
Next, convert the project to Web engineering, right-click on the project properties, click Project Facets in the left menu, and click Convert to faceted from ... :
On the right, we tick Dynamic Web Module (animated web), and then click OK:
There will be an extra webcontent directory:
In the Web-inf directory, add the Web.xml file as follows:
<?xml version= "1.0" encoding= "UTF-8"?> <web-app xmlns:xsi=
"Http://www.w3.org/2001/XMLSchema-instance" "
xmlns=" Http://java.sun.com/xml/ns/javaee "
xsi:schemalocation=" Http://java.sun.com/xml/ns/javaee http ://java.sun.com/xml/ns/javaee/web-app_3_0.xsd "
version=" 3.0 ">
<display-name>SpringDataJPA< /display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Then add a welcome page index.html:
At this point the directory structure is as follows:
At this point, you can right-click the project, Run on server, you can see the effect:
3. Integrated SPRING+SPRINGMVC
Create a new package and add some interfaces and classes (which are listed later in the code), as shown in the package structure:
Need to add jar package, directly modify the Pom file, if for ordinary works, press Pom.xml jar package, add to the project can be.
First add the use of the spring version, facilitate unified management, and then add all the required jar packs, the following add all the jar packages needed here, after the completion of the Pom.xml is as follows:
<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < Modelversion>4.0.0</modelversion> <groupId>com.anxpp</groupId> <artifactId> Springdatajpa</artifactid> <version>0.0.1-SNAPSHOT</version> <properties> <!-- Spring version number--> <spring.version>4.2.5.RELEASE</spring.version> </properties> <dependencies > <!--Spring Core package--> <dependency> <groupId>org.springframework</groupId> <artifact Id>spring-core</artifactid> <version>${spring.version}</version> </dependency> < Dependency> <groupId>org.springframework</groupId> <artifactid>spring-web</artifactid > <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version >${spring.version}</version> </dependency> <dependency> <groupid>org.springframework& Lt;/groupid> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> & lt;/dependency> <dependency> <groupId>org.springframework</groupId> <artifactid>spring
-jdbc</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> < version>${spring.version}</version> </dependency> <dependency> <groupId> Org.springframework</groupid> <artifactId>spring-aop</artifactId> <version>${ Spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactid>spring-context-support</artifactid > <version>${spring.version}</version> </dependency> <dependency> <groupid>org. Springframework</groupid> <artifactId>spring-test</artifactId> <version>${spring.version }</version> </dependency> <dependency> <groupId>org.springframework</groupId> <
Artifactid>spring-orm</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa< /artifactid> <version>1.10.1.RELEASE</version> </dependency> </dependencies> </ Project>
Add the Spring configuration file Applicationcontext.xml under the Web-inf directory and add the following:
<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns:
Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:p= "http://www.springframework.org/schema/p" Xmlns:tx = "Http://www.springframework.org/schema/tx" xmlns:mvc= "Http://www.springframework.org/schema/mvc" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-4.2.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/context /spring-context-4.2.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-4.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop-4.2.xsd Http://www.springframework.org/schema/mvc Http://www.springframework.org/schema/mvc/spRing-mvc-4.2.xsd "> <!--open IOC annotation scan--> <context:component-scan base-package=" Com.anxpp.demo "/> <!-- Open MVC annotation Scan--> <mvc:annotation-driven/> </beans>
Modify Web.xml to add Spring in:
<?xml version= "1.0" encoding= "UTF-8"?> <web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http:// Java.sun.com/xml/ns/javaee/web-app_3_0.xsd "version=" 3.0 "> <display-name>springdatajpa</display-name > <listener> <listener-class>org.springframework.web.context.contextloaderlistener</ listener-class> </listener> <context-param> <param-name>contextconfiglocation</param-name
> <param-value>WEB-INF/applicationContext.xml</param-value> </context-param> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class> Org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name> Contextconfiglocation</param-name> <param-value>classpath*:springmvc-servlet.xml</param-value > </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name> Springmvc</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> < welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app >
Here's how to write the code, note don't forget to write, in the beginning of this section has given the package hierarchy.
Entity User:
Package com.anxpp.demo.core.entity;
public class User {
private Integer ID;
private String name;
Public User (Integer ID, String name) {
this.id = ID;
this.name = name;
Public Integer GetId () {return
ID;
}
public void SetId (Integer id) {
this.id = ID;
}
Public String GetName () {return
name;
}
public void SetName (String name) {
this.name = name;
}
@Override public
String toString () {return
"ID:" +id+ ", Name:" +name;
}
}
DAO Layer Interface Userdao:
Package Com.anxpp.demo.core.dao;
Import Com.anxpp.demo.core.entity.User;
Public interface Userdao {
User getuser (Integer id,string name);
}
DAO Layer Implementation Userdaoimpl:
Package Com.anxpp.demo.core.dao.impl;
Import org.springframework.stereotype.Repository;
Import Com.anxpp.demo.core.dao.UserDao;
Import Com.anxpp.demo.core.entity.User;
@Repository public
class Userdaoimpl implements userdao{
@Override public
User GetUser (Integer ID, String Name) {return
new User (ID, name);
}
}
Service Layer Interface UserService:
Package com.anxpp.demo.core.service;
Import Com.anxpp.demo.core.entity.User;
Public interface UserService {
User getuser (Integer ID, String name);
Service Layer Implementation:
Package Com.anxpp.demo.core.service.impl;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Service;
Import Com.anxpp.demo.core.dao.UserDao;
Import Com.anxpp.demo.core.entity.User;
Import Com.anxpp.demo.core.service.UserService;
@Service public
class Userserviceimpl implements userservice{
@Autowired
Userdao Userdao;
@Override public
User GetUser (Integer ID, String name) {return
userdao.getuser (ID, name);
}
}
Controller Layer Democontroller:
Package Com.anxpp.demo.controller;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.bind.annotation.ResponseBody;
Import Com.anxpp.demo.core.service.UserService;
@Controller
@RequestMapping ("/") public
class Democontroller {
@Autowired
userservice userservice ;
@RequestMapping ("/")
@ResponseBody public
String Index () {return
' index ';
}
@RequestMapping ("/getuser")
@ResponseBody public
String GetUser (Integer ID, String name) {
return Userservice.getuser (ID, name). toString ();
}
This is not going to run on Server directly, because the jar package will not be released together, we need to configure the following:
Right-click the project selection properties, according to the following figure configuration:
This is the time to run the test, the effect is as follows:
Here, we haven't manipulated the database yet.
4, add back JSON format data support
Now, we often use JSON as a format for data transfer, and the following is the support for SPRINGMVC to return JSON
First add the jar package:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId> jackson-databind</artifactid>
<version>2.5.0</version>
</dependency>
< dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId> jackson-core</artifactid>
<version>2.5.0</version>
</dependency>
< dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId> jackson-annotations</artifactid>
<version>2.5.0</version>
</dependency>
Then rewrite the GetUser () method as follows:
@RequestMapping ("/getuser")
@ResponseBody public
map<string, object> getuser (Integer ID, String name) {
map<string, object> Map = new hashmap<string, object> ();
Map.put ("state", "success");
Map.put ("Data", Userservice.getuser (ID, name));
return map;
}
After the rerun, the access effect is as follows:
At this point, you can return the JSON data.
5. Configure static resource access
Under normal circumstances, Web-inf directory resources, we are not directly accessible, if our site is composed of Html+ajax, then you can create a new HTML directory outside the Web-inf, and configure the default filter for Web.xml, but note that you want to put it before the SPINGMVC filter:
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html </url-pattern>
</servlet-mapping>
If you are sure to access resources in the Web-inf directory, by looking through the spring official documentation, you find two ways
1, handwriting a resource mapper:
@Configuration
@EnableWebMvc Public
class Webconfig extends Webmvcconfigureradapter {
@Override
public void Addresourcehandlers (Resourcehandlerregistry registry) {
Registry.addresourcehandler ("/resources/** ")
. Addresourcelocations ("/public-resources/").
Setcachecontrol (cachecontrol.maxage (1, timeunit.hours). Cachepublic ());
}
As you can see, you can also set the caching time, and in a simpler way, the XML configuration:
<mvc:resources mapping= "/resources/**" location= "/public-resources/" >
<mvc:cache-control max-age= " 3600 "cache-public=" true "/>
</mvc:resources>
You can also add the following:
<!--access to static resource files, leave the path that cannot be mapping to controller to the default servlet handler processing-->
6, garbled solution
We usually submit requests using AJAX, but we also use the address bar for direct testing. Request to submit the split get and post.
The use of Post submission request is, generally will not appear in Chinese garbled, but if it does appear garbled, you can add a code filter in Web.xml to solve:
<filter>
<filter-name>CharacterEncoding</filter-name>
<filter-class> org.springframework.web.filter.characterencodingfilter</filter-class>
<init-param>
< param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param >
<init-param>
<param-name>forceEncoding</param-name>
<param-value> true</param-value>
</init-param>
</filter>
<filter-mapping>
< filter-name>characterencoding</filter-name>
<url-pattern>/*</url-pattern>
</ Filter-mapping>
The above can only solve the post of Chinese garbled, for get (including the browser address bar direct submission method), we need to modify the Tomcat configuration, in the Conf directory in the Server.xml found and the following modifications:
<connector connectiontimeout= "20000" port= "8080" protocol= "http/1.1" redirectport= "8443" URIEncoding= "UTF-8"/ >
If we are just testing, the project is not deployed, you can find server.xml directly under the server in Eclipse and make the same changes as above:
7. Integrate Springdatajpa+hibernate
You can use this text to understand JPA:JPA specification Introduction and example (Java Data Persistence solution)
SPRINGDATAJPA is also a lightweight solution, and the preferred hibernate implements JPA.
First, the jar package, the SPRINGDATAJPA jar package, was added to the previous integration of spring, and the following is the hibernate (and MySQL-driven) jar package.
<!--hibernate--> <dependency> <groupId>org.hibernate</groupId> <artifactid>hiber Nate-core</artifactid> <version>${hibernate.version}</version> </dependency> < Dependency> <groupId>org.hibernate</groupId> <artifactid>hibernate-ehcache</artifactid > <version>${hibernate.version}</version> </dependency> <dependency> <groupid>o Rg.hibernate</groupid> <artifactId>hibernate-entitymanager</artifactId> <version>${ hibernate.version}</version> </dependency> <dependency> <groupid>org.hibernate</ Groupid> <artifactId>hibernate-c3p0</artifactId> <version>${hibernate.version}</version > </dependency> <dependency> <groupId>mysql</groupId> <artifactid>mysql-connect Or-java</artifactid> <version>5.1.9</version> </dependency>
The unified management version is:
<!--hibernate version number-->
Add JPA configuration file Persistence.xml to Meta-inf directory, this article describes the database using MySQL. and add the following:
<?xml version= "1.0" encoding= "UTF-8"?> <persistence version= "1.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_1_0.xsd "> <persistence-unit name=" Demo " Transaction-type= "Resource_local" > <!--provider>org.eclipse.persistence.jpa.persistenceprovider</ Provider--> <provider>org.hibernate.ejb.HibernatePersistence</provider> <class> com.ninelephas.meerkat.pojo.user</class> <!--MYSql connection--> <properties> <property name= "Hiber Nate.connection.driver_class "value=" Com.mysql.jdbc.Driver "/> <property name=" Hibernate.connection.url " Value= "Jdbc:mysql://127.0.0.1:3306/demo?createdatabaseifnotexist=true"/> <property name= " Hibernate.connection.username "value=" root "/> <property name=" Hibernate.connection.password "value="Root "/> <property name=" Hibernate.dialect "value=" Org.hibernate.dialect.MySQLDialect "/> </PROPERTIES&G
T </persistence-unit> </persistence>
Spring Profile Applicationcontext.xml Add the full content of JPA support:
<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns:
Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:p= "http://www.springframework.org/schema/p" Xmlns:tx = "Http://www.springframework.org/schema/tx" xmlns:mvc= "Http://www.springframework.org/schema/mvc" xmlns:jpa= "
HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/DATA/JPA "xsi:schemalocation=" Http://www.springframework.org/schema/beans
Http://www.springframework.org/schema/beans/spring-beans-4.2.xsd Http://www.springframework.org/schema/context
Http://www.springframework.org/schema/context/spring-context-4.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX Http://www.springframework.org/schema/tx/spring-tx-4.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http:// Www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/SCHEMA/MVC http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/ DATA/JPA http://www.springframework.org/schema/data/jpa/spring-jpa.xsd "> <!--open IOC annotation scan--> <context:co Mponent-scan base-package= "Com.anxpp.demo"/> <bean id= "Entitymanagerfactory"
Org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean "> <property name=" Jpavendoradapter "> <bean class= "Org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" > <property name= "Generateddl" Value= "true"/> <property name= "database" value= "MYSQL"/> </bean> </property> <propert
Y name= "Persistenceunitname" value= "demo"/> </bean> <!--open MVC annotation scan--> <mvc:annotation-driven/> <bean class= "Org.springframework.web.servlet.view.ContentNegotiatingViewResolver" > <property name= " Viewresolvers "> <list> <bean class=" Org.springframEwork.web.servlet.view.InternalResourceViewResolver "> <property name=" prefix "value="/web-inf/view/"/>" <property name= "suffix" value= ". html"/> </bean> </list> </property> <!--used to convert objects to JSON--> <property name= "Defaultviews" > <list> <bean class= "Org.springframework.web.servle T.view.json.mappingjackson2jsonview "/> </list> </property> </bean> <!--access to static resource files will not be Mapp ing to Controller's path to the default servlet handler processing--> <mvc:default-servlet-handler/> <!--configuration transaction manager--> < Bean id= "TransactionManager" class= "Org.springframework.orm.jpa.JpaTransactionManager" > <property name= " Entitymanagerfactory "ref=" entitymanagerfactory/> </bean> <!--enable annotation transactions--> Driven transaction-manager= "TransactionManager"/> <!--Configure the spring Data JPA Scan directory--> <jpa:repositories Ckage= "Com.anxpp.demo"/> </beAns>
To modify an entity:
Package com.anxpp.demo.core.entity;
Import javax.persistence.Entity;
Import Javax.persistence.GeneratedValue;
Import Javax.persistence.GenerationType;
Import Javax.persistence.Id;
Import javax.persistence.Table;
@Entity
@Table Public
class User {
@Id
@GeneratedValue (strategy = Generationtype.auto)
Private Integer ID;
private String name;
Public user () {
} public
User (String name) {
this.name = name;
}
Public Integer GetId () {return
ID;
}
public void SetId (Integer id) {
this.id = ID;
}
Public String GetName () {return
name;
}
public void SetName (String name) {
this.name = name;
}
@Override public
String toString () {return
"ID:" +id+ ", Name:" +name;
}
}
You can erase the DAO layer implementation, and we remember to inherit the DAO layer interface from the powerful jparepository:
Public interface Userdao extends Jparepository<user, serializable>{
User FindByID (Integer ID);
Does it look particularly concise, and does not need to write implementation, SPRINGDATAJPA will automatically help us complete.
To modify the service layer interface:
Package com.anxpp.demo.core.service;
Import java.util.List;
Import Com.anxpp.demo.core.entity.User;
Public interface UserService {
User FindByID (Integer ID);
User Save (String name);
List<user> findall ();
}
To modify the service layer implementation:
Package Com.anxpp.demo.core.service.impl;
Import java.util.List;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Service;
Import Com.anxpp.demo.core.dao.UserDao;
Import Com.anxpp.demo.core.entity.User;
Import Com.anxpp.demo.core.service.UserService;
@Service public
class Userserviceimpl implements userservice{
@Autowired
Userdao Userdao;
@Override public
User FindByID (Integer ID) {return
Userdao.findbyid (ID);
}
@Override public
User Save (String name) {return
userdao.save (new User (name));
@Override public
list<user> FindAll () {return
userdao.findall ();
}
}
Modify controller to provide multiple test interfaces:
Package Com.anxpp.demo.controller;
Import Java.util.HashMap;
Import Java.util.Map;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.bind.annotation.ResponseBody;
Import Com.anxpp.demo.core.service.UserService;
@Controller @RequestMapping ("/") public class Democontroller {@Autowired userservice userservice;
@RequestMapping ("/") @ResponseBody Public String Index () {return ' index ';
@RequestMapping ("/info") public String info () {return "info"; @RequestMapping ("/findall") @ResponseBody public map<string, object> GetUser () {map<string, object> Map
= new hashmap<string, object> ();
Map.put ("state", "success");
Map.put ("Data", Userservice.findall ());
return map; @RequestMapping ("/findbyid") @ResponseBody public map<string, object> FindByID (Integer id) {map<string, Ob Ject>Map = new hashmap<string, object> ();
Map.put ("state", "success");
Map.put ("Data", Userservice.findbyid (ID));
return map; @RequestMapping ("/add") @ResponseBody public map<string, object> Save (String name) {map<string, object>
Map = new hashmap<string, object> ();
Map.put ("state", "success");
Map.put ("Data", Userservice.save (name));
return map; }
}
Operation Effect:
So, what if you need to add a lookup with a specified last name that is greater than the specified value?
If it's SQL, we'll write it like this (?) Represents a parameter):
SELECT * from user WHERE id>? and name like '?% ';
But here, we don't have to write SQL (or HQL), just add a method directly to the DAO layer interface:
List<user> findbyidgreaterthanandnamelike (Integer id,string name);
You do not need to doubt that the above method of execution is to be successful (note: The use of service implementation, call the method remember name+ "%")!
The above is a small set to introduce the most basic Java project to build springmvc+springdatajpa+hibernate related knowledge, hope to help everyone, if you want to learn more information please pay attention to cloud Habitat community website!