利用freemarker对参数进行校验
这篇文章主要用到的技术点:
- 自定义注解的使用
- 反射机制
- SAX解析xml
- Freemarker的运用
我们在工作中经常需要上传excel文件,然后在对文件中的字段进行校验。如果文件里的字段是反复出现,或者文件的字段比较多的话,这是就会使代码变得繁琐,而且也不容易维护。
比如说像下面那张学生的表格
我们需要对上面表中的每个字段做校验
1.userName 必传字段
2. telephone 手机电话号码格式校验
3. email格式的校验
4. birthday 格式的校验
5. userId的生成规则等
有时候我们用自定义注解+反射,往往可以使代码变得清晰明了,不说了,直接上代码:
package com.example.demo.Controller;
import com.example.demo.utils.DealException;
import com.example.demo.utils.ExcelUtils;
import com.example.demo.validate.TemplateXmlUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static freemarker.template.Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS;
@RestController
public class UploadExcelController {
@RequestMapping("/upload")
public Object uploadFile(MultipartFile file) throws IOException, TemplateException {
//读取文件的基本信息
String filename = file.getOriginalFilename();
InputStream inputStream = file.getInputStream();
try {
// Workbook workbook = ExcelUtils.buildWorkookFromStream(filename, inputStream);
//解析excel
List<Map<String, Object>> maps = ExcelUtils.excelToList(filename, inputStream, 0, 0);
Configuration configuration = new Configuration(DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
URL url = this.getClass().getClassLoader().getResource("freemarkers");
configuration.setDirectoryForTemplateLoading(new File(url.getFile()));
Template template = configuration.getTemplate("userMapper.ftl");
HashMap<String, Object> objMap = new HashMap<>();
objMap.put("maps",maps);
StringWriter sw = new StringWriter();
template.process(objMap,sw);
System.out.println(sw.toString());