Spring+SpringMVC+SpringDataJpa整合
一、思路:
(一) Dao层与Service层:
applicationContext.xml。
a) 数据库连接池
b) 整合jpa
c) 配置@service文件扫描器。
d) 配置事务管理管理器,开启事务注解
e) 配置jpa扫描器
(二)Controller层:
Springmvc.xml
1、包扫描器,扫描@Controller注解的类。
2、配置注解驱动。
3、视图解析器。
(三)web.xml
1. 配置spring容量监听器
2. 配置前端控制器
二、构建项目
(一)构建maven项目,添加依赖
<?xml version="1.0" encoding="UTF-8"?> <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.cenobitor</groupId>
<artifactId>ssh_template</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging> <name>ssm_template Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url> <properties>
<!--设置编译的版本使用1.8版本-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- 和设置编译插件是一样的效果-->
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target> <junit.version>4.12</junit.version>
<spring.version>4.3.10.RELEASE</spring.version>
<servlet-api.version>2.5</servlet-api.version>
<springdatajpa.version>1.10.4.RELEASE</springdatajpa.version>
<hibernate.version>5.0.7.Final</hibernate.version>
<javassist.version>3.11.0.GA</javassist.version>
<mysql.version>5.1.32</mysql.version>
<druid.version>1.0.9</druid.version>
<commons-fileupload.version>1.3.1</commons-fileupload.version>
<commons-lang3.version>3.3.2</commons-lang3.version>
<commons-io.version>1.3.2</commons-io.version>
<jackson.version>2.8.9</jackson.version>
<jstl.version>1.2</jstl.version>
<jsp-api.version>2.0</jsp-api.version>
<fastjson.version>1.2.28</fastjson.version>
<slf4j.version>1.6.4</slf4j.version>
<lombok.version>1.16.20</lombok.version>
</properties> <dependencies>
<!-- Apache工具组件 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<!-- Jackson Json处理工具包 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency> <!--alibaba json处理工具包-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!-- 日志处理 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!--实体类get/set注解-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency> <!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</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-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</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>
<!--jsp相关-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<!-- 文件上传组件 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency> <!-- spring data jpa 数据库持久层 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${springdatajpa.version}</version>
</dependency> <!-- hibernate 框架 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency> <!-- MySql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- 连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency> </dependencies> <build>
<finalName>ssh_template</finalName> <plugins>
<!-- 配置Tomcat7插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<uriEncoding>UTF-8</uriEncoding>
</configuration>
</plugin>
<!-- 配置打包时跳过测试 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12.4</version>
</plugin>
</plugins>
</build> </project>
(二)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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
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/tx http://www.springframework.org/schema/tx/spring-tx.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"> <!--指定连接池配置-->
<!-- dao层 数据库连接部分-->
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:properties/db.properties"/> <!-- 配置service扫描 -->
<context:component-scan base-package="com.cenobitor.service"/> <!-- 数据库连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- 连接池的最大数据库连接数 -->
<property name="maxActive" value="10"/>
<!-- 最大空闲数 -->
<property name="maxIdle" value="5"/>
</bean>
<!-- spring整合JPA -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--指定JPA扫描的实体类所在的包-->
<property name="packagesToScan" value="com.cenobitor.pojo" />
<!-- 指定持久层提供者为Hibernate -->
<property name="persistenceProvider">
<bean class="org.hibernate.ejb.HibernatePersistence" />
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!-- 自动建表 -->
<property name="generateDdl" value="true" />
<property name="database" value="MYSQL" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
</bean> <!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean> <!-- 开启事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!--指定Spring Data JPA要进行扫描的包,该包中的类框架会自动为其创建代理-->
<jpa:repositories base-package="com.cenobitor.dao" /> </beans>
1 jdbc.driver=com.mysql.jdbc.Driver
2 jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8
3 jdbc.username=root
4 jdbc.password=
(三)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">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> <!-- spring配置文件路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext.xml</param-value>
</context-param> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- 解决post乱码问题 -->
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!-- 设置编码参是UTF8 -->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- 配置SpringMvc 前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--指定SpringMvc 配置文件-->
<!-- springmvc的配置文件默认路径是 /WEB-INF/${servlet-name}_servlet.xml -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping> </web-app>
(四)springMVC的配置
<?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/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!--配置controller扫描-->
<context:component-scan base-package="com.cenobitor.controller"/> <!-- 注解驱动 -->
<mvc:annotation-driven/> <!--<!–自定义转换器配置模板–>
<!–使用自定义转换器–>
<mvc:annotation-driven conversion-service="myConverter" /> <!– 定义转换器 –>
<bean id="myConverter" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<!– 日期转换器 –>
<bean class="com.cenobitor.converter.DateConverter" />
</set>
</property>
</bean>--> <!-- 配置多媒体解析器 -->
<!-- 注意:这里的id只能是multipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 限定文件最大上传大小为:8MB -->
<property name="maxUploadSize" value="8388608" />
</bean> <!--可减少简写路径名-->
<!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!– 配置逻辑视图的前缀 –>
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>-->
</beans>
(五)log4j配置文件,位于resources包下:
1 log4j.rootLogger=DEBUG, Console
2 #Console
3 log4j.appender.Console=org.apache.log4j.ConsoleAppender
4 log4j.appender.Console.layout=org.apache.log4j.PatternLayout
5 log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
6 log4j.logger.java.sql.ResultSet=INFO
7 log4j.logger.org.apache=INFO
8 log4j.logger.java.sql.Connection=DEBUG
9 log4j.logger.java.sql.Statement=DEBUG
10 log4j.logger.java.sql.PreparedStatement=DEBUG
三、 图片上传预览
1、创建pojo,自动建表
package com.cenobitor.pojo; import lombok.Data;
import javax.persistence.*; /**
* @Description:
* @Date: Created in 11:05 AM 2018/5/1
* @Author: Cenobitor
* @Modified By:
*/
@Data
@Entity
@Table(name = "t_pic")
public class Pic { @Id
@GeneratedValue
@Column(name = "t_id")
private Integer id;
@Column(name = "t_name")
private String name;
@Column(name = "t_url")
private String url; public Pic(String name, String url) {
this.name = name;
this.url = url;
} public Pic() {
}
}
2、设置文件存储的虚拟路径
2、创建上传页面
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>上传图片</title>
6 </head>
7 <body>
8 <form id="upload" action="/uploadpic.action" method="post" enctype="multipart/form-data">
9 <input type="file" name="picFile"/>
10 <br/>
11 <input type="submit" value="提交"/>
12 </form>
13 </body>
14 </html>
3、创建Controller类
1 package com.cenobitor.controller;
2
3 import com.cenobitor.service.UploadFileService;
4 import org.springframework.beans.factory.annotation.Autowired;
5 import org.springframework.stereotype.Controller;
6 import org.springframework.web.bind.annotation.*;
7 import org.springframework.web.multipart.MultipartFile;
8
9 @Controller
10 public class UploadFileController {
11
12 @Autowired
13 private UploadFileService uploadFileService;
14
15 //图片上传用MultipartFile接收文件,其中参数名要表单中的文件名一致
16 @RequestMapping("/uploadpic")
17 public String uploadPic(MultipartFile picFile) throws Exception {
18 String picUrl = uploadFileService.UploadPic(picFile);
19 if (picUrl == null){
20 return "redirect:error.html";
21 }
22 //重定向预览图片
23 return "redirect:"+picUrl;
24 }
25 }
4、创建service层
1 public interface UploadFileService {
2 public String UploadPic(MultipartFile picFile);
3 }
package com.cenobitor.service.impl; import com.cenobitor.dao.PicRepository;
import com.cenobitor.pojo.Pic;
import com.cenobitor.service.UploadFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID; @Service
@Transactional
public class UploadFileServiceImpl implements UploadFileService { @Autowired
private PicRepository repository; @Override
public String UploadPic(MultipartFile picFile) {
try {
// 图片新名字
String name = UUID.randomUUID().toString();
// 图片原名字
String oldName = picFile.getOriginalFilename();
// 后缀名
String exeName = oldName.substring(oldName.lastIndexOf("."));
//保存图片路径为绝对路径
File pic = new File("/Users/Shared/jpg/" + name + exeName);
// 保存图片到本地磁盘
picFile.transferTo(pic); //保存数据到数据库中
repository.save(new Pic(name,"../jpg/"+name+exeName));
return "/jpg/"+name+exeName; } catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
5、创建dao层
package com.cenobitor.dao; import com.cenobitor.pojo.Pic;
import org.springframework.data.jpa.repository.JpaRepository; public interface PicRepository extends JpaRepository<Pic,Integer> { }
6、项目的目录结构
Spring+SpringMVC+SpringDataJpa整合的更多相关文章
- Spring+springmvc+Mybatis整合案例 annotation版(myeclipse)详细版
Spring+springmvc+Mybatis整合案例 Version:annotation版 文档结构图: 从底层开始做起: 01.配置web.xml文件 <?xml version=&qu ...
- Spring+springmvc+Mybatis整合案例 xml配置版(myeclipse)详细版
Spring+springmvc+Mybatis整合案例 Version:xml版(myeclipse) 文档结构图: 从底层开始做起: 01.配置web.xml文件 <?xml version ...
- 框架篇:Spring+SpringMVC+hibernate整合开发
前言: 最近闲的蛋疼,搭个框架写成博客记录下来,拉通一下之前所学知识,顺带装一下逼. 话不多说,我们直接步入正题. 准备工作: 1/ IntelliJIDEA的安装配置:jdk/tomcat等..(本 ...
- 框架篇:Spring+SpringMVC+Mybatis整合开发
前言: 前面我已搭建过ssh框架(http://www.cnblogs.com/xrog/p/6359706.html),然而mybatis表示不服啊. Mybatis:"我抗议!" ...
- spring+springmvc+hibernate整合遇到的问题
spring+springmvc+hibernate整合遇到的问题2016年10月20日 23:24:03 守望dfdfdf 阅读数:702 标签: ssh学习经历的异常exception异常框架更多 ...
- ssm之spring+springmvc+mybatis整合初探
1.基本目录如下 2.首先是向lib中加入相应的jar包 3.然后在web.xml中加入配置,使spring和springmvc配置文件起作用. <?xml version="1. ...
- springmvc框架(Spring SpringMVC, Hibernate整合)
直接干货 model 考虑给用户展示什么.关注支撑业务的信息构成.构建成模型. control 调用业务逻辑产生合适的数据以及传递数据给视图用于呈献: view怎样对数据进行布局,以一种优美的方式展示 ...
- Eclipse Meaven Spring SpringMVC Mybaits整合
本示例是在:Ubuntu15上实现的:Windows上安装Maven将不太相同. Maven Install Run command sudo apt-get install maven, to in ...
- spring+springmvc+mybaties整合实例
spring+springmvc+mybaties即SSM框架整合在ecpliseee中开发:很么多西都是只有只有自己上手做,才会懂.昨晚熬了很久,才弄出来.也希望对新手有帮助!下面整理一下思路:关键 ...
随机推荐
- 940. Distinct Subsequences II
Given a string S, count the number of distinct, non-empty subsequences of S . Since the result may b ...
- jvm高级特性(4)(内存分配回收策略)
JVM高级特性与实践(四):内存分配 与 回收策略 一. 内存分配 和 回收策略 1,对象内存分配的概念: 往大方向讲,它就是在堆上分配(但也可能经过JIT编译后被拆散为标量类型并间接地栈上分配), ...
- iOS设置圆角的三种方式
第一种方法:通过设置layer的属性 最简单的一种,但是很影响性能,一般在正常的开发中使用很少. ? 1 2 3 4 5 6 7 UIImageView *imageView = [[UIImageV ...
- AngularJS自定义Directive
(编辑完这篇之后,发现本篇内容应该属于AngularJS的进阶,内容有点多,有几个例子偷懒直接用了官方的Demo稍加了一些注释,敬请见谅). 前面一篇介绍了各种常用的AngularJS内建的Direc ...
- 理解HashMap的原理
HashMap内部数据结构 HashMap内部采用数组和链表结合的方式来存取数据(见下图).这种方式有什么好处呢? 我们知道,数组操作对于检索是O(1)的,能够很快的根据数组的下标定位对 ...
- An assembly specified in the application dependencies manifest
.Net Core 运行的时候报错 An assembly specified in the application dependencies manifest (xxx.deps.json) was ...
- .Net Core 发布WindowsServices
项目代码文件夹 执行命令 dotnet publish -c Release -r win-x64
- 【树】Convert Sorted Array to Binary Search Tree
题目: Given an array where elements are sorted in ascending order, convert it to a height balanced BST ...
- eclipse maven插件创建maven项目
1.下载好maven压缩包http://maven.apache.org/ ,解压后放到想要安装的目录,如E:/server/maven,然后配置好maven环境变量,找到maven安装目录下conf ...
- Impala学习–Impala后端代码分析
Table of Contents 1 代码结构 2 StateStore 3 Scheduler 4 impalad启动流程 5 Coordinator 6 ExecNode 7 PlanFragm ...