码迷,mamicode.com
首页 > 编程语言 > 详细

Spring+SpringMVC+SpringDataJpa整合

时间:2018-05-02 02:38:48      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:tomcat7   temp   listener   title   meta   provider   desc   close   script   

一、思路:

(一) 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项目,添加依赖

  1 <?xml version="1.0" encoding="UTF-8"?>
  2 
  3 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5     <modelVersion>4.0.0</modelVersion>
  6 
  7     <groupId>com.cenobitor</groupId>
  8     <artifactId>ssh_template</artifactId>
  9     <version>1.0-SNAPSHOT</version>
 10     <packaging>war</packaging>
 11 
 12     <name>ssm_template Maven Webapp</name>
 13     <!-- FIXME change it to the project‘s website -->
 14     <url>http://www.example.com</url>
 15 
 16     <properties>
 17         <!--设置编译的版本使用1.8版本-->
 18         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 19         <!-- 和设置编译插件是一样的效果-->
 20         <maven.compiler.source>1.8</maven.compiler.source>
 21         <maven.compiler.target>1.8</maven.compiler.target>
 22         
 23         <junit.version>4.12</junit.version>
 24         <spring.version>4.3.10.RELEASE</spring.version>
 25         <servlet-api.version>2.5</servlet-api.version>
 26         <springdatajpa.version>1.10.4.RELEASE</springdatajpa.version>
 27         <hibernate.version>5.0.7.Final</hibernate.version>
 28         <javassist.version>3.11.0.GA</javassist.version>
 29         <mysql.version>5.1.32</mysql.version>
 30         <druid.version>1.0.9</druid.version>
 31         <commons-fileupload.version>1.3.1</commons-fileupload.version>
 32         <commons-lang3.version>3.3.2</commons-lang3.version>
 33         <commons-io.version>1.3.2</commons-io.version>
 34         <jackson.version>2.8.9</jackson.version>
 35         <jstl.version>1.2</jstl.version>
 36         <jsp-api.version>2.0</jsp-api.version>
 37         <fastjson.version>1.2.28</fastjson.version>
 38         <slf4j.version>1.6.4</slf4j.version>
 39         <lombok.version>1.16.20</lombok.version>
 40     </properties>
 41 
 42     <dependencies>
 43         <!-- Apache工具组件 -->
 44         <dependency>
 45             <groupId>org.apache.commons</groupId>
 46             <artifactId>commons-lang3</artifactId>
 47             <version>${commons-lang3.version}</version>
 48         </dependency>
 49         <dependency>
 50             <groupId>org.apache.commons</groupId>
 51             <artifactId>commons-io</artifactId>
 52             <version>${commons-io.version}</version>
 53         </dependency>
 54         <!-- Jackson Json处理工具包 -->
 55         <dependency>
 56             <groupId>com.fasterxml.jackson.core</groupId>
 57             <artifactId>jackson-databind</artifactId>
 58             <version>${jackson.version}</version>
 59         </dependency>
 60 
 61         <!--alibaba json处理工具包-->
 62         <dependency>
 63             <groupId>com.alibaba</groupId>
 64             <artifactId>fastjson</artifactId>
 65             <version>${fastjson.version}</version>
 66         </dependency>
 67         <!-- 日志处理 -->
 68         <dependency>
 69             <groupId>org.slf4j</groupId>
 70             <artifactId>slf4j-log4j12</artifactId>
 71             <version>${slf4j.version}</version>
 72         </dependency>
 73         <!--实体类get/set注解-->
 74         <dependency>
 75             <groupId>org.projectlombok</groupId>
 76             <artifactId>lombok</artifactId>
 77             <version>${lombok.version}</version>
 78             <scope>provided</scope>
 79         </dependency>
 80         <!--单元测试-->
 81         <dependency>
 82             <groupId>junit</groupId>
 83             <artifactId>junit</artifactId>
 84             <version>${junit.version}</version>
 85         </dependency>
 86 
 87         <!-- Spring -->
 88         <dependency>
 89             <groupId>org.springframework</groupId>
 90             <artifactId>spring-context</artifactId>
 91             <version>${spring.version}</version>
 92         </dependency>
 93         <dependency>
 94             <groupId>org.springframework</groupId>
 95             <artifactId>spring-beans</artifactId>
 96             <version>${spring.version}</version>
 97         </dependency>
 98         <dependency>
 99             <groupId>org.springframework</groupId>
