功能需求:
web应用中实现简易记事本,内容保存到本地文件
概要设计:
1.spring boot实现前后端消息传送
2.业务类中实现写入本地文件
实现:
1.spring boot搭建
mvn导入spring boot核心包
其中thymeleaf包的作用是查询并匹配项目中的响应路径
配置文件为application.properties
f
这里prefix为templates文件夹,response返回到该路径下的html文件
2.controller请求控制器的实现
package com.example.demo.controller;
import com.example.demo.biz.Save2TxtBiz;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
@Controller
public class Save2TxtController {
@PostMapping("save2Txt")
public String save2Txt(HttpServletRequest request){
Map map = request.getParameterMap();
// System.out.println("test text value = " + textValue);
Set set = map.entrySet();
String[] temp = (String[]) map.get("textValue");
System.out.println("test value = " + temp[0]);
Save2TxtBiz.save(temp[0],"hehe.txt");
return "test";
}
@RequestMapping("noteBook")
public String redirectNoteBookPage(){
return "noteBook";
}
}
浏览器发送后缀类似/save2Txt的请求后由PostMapping捕捉并执行业务,这里的Mapping类用的是PostMapping,这是由于html中的form表单提交文本,需要的字节数可能比较大,而get方法的大小的是固定的
3.前段表单提交页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>记事本</title>
</head>
<body>
<form action="/save2Txt" method="post">
<textarea id="textValue" name="textValue"></textarea>
<input type="submit" value="保存并提交"></input>
</form>
</body>
</html>
控制器通过textValue这个字段获取文本的值
4.最后是接受文本值并将文本写入到本地文件,我写了一个类完成所有的工作
package com.example.demo.biz;
import java.io.*;
public class Save2TxtBiz {
public static String FILE_PATH = "C:\\Users\\Administrator\\Desktop\\test\\";
public static boolean save(String content,String fileName){
String path = FILE_PATH + fileName;
File file = new File(path);
//创建文件
if(!file.exists()){
try {
file.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
}
return write2Txt(content,path);
}
//写入txt
public static boolean write2Txt(String content,String path){
File file = new File(path);
FileInputStream fileInputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
String temp = "";
try {
fileInputStream = new FileInputStream(file);
inputStreamReader = new InputStreamReader(fileInputStream);
bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0;(temp = bufferedReader.readLine()) != null;i ++){
stringBuffer.append(temp);
stringBuffer.append(System.getProperty("ling.separator"));
}
stringBuffer.append(content + "\r\n");
FileOutputStream fileOutputStream = new FileOutputStream(file);
PrintWriter printWriter = new PrintWriter(fileOutputStream);
printWriter.write(stringBuffer.toString().toCharArray());
printWriter.flush();
}catch (IOException e){
e.printStackTrace();
}
return true;
}
}
5.执行结果
写入文本点击提交
本地文件保存
写入成功