Springboot常见业务逻辑代码汇总


Springboot常见业务逻辑代码汇总

目录

  1. Controller的转发和重定向
  2. Input标签上传多个图片到服务器
  3. 前端页面文件下载
  4. 本地磁盘读写
  5. 第三方支付
  6. 发送邮件
  7. Excel操作

参考:

Controller的转发和重定向

转发

使用request也行。

@RequestMapping("/helloForward")
publicString helloForward(@RequestParam(value="name", required=false, defaultValue="World2017") String name, Model model) {
        model.addAttribute("name", name);
        return"hello";
    }

重定向

在Action的返回值里使用redirect:/path方式进行重定向。

重定向过程中,有以下两种方式保存参数值。

(1)RedirectAttributes类

/** * 使用RedirectAttributes类

    * @param name

    * @param redirectAttributes

    * @return*/    @RequestMapping("/helloRedirect")

    publicString helloRedirect(@RequestParam(value="name", required=false ) String name, RedirectAttributes redirectAttributes) {

        redirectAttributes.addFlashAttribute("name", name);

        return"redirect:/hello";

    }

(2)借助Session传值

    /**    * 常规做法,重定向之前把参数放进Session中,在重定向之后的controller中把参数从Session中取出并放进ModelAndView

    * @param name

    * @param request

    * @return*/   

    @RequestMapping("/helloRedirect2")

    publicString helloRedirect2(@RequestParam(value="name", required=false ) String name, HttpServletRequest request) {

        request.getSession().setAttribute("name", name);

        return"redirect:/hello2";

    }

@RequestMapping("/hello2")

    public String hello2(Model model,HttpServletRequest request) {

        HttpSession session = request.getSession();

        model.addAttribute("name",session.getAttribute("name"));

        return"hello";     

    }

Input标签文件上传

(1)前端页面

<form action="getData" style="font-size: 14px;" method="post"  ENCTYPE="multipart/form-data">
    <td><input type="file" name="file" multiple="multiple"></td>
</form>

(2)服务器端

public void getData(@RequestParam(value = "file", required = false) List<MultipartFile> file, HttpServletRequest req) {
  try {
    for (MultipartFile f : file) {
        //....
    }
  }
}

文件大小限制带来的问题

Spring Boot做文件上传时出现了**The field file exceeds its maximum permitted size of 1048576 bytes.**错误,显示文件的大小超出了允许的范围。

文档说明表示,每个文件的配置最大为1Mb,单次请求的文件的总数不能大于10Mb。

要更改这个默认值需要在配置文件(如application.properties)中加入两个配置。

Spring Boot1.4版本后配置更改为:

spring.http.multipart.maxFileSize = 10Mb 
spring.http.multipart.maxRequestSize=100Mb 

Spring Boot2.0之后的版本配置修改为:

spring.servlet.multipart.max-file-size = 10MB
spring.servlet.multipart.max-request-size=100MB

前端页面文件下载

@RequestMapping(value = "downloadZip", method = RequestMethod.GET)
    public void downloadZip(HttpServletResponse response,String id) throws Exception {
        String fileName=workCardPhotoFileService.downloadZipFile(id); //获取文件名
        if (StringUtils.isNotEmpty(fileName)){
            response.setContentType("application/application/vnd.ms-excel");
            response.setHeader("Content-disposition",
                    "attachment;filename=" + fileName);
            download(response.getOutputStream(),fileName);
        }
    }

public void download(OutputStream os, String fileName) throws IOException {
        //获取服务器文件
        File file = new File("/Users/Desktop/download/workcardphoto/"+fileName);
        InputStream ins = new FileInputStream(file);
        byte[] b = new byte[1024];
        int len;
        while((len = ins.read(b)) > 0){
            os.write(b,0,len);
        }
        os.flush();
        os.close();
        ins.close();
    }