100             <artifactId>spring-webmvc</artifactId>
101             <version>${spring.version}</version>
102         </dependency>
103         <dependency>
104             <groupId>org.springframework</groupId>
105             <artifactId>spring-jdbc</artifactId>
106             <version>${spring.version}</version>
107         </dependency>
108         <dependency>
109             <groupId>org.springframework</groupId>
110             <artifactId>spring-aspects</artifactId>
111             <version>${spring.version}</version>
112         </dependency>
113         <dependency>
114             <groupId>org.springframework</groupId>
115             <artifactId>spring-jms</artifactId>
116             <version>${spring.version}</version>
117         </dependency>
118         <dependency>
119             <groupId>org.springframework</groupId>
120             <artifactId>spring-context-support</artifactId>
121             <version>${spring.version}</version>
122         </dependency>
123         <dependency>
124             <groupId>org.springframework</groupId>
125             <artifactId>spring-test</artifactId>
126             <version>${spring.version}</version>
127         </dependency>
128         <!--jsp相关-->
129         <dependency>
130             <groupId>javax.servlet</groupId>
131             <artifactId>servlet-api</artifactId>
132             <version>${servlet-api.version}</version>
133             <scope>provided</scope>
134         </dependency>
135         <!-- 文件上传组件 -->
136         <dependency>
137             <groupId>commons-fileupload</groupId>
138             <artifactId>commons-fileupload</artifactId>
139             <version>${commons-fileupload.version}</version>
140         </dependency>
141 
142         <!-- spring data jpa 数据库持久层 -->
143         <dependency>
144             <groupId>org.springframework.data</groupId>
145             <artifactId>spring-data-jpa</artifactId>
146             <version>${springdatajpa.version}</version>
147         </dependency>
148 
149         <!-- hibernate 框架 -->
150         <dependency>
151             <groupId>org.hibernate</groupId>
152             <artifactId>hibernate-core</artifactId>
153             <version>${hibernate.version}</version>
154         </dependency>
155         <dependency>
156             <groupId>org.hibernate</groupId>
157             <artifactId>hibernate-entitymanager</artifactId>
158             <version>${hibernate.version}</version>
159         </dependency>
160 
161         <!-- MySql -->
162         <dependency>
163             <groupId>mysql</groupId>
164             <artifactId>mysql-connector-java</artifactId>
165             <version>${mysql.version}</version>
166         </dependency>
167         <!-- 连接池 -->
168         <dependency>
169             <groupId>com.alibaba</groupId>
170             <artifactId>druid</artifactId>
171             <version>${druid.version}</version>
172         </dependency>
173 
174     </dependencies>
175 
176     <build>
177         <finalName>ssh_template</finalName>
178 
179         <plugins>
180             <!-- 配置Tomcat7插件 -->
181             <plugin>
182                 <groupId>org.apache.tomcat.maven</groupId>
183                 <artifactId>tomcat7-maven-plugin</artifactId>
184                 <version>2.2</version>
185                 <configuration>
186                     <uriEncoding>UTF-8</uriEncoding>
187                 </configuration>
188             </plugin>
189             <!-- 配置打包时跳过测试  -->
190             <plugin>
191                 <groupId>org.apache.maven.plugins</groupId>
192                 <artifactId>maven-surefire-plugin</artifactId>
193                 <version>2.12.4</version>
194             </plugin>
195         </plugins>
196     </build>
197 
198 </project>

(二)applicationContext.xml的配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:tx="http://www.springframework.org/schema/tx"
 5 
 6        xmlns:context="http://www.springframework.org/schema/context"
 7        xmlns:jpa="http://www.springframework.org/schema/data/jpa"
 8 
 9        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
