• SpringBoot学习笔记5-整合Email-文件上传-Neo4J-打包为war包


    二十九 SpringBoot整合Email

    以下演示的是简单邮件发送

    29.1 加入相关依赖   

     1           <dependency>
     2           <groupId>org.springframework.boot</groupId>
     3           <artifactId>spring-boot-starter-web</artifactId>  
     4        </dependency>
     5        
     6        <!-- Email依赖 -->
     7        <dependency>
     8                <groupId>org.springframework.boot</groupId>
     9                <artifactId>spring-boot-starter-mail</artifactId>
    10        </dependency>
    11        
    12        <!-- freemarker的依赖 -->
    13        <dependency>
    14                <groupId>org.springframework.boot</groupId>
    15                <artifactId>spring-boot-starter-freemarker</artifactId>
    16        </dependency>    
    相关依赖

    29.2 在全局配置文件中配置相关属性

    1 spring.mail.host=smtp.qq.com
    2 spring.mail.username=your@qq.com
    3 #授权码
    4 spring.mail.password=
    5 spring.mail.properties.mail.smtp.auth=true
    6 spring.mail.properties.mail.smtp.starttls.enable=true
    7 spring.mail.properties.mail.smtp.starttls.required=true
    application.properties

    29.3 service层

     1 package com.wu.service;
     2 
     3 import java.io.File;
     4 
     5 public interface EmailService {
     6     //发送简单的邮件
     7     public void sendSimpleEmailService(String sendTo,String title,String content);
     8     
     9     //发送带有附件的邮件
    10     public void sendAttachmentMail(String sendTo,String title,String content,File file);
    11     
    12     //发送模板邮件
    13     public void sendTemplateEmailService(String sendTo,String title,String content);
    14 }
    EmailService.java
     1 package com.wu.service;
     2 
     3 import java.io.File;
     4 import java.util.HashMap;
     5 import java.util.Map;
     6 
     7 import javax.mail.MessagingException;
     8 import javax.mail.internet.MimeMessage;
     9 
    10 import org.springframework.beans.factory.annotation.Autowired;
    11 import org.springframework.beans.factory.annotation.Value;
    12 import org.springframework.core.io.FileSystemResource;
    13 import org.springframework.mail.SimpleMailMessage;
    14 import org.springframework.mail.javamail.JavaMailSender;
    15 import org.springframework.mail.javamail.MimeMessageHelper;
    16 import org.springframework.stereotype.Service;
    17 import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
    18 import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
    19 import freemarker.template.Template;
    20 
    21 @Service
    22 public class EmailServiceImp implements EmailService {
    23     @Autowired
    24     private JavaMailSender sender;
    25     
    26     @Autowired
    27     private FreeMarkerConfigurer fc;
    28     
    29     @Value("${spring.mail.username}")
    30     private String sendFrom;
    31     
    32     @Override
    33     public void sendSimpleEmailService(String sendTo, String title, String content) {
    34         SimpleMailMessage message=new SimpleMailMessage();
    35         message.setFrom(sendFrom);
    36         message.setTo(sendTo);
    37         message.setSubject(title);
    38         message.setText(content);
    39         sender.send(message);
    40     }
    41 
    42     @Override
    43     public void sendAttachmentMail(String sendTo, String title, String content, File file) {
    44         MimeMessage message=sender.createMimeMessage();
    45         try {
    46             MimeMessageHelper helper=new MimeMessageHelper(message,true);//true为设置为multipart模式
    47             helper.setFrom(sendFrom);
    48             helper.setTo(sendTo);
    49             helper.setSubject(title);
    50             helper.setText(content);
    51             FileSystemResource fsResource=new FileSystemResource(file);
    52             helper.addAttachment("这是一个附件",fsResource);
    53             sender.send(message);
    54         } catch (MessagingException e) {
    55             e.printStackTrace();
    56         }
    57     }
    58 
    59     @Override
    60     public void sendTemplateEmailService(String sendTo, String title, String content){
    61         MimeMessage message=sender.createMimeMessage();
    62         try {
    63             MimeMessageHelper helper=new MimeMessageHelper(message,true);
    64             helper.setTo(sendTo);
    65             helper.setFrom(sendFrom);
    66             helper.setSubject(title);
    67             
    68             //封装模板数据
    69             Map<String,Object> map=new HashMap<>();
    70             map.put("username","工具人");
    71             
    72             
    73             //得到模板并将数据加入到模板中
    74             Template template = fc.getConfiguration().getTemplate(content);
    75             String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
    76             
    77             //封装邮件模板
    78             helper.setText(html);
    79             
    80             //发送邮件
    81             sender.send(message);
    82         } catch (Exception e) {
    83             e.printStackTrace();
    84         }
    85     }
    86     
    87 }
    EmailServiceImp.java

    29.4 controller层

     1 package com.wu.controller;
     2 
     3 import java.io.File;
     4 
     5 import org.springframework.beans.factory.annotation.Autowired;
     6 import org.springframework.web.bind.annotation.RequestMapping;
     7 import org.springframework.web.bind.annotation.RestController;
     8 import com.wu.service.EmailService;
     9 
    10 @RestController
    11 public class EmailController {
    12     @Autowired
    13     private EmailService service;
    14      
    15     //发送简单邮件
    16     @RequestMapping("/sendSimpleEmail")
    17     public String sendSimpleEmail(){
    18         service.sendSimpleEmailService("toSend@gmail.com","这是一个测试","请忽略!");
    19         return "success";
    20     }
    21     
    22     //发送带有附件的邮件
    23     @RequestMapping("/sendAttachmentEmail")
    24     public String sendAttachmentEmail(){
    25         File file=new File("src/main/resources/static/test.txt");
    26         service.sendAttachmentMail("toSend@gmail.com","这也是一个测试","请忽略",file);
    27         return "success again";
    28     }
    29     
    30     //发送模板邮件
    31     @RequestMapping("/sendTemplateEmailService")
    32     public String sendTemplateEmailService(){
    33         service.sendTemplateEmailService("toSend@gmail.com","这是模板邮件","info.html");
    34         return "success again again";
    35     }
    36 }
    EmailController.java 

    三十 SpringBoot实现文件上传

     30.1 相关依赖

     1           <dependency>
     2           <groupId>org.springframework.boot</groupId>
     3           <artifactId>spring-boot-starter-web</artifactId>  
     4        </dependency>
     5        
     6        <!-- Thymeleaf模板 -->
     7        <dependency>
     8           <groupId>org.springframework.boot</groupId>
     9           <artifactId>spring-boot-starter-thymeleaf</artifactId>  
    10        </dependency>         
    依赖

    30.2  相关配置

    1 #单个文件大小
    2 multipart.maxFileSize=50Mb
    3 #接收的所有文件大小
    4 multipart.maxRequestSize=500Mb
    application.properties

    30.3 Thymeleaf上传文件

     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4 <meta charset="UTF-8"/>
     5 <title>上传文件</title>
     6 </head>
     7 <body>
     8 <p>单个文件上传</p>
     9 <form action="/upload" enctype="multipart/form-data" method="post">
    10     <input type="file" name="file"/><br></br>
    11     <input type="submit" value="提交"/>
    12 </form>
    13 <hr></hr>
    14 <p>批量文件上传</p>
    15 <form action="/uploads" enctype="multipart/form-data" method="post">
    16     <input type="file" name="file"/><br></br>
    17     <input type="file" name="file"/><br></br>
    18     <input type="file" name="file"/><br></br>
    19     <input type="submit" value="提交"/>
    20 </form>
    21 </body>
    22 </html>
    upload.html

    30.4 controller层

     1 package com.wu.controller;
     2 
     3 import java.io.File;
     4 import java.util.UUID;
     5 import javax.servlet.http.HttpServletRequest;
     6 import org.springframework.stereotype.Controller;
     7 import org.springframework.web.bind.annotation.RequestMapping;
     8 import org.springframework.web.bind.annotation.ResponseBody;
     9 import org.springframework.web.multipart.MultipartFile;
    10 
    11 @Controller
    12 public class UploadController {
    13     @RequestMapping("/index")
    14     public String upload(){
    15         return "upload";
    16     }
    17     
    18     @ResponseBody
    19     @RequestMapping("/upload")
    20     public String uploadFile(MultipartFile file,HttpServletRequest request){
    21         //路径
    22         String dir = request.getServletContext().getRealPath("/upload");
    23         File fileDir=new File(dir);
    24         if(!fileDir.exists()){
    25             fileDir.mkdir();
    26         }
    27         //文件名
    28         String suffex = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
    29         String fileName=UUID.randomUUID().toString()+suffex;
    30         File file2=new File(fileDir+fileName);
    31         try {
    32             file.transferTo(file2);
    33         } catch (Exception e) {
    34             e.printStackTrace();
    35             return "上传失败";
    36         } 
    37         return "上传成功";
    38     }
    39     
    40     @ResponseBody
    41     @RequestMapping("/uploads")
    42     public String uploadFiles(MultipartFile file[],HttpServletRequest request){
    43         //路径
    44         String dir = request.getServletContext().getRealPath("/upload");
    45         File fileDir=new File(dir);
    46         if(!fileDir.exists()){
    47             fileDir.mkdir();
    48         }
    49         //文件名
    50         for(int i=0;i<file.length;i++){
    51             String suffex = file[i].getOriginalFilename().substring(file[i].getOriginalFilename().lastIndexOf("."));
    52             String fileName=UUID.randomUUID().toString()+suffex;
    53             File file2=new File(fileDir+fileName);
    54             try {
    55                 file[i].transferTo(file2);
    56             } catch (Exception e) {
    57                 e.printStackTrace();
    58                 return "上传失败";
    59             } 
    60         }
    61     
    62         return "上传成功";
    63     }
    64 }
    UploadController.java

    30.5 结果显示

     三十一 Neo4J的介绍与安装

     31.0 简单介绍

    Neo4j是一个高性能的,NOSQL图形数据库,它将结构化数据存储在网络上而不是表中。它是一个嵌入式的、基于磁盘的、具备完全的事务特性的Java持久化引擎,但是它将结构化数据存储在网络(从数学角度叫做图)上而不是表中。Neo4j也可以被看作是一个高性能的图引擎,该引擎具有成熟数据库的所有特性。程序员工作在一个面向对象的、灵活的网络结构下而不是严格、静态的表中——但是他们可以享受到具备完全的事务特性、企业级的数据库的所有好处。(Neo4j的百度百科)

    具体可以参考: Neo4j教程

    31.1 windows下的安装

    可以自行下载较新版本哈,百度云下载:neo4j-community-3.5.5   提取码:yu3u

    31.2 启动运行

    1)在  neo4j-community-3.5.5conf  目录下修改neo4j.conf  文件,把 #dbms.connectors.default_listen_address=0.0.0.0 的 #  去掉,并保存文件

    2)通过dos命令 如:D:>cd BaiduNetdiskDownload eo4j-community-3.5.5in  在该目录下执行 neo4j.bat console 即可启动

    3)若显示 “powershell”不是内部或外部命令,也不是可运行的程序或批处理文件  则在系统环境变量的 Path 中加 C:WindowsSystem32WindowsPowerShellv1.0  若还是不行,重启电脑

    31.3 显示

    在浏览器中输入启动成功后给出的地址 http://localhost:7474/browser/   登录密码为neo4j,之后更改密码,最终界面如下:

    三十二 SpringBoot整合Neo4j

    32.1 添加相关依赖

     1            <dependency>
     2           <groupId>org.springframework.boot</groupId>
     3           <artifactId>spring-boot-starter-web</artifactId>  
     4        </dependency>
     5        
     6        <!-- SpringBoot整合Neo4j的依赖 -->
     7        <dependency>
     8                <groupId>org.springframework.boot</groupId>
     9                <artifactId>spring-boot-starter-data-neo4j</artifactId>
    10        </dependency>
    依赖

    32.2 application.properties中的相关配置

    1 spring.data.neo4j.uri=http://localhost:7474
    2 spring.data.neo4j.username=neo4j
    3 spring.data.neo4j.password=
    Neo4j的相关配置

    32.3 编写实体类(包括节点和关系)

     1 package com.wu.pojo;
     2 
     3 import org.neo4j.ogm.annotation.GraphId;
     4 import org.neo4j.ogm.annotation.NodeEntity;
     5 import org.neo4j.ogm.annotation.Property;
     6 
     7 @NodeEntity(label="User")//将该节点加入到数据库中
     8 public class UserNode {
     9     @GraphId//图形id
    10     private Long NodeId;
    11     
    12     @Property
    13     private Long userId;
    14     @Property
    15     private String name;
    16     @Property
    17     private Integer age;
    18     public Long getNodeId() {
    19         return NodeId;
    20     }
    21     public void setNodeId(Long nodeId) {
    22         NodeId = nodeId;
    23     }
    24     public Long getUserId() {
    25         return userId;
    26     }
    27     public void setUserId(Long userId) {
    28         this.userId = userId;
    29     }
    30     public String getName() {
    31         return name;
    32     }
    33     public void setName(String name) {
    34         this.name = name;
    35     }
    36     public Integer getAge() {
    37         return age;
    38     }
    39     public void setAge(Integer age) {
    40         this.age = age;
    41     }
    42     
    43 }
    UserNode.java
     1 package com.wu.pojo;
     2 
     3 import org.neo4j.ogm.annotation.EndNode;
     4 import org.neo4j.ogm.annotation.GraphId;
     5 import org.neo4j.ogm.annotation.RelationshipEntity;
     6 import org.neo4j.ogm.annotation.StartNode;
     7 @RelationshipEntity(type="UserRelation")//将该关系加入到数据库中
     8 public class UserRelation {
     9     @GraphId//
    10     private Long RelationId;
    11     
    12     @StartNode
    13     private UserNode startUser;
    14     
    15     @EndNode
    16     private UserNode endUser;
    17 
    18     public Long getRelationId() {
    19         return RelationId;
    20     }
    21 
    22     public void setRelationId(Long relationId) {
    23         RelationId = relationId;
    24     }
    25 
    26     public UserNode getStartUser() {
    27         return startUser;
    28     }
    29 
    30     public void setStartUser(UserNode startUser) {
    31         this.startUser = startUser;
    32     }
    33 
    34     public UserNode getEndUser() {
    35         return endUser;
    36     }
    37 
    38     public void setEndUser(UserNode endUser) {
    39         this.endUser = endUser;
    40     }
    41     
    42 }
    UserRelation.java

    32.4 编写dao层(映射)

     1 package com.wu.dao;
     2 
     3 import java.util.List;
     4 
     5 import org.springframework.data.neo4j.annotation.Query;
     6 import org.springframework.data.neo4j.repository.GraphRepository;
     7 import org.springframework.data.repository.query.Param;
     8 import org.springframework.stereotype.Component;
     9 
    10 import com.wu.pojo.UserNode;
    11 @Component//注入Spring
    12 public interface UserRepository extends GraphRepository<UserNode>{
    13     //根据用户节点查询
    14     @Query("match (n:User) return n")
    15     List<UserNode> getUserNodeList();
    16     
    17     //添加用户节点
    18     @Query("create (n:User{age:{age},name:{name}}) return n")
    19     List<UserNode> addUserNodeList(@Param("name") String name,@Param("age") int age);
    20     
    21 }
    UserRepository.java
     1 package com.wu.dao;
     2 
     3 import java.util.List;
     4 
     5 import org.springframework.data.neo4j.annotation.Query;
     6 import org.springframework.data.neo4j.repository.GraphRepository;
     7 import org.springframework.data.repository.query.Param;
     8 import org.springframework.stereotype.Component;
     9 
    10 import com.wu.pojo.UserRelation;
    11 @Component
    12 public interface UserRelationRepository extends GraphRepository<UserRelation> {
    13     //根据用户id查询对应关系
    14      @Query("match p=(n:User)<-[r:UserRelation]->(n1:User) where n.userId={firstUserId} and n1.userId={secondUserId} return p")
    15      List<UserRelation> findUserRelationByEachId(@Param("firstUserId") String firstUserId,@Param("secondUserId") String secondUserId);
    16      
    17      //创建关系
    18      @Query("match (fu:User),(su:User) where fu.userId={firstUserId} and su.userId={secondUserId} create p=(fu)-[r:UserRelation]->(su) return p")
    19      List<UserRelation> addUserRelation(@Param("firstUserId") Long firstUserId,@Param("secondUserId") Long secondUserId);
    20      
    21 }
    UserRelationRepository.java

    32.5 编写service层

     1 package com.wu.service;
     2 
     3 import java.util.List;
     4 import org.springframework.beans.factory.annotation.Autowired;
     5 import org.springframework.stereotype.Service;
     6 import com.wu.dao.UserRelationRepository;
     7 import com.wu.dao.UserRepository;
     8 import com.wu.pojo.UserNode;
     9 import com.wu.pojo.UserRelation;
    10 
    11 @Service
    12 public class UserService {
    13     @Autowired
    14     private UserRepository userRepository;
    15     @Autowired
    16     private UserRelationRepository userRelationRepository;
    17     
    18     //添加用户节点
    19     public void  addUserNode(UserNode userNode){
    20         userRepository.addUserNodeList(userNode.getName(),userNode.getAge());
    21     }
    22     
    23     //查询用户节点
    24     public List<UserNode> getUserNodeList(){
    25         return userRepository.getUserNodeList();
    26     }
    27     
    28     //添加用户关系
    29     public void addUserRelation(UserRelation userRelation){
    30         userRelationRepository.addUserRelation(userRelation.getStartUser().getUserId(), userRelation.getEndUser().getUserId());
    31     }
    32 }
    UserService.java

    32.6 编写controller层

     1 package com.wu.controller;
     2 
     3 import org.springframework.beans.factory.annotation.Autowired;
     4 import org.springframework.web.bind.annotation.RequestMapping;
     5 import org.springframework.web.bind.annotation.RestController;
     6 import com.wu.pojo.UserNode;
     7 import com.wu.service.UserService;
     8 
     9 @RestController
    10 public class UserController {
    11     @Autowired
    12     private UserService userService;
    13     
    14     @RequestMapping("/addUserNode")
    15     public String addUserNode(){
    16         UserNode userNode=new UserNode();
    17         userNode.setNodeId(1l);
    18         userNode.setUserId(1l);
    19         userNode.setAge(13);
    20         userNode.setName("用户1");
    21         userService.addUserNode(userNode);
    22         return "success";
    23     }
    24     
    25     /*@RequestMapping("/addUserRelation")
    26     public String addUserRelation(){
    27         UserRelation userRelation=new UserRelation();
    28         //查询用户为之添加关系
    29         List<UserNode> userNodeList = userService.getUserNodeList();
    30         userRelation.setRelationId(1l);
    31         userRelation.setStartUser(userNodeList.get(0));
    32         userRelation.setEndUser(userNodeList.get(1));
    33         userService.addUserRelation(userRelation);
    34         return "success";
    35     }*/
    36 }
    UserController.java

    32.7 结果

    三十三 打包为war包并发布到tomcat中

    33.1 创建maven工程时打包方式设为war

    33.2 添加以下依赖,打包时排除tomcat

     1       <dependency>
     2           <groupId>org.springframework.boot</groupId>
     3           <artifactId>spring-boot-starter-web</artifactId>
     4           <!-- 移除嵌入式tomcat插件 -->
     5           <exclusions>
     6               <exclusion>
     7                   <groupId>org.springframework.boot</groupId>
     8                   <artifactId>spring-boot-starter-tomcat</artifactId>
     9               </exclusion>
    10           </exclusions>
    11       </dependency>
    12 
    13       <dependency>
    14             <groupId>org.springframework.boot</groupId>
    15             <artifactId>spring-boot-starter-tomcat</artifactId>
    16             <scope>provided</scope>
    17        </dependency>        
    相关依赖

    33.3 启动类的设置

    启动类继承 extends SpringBootServletInitializer  重写

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
    return builder.sources(启动类.class);
    }

    33.4 输入打包命令

    右击项目-->Run As-->Maven build-->Goals:clean package  --> Run

    作者:wuba
    出处:http://www.cnblogs.com/wuba/
    版权声明:本博客所有文章除特别声明外,均采用CC BY-NC-SA 4.0许可协议。转载请注明出处!
  • 相关阅读:
    js-url打开方式
    eclipse删除所有空行
    Oracle重启 error: ora-01034:oracle not available ora-27101:shared memory realm does not exist
    最近面试遇到了高阶函数的概念混乱了
    关于跨域的cookie问题
    二叉树 呜呜
    函数的尾递归
    react context
    二叉树
    dom3级事件
  • 原文地址:https://www.cnblogs.com/wuba/p/11242656.html
Copyright © 2020-2023  润新知