---
# System prepended metadata

title: 表單傳送資料到後端(觀念)
tags: [SpringBoot, frontend]

---

---
title: '表單傳送資料到後端(觀念)'
disqus: hackmd
---
###### tags: `frontend` `SpringBoot`

表單傳送資料到spring boot後端，尚未建立資料庫
===

[TOC]

# 適用場景

html上面有個表單，想要把他的資料傳送到後端去，最後希望*打印*在console上面，希望枚舉出幾種常用的方法

1. 完全不靠js 直接傳送到後端
2. 靠js去做submit的動作
3. ajax
4. axios
5. jquery

# 撰寫順序

1. 寫出html 的form，放的位置要記得要在`src/main/resources/templates`下面
2. 寫出後端可以接收的controller，關鍵在於@RequestParam


# 單純使用html去submit

## HTML

```htmlembedded=
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>博主資訊</title>
</head>
<body>
<form th:action="@{/formsubmit/}" method="POST">
UserName : <input type="text" name="name"/> <br><br>   
Password : <input type="text" name="pass"/> <br><br>   
<input type="submit" name="submit">  
</form>  
</body>
</html>
```

## Controller

```java=
package com.allproducts.ai_center.form.controller;

import javax.websocket.Session;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

@Controller
@SessionAttributes({"username"})
public class FormController {

	@GetMapping("/formbyhtmlsubmit")
	
	public String getformbyhtmlsubmit() {
		
		return "form/formbyhtmlsubmit";
	}
	
	@PostMapping("/formsubmit")
	public String bet(@RequestParam("name") String name , @RequestParam("pass") String pass,Model model) {
		
		System.out.println(name);
		System.out.println(pass);
		model.addAttribute("username",name);
		return "user/hellonewuser";
		
	}
	
	@GetMapping("/hellonewuser2")
	
	public String getformbyhtmlsubmits() {
		
		return "user/hellonewuser2";
	}
	
	 @GetMapping("/showusername")
	 @ResponseBody
	 public String sdg( Model model    ) {
		
		String name = (String) model.getAttribute("username");
	    
		System.out.println("name = " + name);
		return name;
	}
}


```


> 使用@SessionAttributes({"username"})註解可以將username這個**識別字串**存在session
> 真的需要使用username的時候只需要調用`String name = (String) model.getAttribute("username");`便可以使用



# 使用javascript 去做submit



# 對表單去做驗證後再做出submit

> 關鍵在於要使用html tag onsubmit




# 參考連結

![](https://i.imgur.com/QCKaQkY.png)

[FormData](https://javascript.info/formdata)

[靠js去做submit](https://www.w3school.com.cn/tiy/t.asp?f=hdom_form_submit)

[Thymleaf](https://springhow.com/thymeleaf-form-handling/)

https://harttle.land/2015/08/03/form-submit.html

medium
https://medium.com/@rktlukman/form-validation-using-javascript-8896817b427b

