2017-02-13 46 views
-1

我構建了一個簡單的Spring Web應用程序。我有一個@RequestMapping這個簡單@Controller,但是當我運行它,我不能打的網址:我簡單的Spring web服務有什麼問題?

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(); 
    } 


} 
+2

你還可以嘗試http:// localhost:8080/all嗎?它似乎像一個URL問題給我。 – Kael53

+0

您可否請您發佈您的application-context.xml文件。 – SachinSarawgi

+0

您沒有在控制器的任何位置設置'/ labutil'。 @ Kael53建議應該可行(可能在URL中添加應用上下文) – Alfabravo

回答

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庫像傑克遜或GSON並配置相應的庫視圖實現視圖。