10                         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
11                         http://www.springframework.org/schema/context
12                         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">
13 
14     <!--指定连接池配置-->
15     <!-- dao层 数据库连接部分-->
16     <!-- 加载配置文件 -->
17     <context:property-placeholder location="classpath:properties/db.properties"/>
18 
19     <!-- 配置service扫描 -->
20     <context:component-scan base-package="com.cenobitor.service"/>
21 
22     <!-- 数据库连接池 -->
23     <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
24         <property name="driverClassName" value="${jdbc.driver}"/>
25         <property name="url" value="${jdbc.url}"/>
26         <property name="username" value="${jdbc.username}"/>
27         <property name="password" value="${jdbc.password}"/>
28         <!-- 连接池的最大数据库连接数 -->
29         <property name="maxActive" value="10"/>
30         <!-- 最大空闲数 -->
31         <property name="maxIdle" value="5"/>
32     </bean>
33     <!-- spring整合JPA -->
34     <bean id="entityManagerFactory"
35           class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
36         <property name="dataSource" ref="dataSource" />
37         <!--指定JPA扫描的实体类所在的包-->
38         <property name="packagesToScan" value="com.cenobitor.pojo" />
39         <!-- 指定持久层提供者为Hibernate -->
40         <property name="persistenceProvider">
41             <bean class="org.hibernate.ejb.HibernatePersistence" />
42         </property>
43         <property name="jpaVendorAdapter">
44             <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
45                 <!-- 自动建表 -->
46                 <property name="generateDdl" value="true" />
47                 <property name="database" value="MYSQL" />
48                 <property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
49                 <property name="showSql" value="true" />
50             </bean>
51         </property>
52         <property name="jpaDialect">
53             <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
54         </property>
55     </bean>
56 
57     <!-- 配置事务管理器 -->
58     <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
59         <property name="entityManagerFactory" ref="entityManagerFactory" />
60     </bean>
61 
62     <!-- 开启事务注解 -->
63     <tx:annotation-driven transaction-manager="transactionManager" />
64     <!--指定Spring Data JPA要进行扫描的包,该包中的类框架会自动为其创建代理-->
65     <jpa:repositories base-package="com.cenobitor.dao" />
66 
67 </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 的配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3          xmlns="http://java.sun.com/xml/ns/javaee"
 4          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 5             http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 6          id="WebApp_ID" version="2.5">
 7     <welcome-file-list>
 8         <welcome-file>index.jsp</welcome-file>
 9     </welcome-file-list>
