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

  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.0modelVersion>
  6 
  7     <groupId>com.cenobitorgroupId>
  8     <artifactId>ssh_templateartifactId>
  9     <version>1.0-SNAPSHOTversion>
 10     <packaging>warpackaging>
 11 
 12     <name>ssm_template Maven Webappname>
 13     
 14     <url>http://www.example.comurl>
 15 
 16     <properties>
 17         
 18         <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
 19         
 20         <maven.compiler.source>1.8maven.compiler.source>
 21         <maven.compiler.target>1.8maven.compiler.target>
 22         
 23         <junit.version>4.12junit.version>
 24         <spring.version>4.3.10.RELEASEspring.version>
 25         <servlet-api.version>2.5servlet-api.version>
 26         <springdatajpa.version>1.10.4.RELEASEspringdatajpa.version>
 27         <hibernate.version>5.0.7.Finalhibernate.version>
 28         <javassist.version>3.11.0.GAjavassist.version>
 29         <mysql.version>5.1.32mysql.version>
 30         <druid.version>1.0.9druid.version>
 31         <commons-fileupload.version>1.3.1commons-fileupload.version>
 32         <commons-lang3.version>3.3.2commons-lang3.version>
 33         <commons-io.version>1.3.2commons-io.version>
 34         <jackson.version>2.8.9jackson.version>
 35         <jstl.version>1.2jstl.version>
 36         <jsp-api.version>2.0jsp-api.version>
 37         <fastjson.version>1.2.28fastjson.version>
 38         <slf4j.version>1.6.4slf4j.version>
 39         <lombok.version>1.16.20lombok.version>
 40     properties>
 41 
 42     <dependencies>
 43         
 44         <dependency>
 45             <groupId>org.apache.commonsgroupId>
 46             <artifactId>commons-lang3artifactId>
 47             <version>${commons-lang3.version}version>
 48         dependency>
 49         <dependency>
 50             <groupId>org.apache.commonsgroupId>
 51             <artifactId>commons-ioartifactId>
 52             <version>${commons-io.version}version>
 53         dependency>
 54         
 55         <dependency>
 56             <groupId>com.fasterxml.jackson.coregroupId>
 57             <artifactId>jackson-databindartifactId>
 58             <version>${jackson.version}version>
 59         dependency>
 60 
 61         
 62         <dependency>
 63             <groupId>com.alibabagroupId>
 64             <artifactId>fastjsonartifactId>
 65             <version>${fastjson.version}version>
 66         dependency>
 67         
 68         <dependency>
 69             <groupId>org.slf4jgroupId>
 70             <artifactId>slf4j-log4j12artifactId>
 71             <version>${slf4j.version}version>
 72         dependency>
 73         
 74         <dependency>
 75             <groupId>org.projectlombokgroupId>
 76             <artifactId>lombokartifactId>
 77             <version>${lombok.version}version>
 78             <scope>providedscope>
 79         dependency>
 80         
 81         <dependency>
 82             <groupId>junitgroupId>
 83             <artifactId>junitartifactId>
 84             <version>${junit.version}version>
 85         dependency>
 86 
 87         
 88         <dependency>
 89             <groupId>org.springframeworkgroupId>
 90             <artifactId>spring-contextartifactId>
 91             <version>${spring.version}version>
 92         dependency>
 93         <dependency>
 94             <groupId>org.springframeworkgroupId>
 95             <artifactId>spring-beansartifactId>
 96             <version>${spring.version}version>
 97         dependency>
 98         <dependency>
 99             <groupId>org.springframeworkgroupId>
