【问题标题】:what's wrong with my simple Spring web service?我的简单 Spring Web 服务有什么问题?
【发布时间】:2017-07-01 23:27:31
【问题描述】:

我构建了一个简单的 Spring Web 应用程序。我有一个带有@RequestMapping 的简单@Controller,但是当我运行它时,我无法点击 URL:

http://localhost:8080/labutil/all

我做错了什么?

package com.mycompany.ion.labutil.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.nokia.ion.labutil.service.LabService;

@Controller
public class LabController {

    @Autowired
    private LabService labService;

    @RequestMapping(value = "/all", method = RequestMethod.GET)
    public String getAll() throws Exception {
        List<String> list = labService.getAll();

        // build fake little json formatted data
        StringBuffer sb = new StringBuffer("{");
        for (String s : list) {
            sb.append("{ "+s+" }, ");
        }
        sb.append("}");

        return sb.toString();
    }


}

【问题讨论】:

  • 你也可以试试localhost:8080/all 吗?对我来说,这似乎是一个 url 问题。
  • 能否请您发布您的 application-context.xml 文件。
  • 你没有在控制器的任何地方设置/labutil。 @Kael53 建议应该有效(也许在 URL 中添加应用上下文)
  • 你需要@RestController,而不是@Controller。否则,返回的字符串应该是视图名称。
  • @Kael53 /all 也不起作用。该网络应用程序以localhost:8080/labutil 运行...当我去那里时,我看到了位于 /src/main/webapp/index.jsp 中的 index.jsp ...我假设 URL 将是 /labutil/all

标签: java spring spring-mvc spring-web


【解决方案1】:

您必须将控制器注释为@RestController 或将@ResponseBody 注释添加到您的方法中。通过这种方式,您告诉 Spring 该方法将对象作为 HTTP 正文响应返回。 @RestController 是一个方便的注解,同时使用了@Controller 和@ResponseBody 注解。

Here 回答为什么你应该使用这个注解。

@RequestMapping(value = "/all", method = RequestMethod.GET)
@ResponseBody
public String getAll() throws Exception {
    List<String> list = labService.getAll();

    // build fake little json formatted data
    StringBuffer sb = new StringBuffer("{");
    for (String s : list) {
        sb.append("{ "+s+" }, ");
    }
    sb.append("}");

    return sb.toString();
}

另一方面,您应该返回一个对象,而不是解析的字符串 Json,添加一些 Json 库,如 Jackson 或 Gson,并使用相应的库视图实现配置视图。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多