gpt4 book ai didi

java - 如何在 Web 应用程序项目的 Controller 中将字符串作为 JSON 对象返回

转载 作者:行者123 更新时间:2023-12-01 10:19:19 25 4
gpt4 key购买 nike

所以我有这个 Controller

    package org.aman.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.aman.model.Brands;
import org.aman.service.BrandsService;
@Controller

public class BrandsController {
@Autowired
private BrandsService brandsService;

@RequestMapping("/index")
public String setupForm(Map<String, Object> map) {
Brands brands = new Brands();
map.put("brands", brands);
map.put("brandsList", brandsService.getAllBrands());
return "brands";
}
@RequestMapping("/inde")
public String setupFor(Map<String, Object> map) {
Brands brands = new Brands();
map.put("brands", brands);
map.put("brandsSelectedList", brandsService.getAllBrands());
return "query";
}

@RequestMapping(value = "/brands.do", method = RequestMethod.POST)
public String doActions(@ModelAttribute Brands brands, BindingResult result, @RequestParam String action,
Map<String, Object> map) {
Brands brandsResult = new Brands();
switch (action.toLowerCase()) {
case "add":
brandsService.add(brands);
brandsResult = brands;
break;
case "edit":
brandsService.edit(brands);
brandsResult = brands;
break;
}
map.put("brands", brandsResult);
map.put("brandsList", brandsService.getAllBrands());
return "brands";
}


}

函数设置表单返回“brands”,该“brands”又映射到 Spring Servlet 中的 brands.jsp。我想返回解决方案的 JSON 对象而不是整个 JSP 页面。

我怎样才能做到这一点?任何形式的帮助将不胜感激。

最佳答案

由于您要将结果数据添加到 map 中,因此将返回类型设置为 Map<String, Object>并用 @ResposeBody 进行注释正如 @jb nizet 评论的那样,

@RequestMapping(value = "/brands.do", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> map doActions(@ModelAttribute Brands brands,
BindingResult result, @RequestParam String action, Map<String, Object> map)
{
Brands brandsResult = new Brands();
switch (action.toLowerCase()) {
case "add":
brandsService.add(brands);
brandsResult = brands;
break;
case "edit":
brandsService.edit(brands);
brandsResult = brands;
break;
}
map.put("brands", brandsResult);
map.put("brandsList", brandsService.getAllBrands());
return map;
}

关于java - 如何在 Web 应用程序项目的 Controller 中将字符串作为 JSON 对象返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35716369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com