10 
11     <!-- spring配置文件路径 -->
12     <context-param>
13         <param-name>contextConfigLocation</param-name>
14         <param-value>classpath:spring/applicationContext.xml</param-value>
15     </context-param>
16 
17     <listener>
18         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
19     </listener>
20 
21     <!-- 解决post乱码问题 -->
22     <filter>
23         <filter-name>encoding</filter-name>
24         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
25         <!-- 设置编码参是UTF8 -->
26         <init-param>
27             <param-name>encoding</param-name>
28             <param-value>UTF-8</param-value>
29         </init-param>
30     </filter>
31     <filter-mapping>
32         <filter-name>encoding</filter-name>
33         <url-pattern>/*</url-pattern>
34     </filter-mapping>
35 
36 
37 
38     <!-- 配置SpringMvc 前端控制器 -->
39     <servlet>
40         <servlet-name>springmvc</servlet-name>
41         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
42         <!--指定SpringMvc 配置文件-->
43         <!-- springmvc的配置文件默认路径是 /WEB-INF/${servlet-name}_servlet.xml -->
44         <init-param>
45             <param-name>contextConfigLocation</param-name>
46             <param-value>classpath:spring/springmvc.xml</param-value>
47         </init-param>
48     </servlet>
49     <servlet-mapping>
50         <servlet-name>springmvc</servlet-name>
51         <url-pattern>*.action</url-pattern>
52     </servlet-mapping>
53 
54 </web-app>

(四)springMVC的配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xmlns:mvc="http://www.springframework.org/schema/mvc"
 6        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
 7               http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
 8               http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
 9 
10     <!--配置controller扫描-->
11     <context:component-scan base-package="com.cenobitor.controller"/>
12 
13     <!-- 注解驱动 -->
14     <mvc:annotation-driven/>
15 
16     <!--&lt;!&ndash;自定义转换器配置模板&ndash;&gt;
17     &lt;!&ndash;使用自定义转换器&ndash;&gt;
18     <mvc:annotation-driven conversion-service="myConverter" />
19 
20     &lt;!&ndash; 定义转换器 &ndash;&gt;
21     <bean id="myConverter" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
22         <property name="converters">
23             <set>
24                 &lt;!&ndash; 日期转换器 &ndash;&gt;
25                 <bean class="com.cenobitor.converter.DateConverter" />
26             </set>
27         </property>
28     </bean>-->
29 
30     <!-- 配置多媒体解析器 -->
31     <!-- 注意:这里的id只能是multipartResolver -->
32     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
33         <!-- 限定文件最大上传大小为:8MB -->
34         <property name="maxUploadSize" value="8388608" />
35     </bean>
36 
37     <!--可减少简写路径名-->
38     <!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
39         &lt;!&ndash; 配置逻辑视图的前缀 &ndash;&gt;
40         <property name="prefix" value="/WEB-INF/views/"/>
41         <property name="suffix" value=".jsp"/>
42     </bean>-->
43 </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,自动建表

 1 package com.cenobitor.pojo;
 2 
 3 import lombok.Data;
 4 import javax.persistence.*;
 5 
 6 /**
 7  * @Description:
 8  * @Date: Created in 11:05 AM 2018/5/1
 9  * @Author: Cenobitor
10  * @Modified By:
11  */
12 @Data
13 @Entity
14 @Table(name = "t_pic")
15 public class Pic {
16 
17     @Id
18     @GeneratedValue
19     @Column(name = "t_id")
20     private Integer id;
21     @Column(name = "t_name")
22     private String name;
23     @Column(name = "t_url")
24     private String url;
25 
26     public Pic(String name, String url) {
27         this.name = name;
28         this.url = url;
29     }
30 
31     public Pic() {
32     }
33 }

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 }
 1 package com.cenobitor.service.impl;
 2 
 3 import com.cenobitor.dao.PicRepository;
 4 import com.cenobitor.pojo.Pic;
 5 import com.cenobitor.service.UploadFileService;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.stereotype.Service;
 8 import org.springframework.transaction.annotation.Transactional;
 9 import org.springframework.web.multipart.MultipartFile;
10 import java.io.File;
11 import java.io.IOException;
12 import java.util.UUID;
13 
14 @Service
15 @Transactional
16 public class UploadFileServiceImpl implements UploadFileService {
17 
18 
19     @Autowired
20     private PicRepository repository;
21 
22     @Override
23     public String UploadPic(MultipartFile picFile) {
24         try {
25             // 图片新名字
26             String name = UUID.randomUUID().toString();
27             // 图片原名字
28             String oldName = picFile.getOriginalFilename();
29             // 后缀名
30             String exeName = oldName.substring(oldName.lastIndexOf("."));
31             //保存图片路径为绝对路径
32             File pic = new File("/Users/Shared/jpg/" + name + exeName);
33             // 保存图片到本地磁盘
34             picFile.transferTo(pic);
35 
36             //保存数据到数据库中
37             repository.save(new Pic(name,"../jpg/"+name+exeName));
38             return "/jpg/"+name+exeName;
39 
40         } catch (IOException e) {
41             e.printStackTrace();
42             return null;
43         }
44     }
45 }

5、创建dao层

1 package com.cenobitor.dao;
2 
3 import com.cenobitor.pojo.Pic;
4 import org.springframework.data.jpa.repository.JpaRepository;
5 
6 public interface PicRepository extends JpaRepository<Pic,Integer> {
7 
8 }

6、项目的目录结构

技术分享图片

Spring+SpringMVC+SpringDataJpa整合

标签:tomcat7   temp   listener   title   meta   provider   desc   close   script   

原文地址:https://www.cnblogs.com/gdwkong/p/8977076.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!