功能需求:
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.執行結果
寫入文本點擊提交
本地文件保存
寫入成功