本地磁盘读写

  • 依赖

    <dependency>
    			<groupId>commons-io</groupId>
    			<artifactId>commons-io</artifactId>
    			<version>2.6</version>
    </dependency>
  • 工具类

    package com.jason.file;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.List;
    
    import org.apache.commons.io.FileUtils;
    
    public class MyFileUtils {
         /**
          * 修改文件内容:字符串逐行替换
          *
          * @param file:待处理的文件
          * @param oldstr:需要替换的旧字符串
          * @param newStr:用于替换的新字符串
          */
         public static boolean modifyFileContent(File file, String oldstr, String newStr) {
             List<String> list = null;
             try {
                 list = FileUtils.readLines(file, "UTF-8");
                 for (int i = 0; i < list.size(); i++) {
                     String temp = list.get(i).replaceAll(oldstr, newStr);
                     list.remove(i);
                     list.add(i, temp);
                 }
                 FileUtils.writeLines(file, "UTF-8", list, false);
             } catch (IOException e) {
                 e.printStackTrace();
             }
     
             return true;
         }
     
         public static boolean modifyFileContent(String filePath, String oldstr, String newStr) {
             return modifyFileContent(new File(filePath), oldstr, newStr);
         }
         
         public static void getFileList(String dirPath, String oldstr, String newStr) {
             File dir = new File(dirPath);
             File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
             if (files != null) {
                 for (int i = 0; i < files.length; i++) {
                     if (files[i].isDirectory()) { // 判断是文件还是文件夹
                         getFileList(files[i].getAbsolutePath(), oldstr, newStr); // 获取文件夹绝对路径
                     } else {
                         String strFileName = files[i].getAbsolutePath();// 获取文件绝对路径
                         System.out.println(strFileName);
                         MyFileUtils.modifyFileContent(strFileName, oldstr, newStr);
                     }
                 }
    
             }
         }
         /**
          * 判断文件夹是否存在
          *   存在,无操作
          *   不存在,创建
          * @param path
          */
         private static void isExist(String path) {
     		File folder = new File(path);
     		if (!folder.exists() && !folder.isDirectory()) {
     			folder.mkdirs();
     		}
     	}
         
         public static void main(String[] args) {
        	 MyFileUtils.getFileList("", "", "");
    	}
     
     }

第三方支付