100             <artifactId>spring-webmvcartifactId>
101             <version>${spring.version}version>
102         dependency>
103         <dependency>
104             <groupId>org.springframeworkgroupId>
105             <artifactId>spring-jdbcartifactId>
106             <version>${spring.version}version>
107         dependency>
108         <dependency>
109             <groupId>org.springframeworkgroupId>
110             <artifactId>spring-aspectsartifactId>
111             <version>${spring.version}version>
112         dependency>
113         <dependency>
114             <groupId>org.springframeworkgroupId>
115             <artifactId>spring-jmsartifactId>
116             <version>${spring.version}version>
117         dependency>
118         <dependency>
119             <groupId>org.springframeworkgroupId>
120             <artifactId>spring-context-supportartifactId>
121             <version>${spring.version}version>
122         dependency>
123         <dependency>
124             <groupId>org.springframeworkgroupId>
125             <artifactId>spring-testartifactId>
126             <version>${spring.version}version>
127         dependency>
128         
129         <dependency>
130             <groupId>javax.servletgroupId>
131             <artifactId>servlet-apiartifactId>
132             <version>${servlet-api.version}version>
133             <scope>providedscope>
134         dependency>
135         
136         <dependency>
137             <groupId>commons-fileuploadgroupId>
138             <artifactId>commons-fileuploadartifactId>
139             <version>${commons-fileupload.version}version>
140         dependency>
141 
142         
143         <dependency>
144             <groupId>org.springframework.datagroupId>
145             <artifactId>spring-data-jpaartifactId>
146             <version>${springdatajpa.version}version>
147         dependency>
148 
149         
150         <dependency>
151             <groupId>org.hibernategroupId>
152             <artifactId>hibernate-coreartifactId>
153             <version>${hibernate.version}version>
154         dependency>
155         <dependency>
156             <groupId>org.hibernategroupId>
157             <artifactId>hibernate-entitymanagerartifactId>
158             <version>${hibernate.version}version>
159         dependency>
160 
161         
162         <dependency>
163             <groupId>mysqlgroupId>
164             <artifactId>mysql-connector-javaartifactId>
165             <version>${mysql.version}version>
166         dependency>
167         
168         <dependency>
169             <groupId>com.alibabagroupId>
170             <artifactId>druidartifactId>
171             <version>${druid.version}version>
172         dependency>
173 
174     dependencies>
175 
176     <build>
177         <finalName>ssh_templatefinalName>
178 
179         <plugins>
180             
181             <plugin>
182                 <groupId>org.apache.tomcat.mavengroupId>
183                 <artifactId>tomcat7-maven-pluginartifactId>
184                 <version>2.2version>
185                 <configuration>
186                     <uriEncoding>UTF-8uriEncoding>
187                 configuration>
188             plugin>
189             
190             <plugin>
191                 <groupId>org.apache.maven.pluginsgroupId>
192                 <artifactId>maven-surefire-pluginartifactId>
193                 <version>2.12.4version>
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     
16     
17     <context:property-placeholder location="classpath:properties/db.properties"/>
18 
19     
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     
34     <bean id="entityManagerFactory"
35           class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
36         <property name="dataSource" ref="dataSource" />
37         
38         <property name="packagesToScan" value="com.cenobitor.pojo" />
39         
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     
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.jspwelcome-file>
 9     welcome-file-list>
10 
11     
12     <context-param>
13         <param-name>contextConfigLocationparam-name>
14         <param-value>classpath:spring/applicationContext.xmlparam-value>
15     context-param>
16 
17     <listener>
18         <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
19     listener>
20 
21     
22     <filter>
23         <filter-name>encodingfilter-name>
24         <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
25         
26         <init-param>
27             <param-name>encodingparam-name>
28             <param-value>UTF-8param-value>
29         init-param>
30     filter>
31     <filter-mapping>
32         <filter-name>encodingfilter-name>
33         <url-pattern>/*url-pattern>
34     filter-mapping>
35 
36 
37 
38     
39     <servlet>
40         <servlet-name>springmvcservlet-name>
41         <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
42         
43         
44         <init-param>
45             <param-name>contextConfigLocationparam-name>
46             <param-value>classpath:spring/springmvc.xmlparam-value>
47         init-param>
48     servlet>
49     <servlet-mapping>
50         <servlet-name>springmvcservlet-name>
51         <url-pattern>*.actionurl-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     
11     <context:component-scan base-package="com.cenobitor.controller"/>
12 
13     
14     <mvc:annotation-driven/>
15 
16     
29 
30     
31     
32     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
33         
34         <property name="maxUploadSize" value="8388608" />
35     bean>
36 
37     
38     
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、设置文件存储的虚拟路径

Spring+SpringMVC+SpringDataJpa整合_第1张图片

2、创建上传页面

 1 
 2 
 3 
 4     
 5     上传图片
 6 
 7 
 8     
9 10
11 12
13 14

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 {
7 
8 }

6、项目的目录结构

Spring+SpringMVC+SpringDataJpa整合_第2张图片

转载于:https://www.cnblogs.com/gdwkong/p/8977076.html

你可能感兴趣的:(java,数据库,web.xml)