SpringBoot和前端数据交互(js,jQuery,thymeleaf)

一、后台接收URL拼接参数
后台代码:

@GetMapping("/item/{code}")    //对应的链接为:/item/10001
public List<Description> getProduct(@PathVariable("code") String productCode) {
    //your code  
}


二、后台接收查询参数
后台代码:

@GetMapping("/detail")    //对应的链接为:/detail?code=&name=
public String listMaterial(@RequestParam("code") String productCode, @RequestParam("name") String productName) {
    //your code
}


前台代码:

1.通过表单提交

2.通过JavaScript使用Formdata对象提交

 

三、后台接收json
后台代码:

@PostMapping("/add")
public MaterialStandard addProduct(@RequestBody Product product ){
    //your code
}


前台代码:

1.通过JavaScript提交

var product = new Product();
$.ajax({
    url:"/add",
    type:"POST",
    data:JSON.stringify(product),
    contentType: "application/json;charset=UTF-8",
    accept : "*/*",
    success : function () {
        console.log("Successfully");
    }
});    //使用了jQuery,原生JavaScript同理


四、接收文件
后台代码:

@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) {
    //your code
}


前台代码:

1.通过表单提交

2.通过JavaScript使用FormData对象提交

<input type="file" id="file" name="file">
var fileInput = $("#file");
var selectedFile = fileInput[0].files[0];
var data = new FormData();
data.append("file", selectedFile);
$.ajax({
    url: '/upload',
    type: 'POST',
    data: data,
    contentType: false, //不设置内容类型
    processData: false, //不处理数据
    accept : "*/*",
    success : function () {
        console.log("Successfully");
    }
});    使用了jQuery,原生JavaScript同理

五、关于thymeleaf模板和Ajax

前台的视图模版我使用的是thymeleaf,它是SpringBoot官方推荐的一个html5模版引擎,SpringBoot官方不推荐使用jsp,SpringBoot官网也是使用这个模版引擎做的。
通过jQuery的ajax向Controller发送请求,在js回调函数中处理返回的数据,页面我用bootstrap快速的做了一个表格,渲染列表使用了一个叫做avalonjs的迷你mvvm框架,生成虚拟dom,可以参考官网。[链接]:http://avalonjs.coding.me/)

 

HTML页面示例:

<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head lang="en">
    <meta charset="UTF-8"/>
    <title></title>
    <link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap.min.css}"/>
</head>
<body ms-controller="viewmodel">
<h1 th:text="${msg}">Hello World</h1>
<button type="button" class="btn btn-primary" style="margin: 10px;" ms-click="@request">{{@text}}</button>
<table class="table table-striped">
    <thead>
    <tr>
        <td class="active">id</td>
        <td class="success">姓名</td>
        <td class="warning">性别</td>
        <td class="danger">年龄</td>
        <td class="info">角色</td>
    </tr>
    </thead>
    <tbody>
    <tr ms-for="el in @datalist">
        <td >{{el.id}}</td>
        <td >{{el.name}}</td>
        <td>{{el.sex}}</td>
        <td >{{el.age}}</td>
        <td >{{el.role}}</td>
    </tr>
    </tbody>
</table>
</body>
<script th:src="@{/js/jquery-2.1.1.min.js}"></script>
<script th:src="@{/js/avalon.js}"></script>
<script th:src="@{/js/bootstrap.min.js}"></script>
<script th:src="@{/js/myscript.js}"></script>
</html>

js文件:

var viewmodel = avalon.define({
    //id必须和页面上定义的ms-controller名字相同,否则无法控制页面
    $id: "viewmodel",
    datalist: {},
    text: "请求数据",

    request: function () {
        $.ajax({
            type: "post",
            url: "/hello/data",    //向后端请求数据的url
            data: {},
            success: function (data) {
                $('button').removeClass("btn-primary").addClass("btn-success").attr('disabled', true);

                viewmodel.datalist = data;

                viewmodel.text = "数据请求成功,已渲染";
            }
        });
    }
});


 

  • 8
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 前后端数据交互可以采用以下几种方式: 1. RESTful API 使用 Spring Boot 提供的 @RestController 注解和 @RequestMapping 注解,可以创建 RESTful API 接口,前端可以通过 Ajax 或者 Fetch API 发送请求,后端返回 JSON 格式的数据。 例如,创建一个 UserController,提供获取用户列表的接口: ```java @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @GetMapping public List<User> getUsers() { return userService.getAllUsers(); } } ``` 前端可以通过以下方式发送 GET 请求: ```javascript fetch('/users') .then(response => response.json()) .then(data => console.log(data)); ``` 2. Thymeleaf 模板引擎 Thymeleaf 是一款流行的模板引擎,可以方便地将后端数据渲染到前端页面上。 例如,在后端控制器中返回 ModelAndView,包含用户列表数据和视图名称: ```java @GetMapping("/users") public ModelAndView getUsers() { List<User> users = userService.getAllUsers(); ModelAndView mav = new ModelAndView("users"); mav.addObject("users", users); return mav; } ``` 在前端页面中使用 Thymeleaf 语法,将用户列表数据渲染到页面上: ```html <table> <thead> <tr> <th>ID</th> <th>Name</th> <th>Email</th> </tr> </thead> <tbody> <tr th:each="user : ${users}"> <td th:text="${user.id}"></td> <td th:text="${user.name}"></td> <td th:text="${user.email}"></td> </tr> </tbody> </table> ``` 3. WebSocket WebSocket 是一种实时通信协议,可以实现前后端的双向通信。Spring Boot 提供了 WebSocket 支持,可以通过 @Controller 和 @MessageMapping 注解实现。 例如,在后端控制器中创建 WebSocket 服务端: ```java @Controller public class WebSocketController { @MessageMapping("/hello") @SendTo("/topic/greetings") public Greeting greeting(HelloMessage message) throws Exception { Thread.sleep(1000); // simulated delay return new Greeting("Hello, " + message.getName() + "!"); } } ``` 前端可以通过以下方式发送消息: ```javascript var socket = new WebSocket('ws://localhost:8080/greetings'); socket.onopen = function(event) { socket.send(JSON.stringify({ name: 'World' })); }; socket.onmessage = function(event) { console.log(JSON.parse(event.data)); }; ``` 以上是 Spring Boot 前后端数据交互的几种方式,可以根据具体的需求选择适合的方式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值