使用IJPay,已经给了Springboot的Demo,直接使用即可

  • 依赖

    <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.6.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.ijpay.demo</groupId>
        <artifactId>IJPay-Demo-SpringBoot</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>${project.artifactId}</name>
        <description>IJPay Demo for Spring Boot</description>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
    
            <ijapy.version>2.7.9</ijapy.version>
            <enjoy.version>4.3</enjoy.version>
            <fastjson.version>1.2.75</fastjson.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <optional>true</optional>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <scope>provided</scope>
            </dependency>
    
            <dependency>
                <groupId>com.github.javen205</groupId>
                <artifactId>IJPay-WxPay</artifactId>
                <version>${ijapy.version}</version>
            </dependency>
    
            <dependency>
                <groupId>com.github.javen205</groupId>
                <artifactId>IJPay-AliPay</artifactId>
                <version>${ijapy.version}</version>
            </dependency>
    
            <dependency>
                <groupId>com.github.javen205</groupId>
                <artifactId>IJPay-QQ</artifactId>
                <version>${ijapy.version}</version>
            </dependency>
    
            <dependency>
                <groupId>com.github.javen205</groupId>
                <artifactId>IJPay-UnionPay</artifactId>
                <version>${ijapy.version}</version>
            </dependency>
    
            <dependency>
                <groupId>com.github.javen205</groupId>
                <artifactId>IJPay-JDPay</artifactId>
                <version>${ijapy.version}</version>
            </dependency>
    
            <dependency>
                <groupId>com.github.javen205</groupId>
                <artifactId>IJPay-PayPal</artifactId>
                <version>${ijapy.version}</version>
            </dependency>
    
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>${fastjson.version}</version>
            </dependency>
    
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-lang3</artifactId>
                <version>3.9</version>
            </dependency>
    
            <dependency>
                <groupId>com.jfinal</groupId>
                <artifactId>enjoy</artifactId>
                <version>${enjoy.version}</version>
            </dependency>
        </dependencies>
    
        <build>
            <resources>
                <resource>
                    <directory>src/main/resources</directory>
                </resource>
                <resource>
                    <directory>src/main/resources/${profiles.active}</directory>
                </resource>
            </resources>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <configuration>
                        <fork>true</fork>
                    </configuration>
                </plugin>
            </plugins>
        </build>
        <profiles>
            <!-- 默认激活 dev 开发环境 -->
            <!-- production使用 mvn xxx -Pproduction -->
            <profile>
                <!-- 本地开发环境 -->
                <id>development</id>
                <properties>
                    <profiles.active>dev</profiles.active>
                </properties>
                <activation>
                    <activeByDefault>true</activeByDefault>
                </activation>
            </profile>
            <profile>
                <!-- 生产环境 -->
                <id>production</id>
                <properties>
                    <profiles.active>production</profiles.active>
                </properties>
            </profile>
        </profiles>
  • 配置文件

    默认使用 resources/dev 下的配置,如果没有请复制 resources/production 并修改为 dev 如果不使用对环境配置可以直接删除直接将配置文件放在 resources 根目录中,并删除 pom.xml 中的 profiles 以及 resources

    修改 dev 下不同支付方式的属性文件。

    1. 属性文件配置详细介绍请参考 IJPay 文档
    2. 属性文件乱码解决方案 IDE中显示 *.properties 为中文

    例如支付宝的参数:

    • appId: 应用编号
    • privateKey: 应用私钥
    • publicKey: 支付宝公钥,通过应用公钥上传到支付宝开放平台换取支付宝公钥(如果是证书模式,公钥与私钥在CSR目录)。
    • appCertPath: 应用公钥证书 (证书模式必须)
    • aliPayCertPath: 支付宝公钥证书 (证书模式必须)
    • aliPayRootCertPath: 支付宝根证书 (证书模式必须)
    • serverUrl: 支付宝支付网关
    • domain: 外网访问项目的域名,支付通知中会使用
  • 接口

    controller包里面,每种支付方式对应一个包,这里拿支付宝举例,在com.ijpay.demo.controller.alipay.AliPayController里有很多接口,其中PC端接口:

    /**
         * PC支付
         */
        @RequestMapping(value = "/pcPay")
        @ResponseBody
        public void pcPay(HttpServletResponse response) {
            try {
                String totalAmount = "88.88";
                String outTradeNo = StringUtils.getOutTradeNo();
                log.info("pc outTradeNo>" + outTradeNo);
    
                String returnUrl = aliPayBean.getDomain() + RETURN_URL;
                String notifyUrl = aliPayBean.getDomain() + NOTIFY_URL;
                AlipayTradePagePayModel model = new AlipayTradePagePayModel();
    
                model.setOutTradeNo(outTradeNo);
                model.setProductCode("FAST_INSTANT_TRADE_PAY");
                model.setTotalAmount(totalAmount);
                model.setSubject("Javen PC支付测试");
                model.setBody("Javen IJPay PC支付测试");
                model.setPassbackParams("passback_params");
                /**
                 * 花呗分期相关的设置,测试环境不支持花呗分期的测试
                 * hb_fq_num代表花呗分期数,仅支持传入3、6、12,其他期数暂不支持,传入会报错;
                 * hb_fq_seller_percent代表卖家承担收费比例,商家承担手续费传入100,用户承担手续费传入0,仅支持传入100、0两种,其他比例暂不支持,传入会报错。
                 */
    //            ExtendParams extendParams = new ExtendParams();
    //            extendParams.setHbFqNum("3");
    //            extendParams.setHbFqSellerPercent("0");
    //            model.setExtendParams(extendParams);
    
                AliPayApi.tradePage(response, model, notifyUrl, returnUrl);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    
        @RequestMapping(value = "/tradePay")
        @ResponseBody
        public String tradePay(@RequestParam("authCode") String authCode, @RequestParam("scene") String scene) {
            String subject = null;
            String waveCode = "wave_code";
            String barCode = "bar_code";
            if (scene.equals(waveCode)) {
                subject = "Javen 支付宝声波支付测试";
            } else if (scene.equals(barCode)) {
                subject = "Javen 支付宝条形码支付测试";
            }
            String totalAmount = "100";
            String notifyUrl = aliPayBean.getDomain() + NOTIFY_URL;
    
            AlipayTradePayModel model = new AlipayTradePayModel();
            model.setAuthCode(authCode);
            model.setSubject(subject);
            model.setTotalAmount(totalAmount);
            model.setOutTradeNo(StringUtils.getOutTradeNo());
            model.setScene(scene);
            try {
                return AliPayApi.tradePayToResponse(model, notifyUrl).getBody();
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return null;
        }

    访问后如下:

    image-20220331155149205

发送邮件

使用Hutool工具包

  • 依赖

    <!--邮件依赖 -->
    		<dependency>
    			<groupId>javax.mail</groupId>
    			<artifactId>mail</artifactId>
    			<version>1.4.7</version>
    		</dependency>
    		<!--工具包 -->
    		<dependency>
    			<groupId>cn.hutool</groupId>
    			<artifactId>hutool-all</artifactId>
    			<version>5.7.22</version>
    		</dependency>
  • 配置类

    @Configuration
    public class AccountConfig {
    
    	@Bean
    	public MailAccount mailAccount() {
    		MailAccount account = new MailAccount();
    		account.setHost("smtp.163.com");
    //		account.setPort(25);
    		account.setAuth(true);
    		account.setFrom("xiaoqianittest@163.com");
    //		account.setUser("xiaoqianittest");
    		account.setPass("------"); //这里添入邮件的授权码
    		return account;
    	}
    }
  • 接口

    @RestController
    public class HutoolEmail {
    	
    	@Autowired
    	private MailAccount mailAccount;
    
    	/**
    	 * MailUtil.send参数:
    	 *  tos: 对方的邮箱地址,可以是单个,也可以是多个(Collection表示)
    		subject:标题
    		content:邮件正文,可以是文本,也可以是HTML内容
    		isHtml: 是否为HTML,如果是,那参数3识别为HTML内容
    		files: 可选:附件,可以为多个或没有,将File对象加在最后一个可变参数中即可
    	 * @return
    	 */
    	@RequestMapping("/hutoolemail")
    	public String hutoolemail(String toEmail, String subject, String content) {
    		try {
    			MailUtil.send(mailAccount, toEmail, subject, content, false);
    			return "Success";
    		} catch (Exception e) {
    			// TODO: handle exception
    			e.printStackTrace();
    			return "Fail";
    		}
    	}
    }

Springboot集成mail

  • 依赖

    <!-- spring 集成发送邮件 -->
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-mail</artifactId>
    		</dependency>
  • 配置文件

    spring:
       mail:
           host: smtp.163.com
           username: xiaoqianittest@163.com
           password: ---- #授权码
           enable:  true
           smtp:
             auth: true
             starttls:
              enable: true
              required: true
  • 接口

    @RestController
    public class SpringEmail {
    	
    	@Value("${spring.mail.username}")
    	private String sender;
    	@Autowired
    	private JavaMailSender javaMailSender;
    
    	@RequestMapping("/springemail")
    	public String springemail(String toEmail, String subject, String content) {
    		SimpleMailMessage message = new SimpleMailMessage();
    		message.setFrom(sender);
    		message.setTo(toEmail);
    		message.setSubject(subject);
    		message.setText(content);
    		try {
    			javaMailSender.send(message);
    			return "Success";
    		} catch (Exception e) {
    			// TODO: handle exception
    			e.printStackTrace();
    			return "Failed";
    		}
    	}
    }

Excel操作

  • 依赖

    注意这里poi-ooxml的版本如果比较高,相应的commons-io的版本也需要高版本,不然会出现ClassNotFound错误。

    <?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    	<parent>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-parent</artifactId>
    		<version>2.6.4</version>
    		<relativePath /> <!-- lookup parent from repository -->
    	</parent>
    	<groupId>com.jason</groupId>
    	<artifactId>CommonBusiness</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<name>CommonBusiness</name>
    	<description>Springboot常见业务逻辑代码,支付、邮件等</description>
    	<properties>
    		<java.version>1.8</java.version>
    		<alipay.version>4.9.153.ALL</alipay.version>
    	</properties>
    	<dependencies>
    		<!-- Web -->
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-web</artifactId>
    		</dependency>
    		<!-- test -->
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-test</artifactId>
    			<scope>test</scope>
    		</dependency>
    		<!--Lombok -->
    		<dependency>
    			<groupId>org.projectlombok</groupId>
    			<artifactId>lombok</artifactId>
    			<version>1.18.6</version>
    		</dependency>
    		<dependency>
    			<groupId>net.logstash.logback</groupId>
    			<artifactId>logstash-logback-encoder</artifactId>
    			<version>4.9</version>
    		</dependency>
    		<!--工具包 -->
    		<dependency>
    			<groupId>cn.hutool</groupId>
    			<artifactId>hutool-all</artifactId>
    			<version>5.7.22</version>
    		</dependency>
    		<!-- 用来File操作的工具包 -->
    		<dependency>
    			<groupId>commons-io</groupId>
    			<artifactId>commons-io</artifactId>
    			<!-- <version>2.6</version> -->
    			<version>2.11.0</version>
    		</dependency>
    		<!-- Excel操作工具包 -->
    		<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
    		<dependency>
    			<groupId>org.apache.poi</groupId>
    			<artifactId>poi-ooxml</artifactId>
    			<version>5.2.2</version>
    		</dependency>
    
    	</dependencies>
    	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-maven-plugin</artifactId>
    			</plugin>
    		</plugins>
    	</build>
    
    </project>
  • Bean

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Excel {
    
    	private String name;
    	private int age;
    	private double score;
    	private boolean isPass;
    	private Date examDate;
    }
  • 接口

    @Controller
    public class TestApi {
    
    	/**
    	 * 输出到本地
    	 * 
    	 * @return
    	 */
    	@RequestMapping("/excel1")
    	@ResponseBody
    	public String excel1() {
    		List<Excel> list = init();
    		/*
    		 * 这里可以获取到target/classes/文件目录,但是我这里有中文,没办法解析 String path =
    		 * this.getClass().getResource("/").getPath(); String filepath = path +
    		 * "../../excel/test.xlsx";
    		 */
    		// 通过工具类创建writer
    		ExcelWriter writer = ExcelUtil
    				.getWriter("/.../excel/test.xlsx");
    		// 合并单元格后的标题行,使用默认标题样式
    		writer.merge(4, "一班成绩单");
    		// 一次性写出内容,使用默认样式,强制输出标题
    		writer.write(list, true);
    		// 关闭writer,释放内存
    		writer.close();
    		return "success";
    	}
    
    	/**
    	 * 输出到浏览器
    	 * 
    	 * @param response
    	 * @throws IOException
    	 */
    	@RequestMapping("/excel2")
    	public void excel2(HttpServletResponse response) throws IOException {
    		List<Excel> rows = init();
    		ExcelWriter writer = ExcelUtil.getWriter(true);
    		writer.write(rows, true);
    		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
    		response.setHeader("Content-Disposition", "attachment;filename=test.xlsx");
    		ServletOutputStream out = response.getOutputStream();
    		writer.flush(out, true);
    		writer.close();
    		IoUtil.close(out);
    	}
    
    	private List<Excel> init() {
    		Excel bean1 = new Excel();
    		bean1.setName("张三");
    		bean1.setAge(22);
    		bean1.setPass(true);
    		bean1.setScore(66.30);
    		bean1.setExamDate(DateUtil.date());
    
    		Excel bean2 = new Excel();
    		bean2.setName("李四");
    		bean2.setAge(28);
    		bean2.setPass(false);
    		bean2.setScore(38.50);
    		bean2.setExamDate(DateUtil.date());
    
    		List<Excel> rows = CollUtil.newArrayList(bean1, bean2);
    		return rows;
    	}
    }

文章作者: 小小千千
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 小小千千 !
评论
  目录