return from springboot

本文介绍Spring框架如何使用Jackson库自动将Greeting对象转换为JSON格式,实现RESTful服务。通过@RestController注解简化控制器实现,直接返回业务对象,由Spring自动处理JSON序列化。
package hello;

public class Greeting {

    private final long id;
    private final String content;

    public Greeting(long id, String content) {
        this.id = id;
        this.content = content;
    }

    public long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }
}
package hello;

import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }
}

As you see in steps below, Spring uses the Jackson JSON library to automatically marshal instances of type Greeting into JSON.

The implementation of the method body creates and returns a new Greeting object with id and content attributes based on the next value from the counter, and formats the given name by using the greeting template.

A key difference between a traditional MVC controller and the RESTful web service controller above is the way that the HTTP response body is created. Rather than relying on a view technology to perform server-side rendering of the greeting data to HTML, this RESTful web service controller simply populates and returns a Greeting object. The object data will be written directly to the HTTP response as JSON.

This code uses Spring 4’s new @RestController annotation, which marks the class as a controller where every method returns a domain object instead of a view. It’s shorthand for @Controller and @ResponseBody rolled together.

The Greeting object must be converted to JSON. Thanks to Spring’s HTTP message converter support, you don’t need to do this conversion manually. Because Jackson 2 is on the classpath, Spring’s MappingJackson2HttpMessageConverter is automatically chosen to convert the Greeting instance to JSON.

在 Spring Boot 中获取表单提交的数据,通常可以通过以下几种方式实现: ### 1. 使用 `@RequestParam` 获取单个字段值 如果前端通过 HTTP 表单提交数据(如 POST 请求),可以使用 `@RequestParam` 注解来获取每个字段的值。这种方法适用于简单的键值对表单数据。 ```java @PostMapping("/submit-form") public String handleFormSubmission(@RequestParam("username") String username, @RequestParam("password") String password) { // 处理接收到的表单数据 return "Received Username: " + username + ", Password: " + password; } ``` ### 2. 使用 `@ModelAttribute` 绑定到对象 当表单字段较多时,推荐将数据绑定到一个 Java 对象上,这样可以简化代码并提高可读性。 定义一个实体类: ```java public class UserForm { private String username; private String password; // Getters and Setters } ``` 然后在控制器中使用 `@ModelAttribute`: ```java @PostMapping("/submit-form") public String handleFormWithModel(@ModelAttribute("userForm") UserForm userForm) { // 处理用户表单 return "Received Username: " + userForm.getUsername() + ", Password: " + userForm.getPassword(); } ``` ### 3. 使用 `HttpServletRequest` 手动获取参数 如果不希望通过注解方式获取数据,也可以直接使用 `HttpServletRequest` 来手动提取表单数据。 ```java @PostMapping("/submit-form") public String handleFormUsingRequest(HttpServletRequest request) { String username = request.getParameter("username"); String password = request.getParameter("password"); return "Received Username: " + username + ", Password: " + password; } ``` ### 4. 使用 `@RequestBody` 接收 JSON 数据 如果前端发送的是 JSON 格式的请求体(例如通过 Axios 或 Fetch API 发送 JSON 数据),可以使用 `@RequestBody` 来接收数据。需要注意设置正确的 Content-Type(如 application/json)。 定义一个用于接收数据的类: ```java public class UserJson { private String username; private String password; // Getters and Setters } ``` 控制器方法示例: ```java @PostMapping("/submit-json") public String handleJsonData(@RequestBody UserJson userJson) { return "Received JSON Data - Username: " + userJson.getUsername() + ", Password: " + userJson.getPassword(); } ``` ### 5. 使用 `MultipartResolver` 处理文件上传和表单数据 如果表单包含文件上传字段,Spring Boot 提供了自动解析 multipart/form-data 请求的功能。可以结合 `@RequestParam` 和 `MultipartFile` 来处理文件上传。 ```java @PostMapping("/upload-form") public String handleFileUpload(@RequestParam("file") MultipartFile file, @RequestParam("username") String username) { // 处理上传的文件和用户名 return "Uploaded File Name: " + file.getOriginalFilename() + ", Username: " + username; } ``` --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值