前后端配置

0)前端怎么发:还是这三种(不变)表单提交:application/x-www-form-urlencoded(或表单默认)JSON:Content-Type: application/json(推荐)文件上传:multipart/form-data你只要把 URL 指向 Java 服务就行,比如 [代码] 。1)J…

作者:lh

0)前端怎么发:还是这三种(不变)

  • 表单提交:application/x-www-form-urlencoded(或表单默认)
  • JSON:Content-Type: application/json(推荐)
  • 文件上传:multipart/form-data

你只要把 URL 指向 Java 服务就行,比如 /api/chat


1)Java 接收表单(同步/异步都行)

前端(表单)

<form method="post" action="/api/submit">  <input name="title" />  <textarea name="content"></textarea>  <button type="submit">提交</button></form>

后端(Spring Boot)

@RestControllerpublic class SubmitController {  @PostMapping("/api/submit")  public Map<String, Object> submit(@RequestParam String title,                                    @RequestParam String content) {    return Map.of("ok", true, "title", title, "content", content);  }}

2)推荐:Java 接收 JSON(fetch 发送画像/请求最合适)

前端(fetch JSON)

<button id="btn">发送</button><script>  document.getElementById("btn").onclick = async () => {    const payload = { user_id: "u123", message: "你好", ts: Date.now() };    const r = await fetch("/api/chat", {      method: "POST",      headers: { "Content-Type": "application/json" },      body: JSON.stringify(payload)    });    const data = await r.json();    console.log(data);  };</script>

后端(Spring Boot:@RequestBody)

DTO

public class ChatReq {  public String user_id;  public String message;  public Long ts;}

Controller

@RestControllerpublic class ChatController {  @PostMapping("/api/chat")  public Map<String, Object> chat(@RequestBody ChatReq req) {    String reply = "收到:" + req.message;    return Map.of("ok", true, "reply", reply, "user_id", req.user_id);  }}
这就是你做“前端传用户画像/候选列表 -> Java 聚合/调用模型服务 -> 返回推荐结果”的标准结构。

3)Java 接收文件上传(multipart/form-data)

前端(FormData)

<input id="f" type="file" /><button id="up">上传</button><script>  document.getElementById("up").onclick = async () => {    const fd = new FormData();    fd.append("file", document.getElementById("f").files[0]);    fd.append("scene", "import_doc");    const r = await fetch("/api/upload", { method: "POST", body: fd });    console.log(await r.json());  };</script>

后端(Spring Boot:MultipartFile)

@RestControllerpublic class UploadController {  @PostMapping("/api/upload")  public Map<String, Object> upload(@RequestParam("file") MultipartFile file,                                    @RequestParam(value="scene", required=false) String scene)      throws Exception {    if (file.isEmpty()) return Map.of("ok", false, "error", "no_file");    return Map.of("ok", true, "filename", file.getOriginalFilename(),                  "size", file.getSize(), "scene", scene);  }}

4)安全/跨域(前后端分离时最常见)

如果你的前端是 http://localhost:8000,Java 后端是 http://localhost:8080,就会跨域。

Spring Boot 快速允许跨域(开发期)

@Configurationpublic class CorsConfig implements WebMvcConfigurer {  @Override  public void addCorsMappings(CorsRegistry registry) {    registry.addMapping("/api/**")        .allowedOrigins("http://localhost:8000")        .allowedMethods("GET","POST","PUT","DELETE","OPTIONS")        .allowedHeaders("*")        .allowCredentials(true);  }}

前端 fetch 如果带 cookie/鉴权(比如 session),要加:

fetch("http://localhost:8080/api/chat", {  method: "POST",  credentials: "include",  headers: {"Content-Type":"application/json"},  body: JSON.stringify(payload)})

5)你如果是“聊天流式输出”,Java 也能做(SSE 版)

前端:

const es = new EventSource("/api/stream");es.onmessage = (e) => console.log("chunk:", e.data);

后端(Spring Boot SSE):

@GetMapping(value="/api/stream", produces="text/event-stream")public SseEmitter stream() {  SseEmitter emitter = new SseEmitter();  new Thread(() -> {    try {      for (int i=0;i<5;i++){        emitter.send("token-" + i);        Thread.sleep(300);      }      emitter.complete();    } catch (Exception e) {      emitter.completeWithError(e);    }  }).start();  return emitter;}