spring + springMVC + spring Data + jpa + maven +(Restful风格) 项目框架搭建(即sssp框架)

本文主要总结本人工作中曾用的web项目框架,由于全权交于我一人,故从头搭起,各种查资料,趟坑。。。

一度想照搬http://www.cnblogs.com/007sx/p/5658194.html上的,但有点问题,tamcat一直启动超时,貌似是无法连接数据库,不知道是数据源dataSource的原因还是什么,探究无果后放弃。。。

开始参照之前学习过的sssp框架自己搭建,以下是搭建详细过程:

具体参照:https://www.cnblogs.com/noteless/p/5213075.html

                 和

                 http://www.cnblogs.com/AloneSword/p/3998557.html


项目结构如下:

 

以下是配置文件

pom.xml

<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.jianfeitech.yidian</groupId>
<artifactId>Flow</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<name>Flow</name>
<url>http://maven.apache.org</url>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>


<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.11.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.11.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>4.3.11.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>com.jolbox</groupId>
<artifactId>bonecp</artifactId>
<version>0.8.0.RELEASE</version>
</dependency>
<dependency>
<groupId>com.jolbox</groupId>
<artifactId>bonecp-spring</artifactId>
<version>0.8.0.RELEASE</version>
</dependency>
<dependency>
<groupId>com.jolbox</groupId>
<artifactId>bonecp-provider</artifactId>
<version>0.8.0-alpha1</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>ant</groupId>
<artifactId>ant</artifactId>
<version>1.6.5</version>
</dependency>
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.18.0-GA</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.3.0.Final</version>
</dependency>
<dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5-pre8</version>
        </dependency>
<!-- jackson -->
<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>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.7.1.RELEASE</version>
</dependency>

</dependencies>
<build>
<plugins>
<!-- 编码和编译 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>utf8</encoding>
</configuration>
</plugin>
</plugins>
<finalName>Flow</finalName>
</build>
</project>


web.xml

<?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_2_5.xsd" id="WebApp_ID" version="2.5">


<!-- 配置启动 IOC 容器的 Listener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>


<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- 配置字符编码过滤器 -->
<!-- 字符编码过滤器必须配置在所有过滤器的最前面! -->
<filter>
<filter-name>CharacterEncodingFilter</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>
</filter>

<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
<filter-name>OpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>OpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- 配置 SpringMVC 的 DispatcherServlet -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springDispatcherServlet-servlet.xml</param-value>
        </init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

</web-app>


applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<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:tx="http://www.springframework.org/schema/tx" 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.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">


<!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.jianfeitech.yidian">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
<context:exclude-filter type="annotation"
expression="org.springframework.web.bind.annotation.ControllerAdvice" />
</context:component-scan>


<!-- 配置数据源 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 亦可不用BoneCPDataSource,可换成其他数据源,如c3p0 -->
<bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource">
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>


<!-- 配置其他属性 -->
</bean>


<!-- 配置 JPA 的 EntityManagerFactory -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean>
</property>
<property name="packagesToScan" value="com.jianfeitech.yidian"></property>
<property name="jpaProperties">
<props>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>


<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory
</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
</props>
</property>
<property name="sharedCacheMode" value="ENABLE_SELECTIVE"></property>
</bean>


<!-- 配置事务 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean>


<!-- 配置支持基于注解的事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />


<!-- 配置 SpringData -->
<jpa:repositories base-package="com.jianfeitech.yidian"
entity-manager-factory-ref="entityManagerFactory"></jpa:repositories>


</beans>


springDispatcherServlet-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
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-4.0.xsd">


<!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.jianfeitech.yidian"
use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
<context:include-filter type="annotation"
expression="org.springframework.web.bind.annotation.ControllerAdvice" />
</context:component-scan>


<mvc:default-servlet-handler />
<mvc:annotation-driven></mvc:annotation-driven>


<!-- 用于返回json格式 -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/x-www-form-urlencoded;charset=UTF-8</value>
</list>
</property>
</bean>


<!-- 完成请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>


</beans>


ehcache.xml

<ehcache>


<!-- Sets the path to the directory where cache .data files are created. 
If the path is a Java System Property it is replaced by its value in the 
running VM. The following properties are translated: user.home - User's home 
directory user.dir - User's current working directory java.io.tmpdir - Default 
temp file path -->
<diskStore path="java.io.tmpdir" />




<!--Default Cache configuration. These will applied to caches programmatically 
created through the CacheManager. The following attributes are required for 
defaultCache: maxInMemory - Sets the maximum number of objects that will 
be created in memory eternal - Sets whether elements are eternal. If eternal, 
timeouts are ignored and the element is never expired. timeToIdleSeconds 
- Sets the time to idle for an element before it expires. Is only used if 
the element is not eternal. Idle time is now - last accessed time timeToLiveSeconds 
- Sets the time to live for an element before it expires. Is only used if 
the element is not eternal. TTL is now - creation time overflowToDisk - Sets 
whether elements can overflow to disk when the in-memory cache has reached 
the maxInMemory limit. -->
<defaultCache maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" />


<!--Predefined caches. Add your cache configuration settings here. If you 
do not have a configuration for your cache a WARNING will be issued when 
the CacheManager starts The following attributes are required for defaultCache: 
name - Sets the name of the cache. This is used to identify the cache. It 
must be unique. maxInMemory - Sets the maximum number of objects that will 
be created in memory eternal - Sets whether elements are eternal. If eternal, 
timeouts are ignored and the element is never expired. timeToIdleSeconds 
- Sets the time to idle for an element before it expires. Is only used if 
the element is not eternal. Idle time is now - last accessed time timeToLiveSeconds 
- Sets the time to live for an element before it expires. Is only used if 
the element is not eternal. TTL is now - creation time overflowToDisk - Sets 
whether elements can overflow to disk when the in-memory cache has reached 
the maxInMemory limit. -->


<!-- Sample cache named sampleCache1 This cache contains a maximum in memory 
of 10000 elements, and will expire an element if it is idle for more than 
5 minutes and lives for more than 10 minutes. If there are more than 10000 
elements it will overflow to the disk cache, which in this configuration 
will go to wherever java.io.tmp is defined on your system. On a standard 
Linux system this will be /tmp" -->
<cache name="sampleCache1" maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" />


<!-- Sample cache named sampleCache2 This cache contains 1000 elements. 
Elements will always be held in memory. They are not expired. -->
<cache name="sampleCache2" maxElementsInMemory="1000" eternal="true"
timeToIdleSeconds="0" timeToLiveSeconds="0" overflowToDisk="false" />
-->


<!-- Place configuration for your caches following -->


</ehcache>


db.properties

jdbc.user=root
jdbc.password=root
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/flow_dev?useUnicode\=true&characterEncoding\=UTF-8


-----------------------------------------------------------------------------------------------------------------------------

以下是测试类:

User.java(实体类)

package com.jianfeitech.yidian.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "user")
public class User implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "account")
private String account;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getAccount() {
return account;
}

public void setAccount(String account) {
this.account = account;
}

}


UserDao.java(Dao层)

package com.jianfeitech.yidian.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.jianfeitech.yidian.model.User;

public interface UserDao extends JpaRepository<User, Long> {
}


UserService.java(Service层)

package com.jianfeitech.yidian.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.jianfeitech.yidian.dao.UserDao;
import com.jianfeitech.yidian.model.User;

@Service
@Transactional
public class UserService {
@Autowired
private UserDao userDao;

public String add(User user) {
userDao.save(user);
return "添加成功!";
}

public String addUser(String account) {
User user = new User();
user.setAccount(account);
userDao.save(user);
return "添加成功!";
}

public User getOneUser(Long id) {
return userDao.findOne(id);
}
}


UserController.java(Controller层)

package com.jianfeitech.yidian.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.jianfeitech.yidian.model.User;
import com.jianfeitech.yidian.service.UserService;

@RestController
@RequestMapping(value = "/frame")
public class UserController {
@Autowired
private UserService userService;

@RequestMapping(value = "/saveUser", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE
+ ";charset=UTF-8")
public String saveUser(@RequestBody User user) {
System.out.println("进来了~~~~");
return userService.add(user);
}

@RequestMapping(value = "/saveUser/{account}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE
+ ";charset=UTF-8")
public String add(@PathVariable String account) {
return userService.addUser(account);
}

@RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE
+ ";charset=UTF-8")
public User add(@PathVariable Long id) {
return userService.getOneUser(id);
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值