简体   繁体   English

仅从 Spring MVC 3 控制器返回字符串消息

[英]Return only string message from Spring MVC 3 Controller

Can any one tell me how I can return string message from controller?谁能告诉我如何从控制器返回字符串消息?

If i just return a string from a controller method then spring mvc treating it as a jsp view name.如果我只是从控制器方法返回一个字符串,那么 spring mvc 将其视为 jsp 视图名称。

Annotate your method in controller with @ResponseBody :使用@ResponseBody在控制器中注释您的方法:

@RequestMapping(value="/controller", method=GET)
@ResponseBody
public String foo() {
    return "Response!";
}

From: 15.3.2.6 Mapping the response body with the @ResponseBody annotation :来自: 15.3.2.6 使用@ResponseBody注释映射响应主体

The @ResponseBody annotation [...] can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name). @ResponseBody注释 [...] 可以放在方法上,并指示返回类型应直接写入 HTTP 响应正文(而不是放置在模型中,或解释为视图名称)。

With Spring 4, if your Controller is annotated with @RestController instead of @Controller , you don't need the @ResponseBody annotation.在 Spring 4 中,如果您的 Controller 使用@RestController而不是@Controller注释,则您不需要@ResponseBody注释。

The code would be代码将是

@RestController
public class FooController {

   @RequestMapping(value="/controller", method=GET)
   public String foo() {
      return "Response!";
   }

}

You can find the Javadoc for @RestController here你可以在这里找到@RestController的 Javadoc

Although, @Tomasz is absolutely right there is another way:虽然@Tomasz 是绝对正确的,但还有另一种方式:

@RequestMapping(value="/controller", method=GET)
public void foo(HttpServletResponse res) {
    try {       
        PrintWriter out = res.getWriter();
        out.println("Hello, world!");
        out.close();
    } catch (IOException ex) { 
        ...
    }
}

but the first method is preferable.但第一种方法更可取。 You can use this method if you want to return response with custom content type or return binary type (file, etc...);如果要返回自定义内容类型的响应或返回二进制类型(文件等...),可以使用此方法;

This is just a note for those who might find this question later, but you don't have to pull in the response to change the content type.这只是给以后可能会发现此问题的人的注释,但您不必拉入响应来更改内容类型。 Here's an example below to do just that:下面是一个例子来做到这一点:

@RequestMapping(method = RequestMethod.GET, value="/controller")
public ResponseEntity<byte[]> displayUploadedFile()
{
  HttpHeaders headers = new HttpHeaders();
  String disposition = INLINE;
  String fileName = "";
  headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

  //Load your attachment here

  if (Arrays.equals(Constants.HEADER_BYTES_PDF, contentBytes)) {
    headers.setContentType(MediaType.valueOf("application/pdf"));
    fileName += ".pdf";
  }

  if (Arrays.equals(Constants.HEADER_BYTES_TIFF_BIG_ENDIAN, contentBytes)
      || Arrays.equals(Constantsr.HEADER_BYTES_TIFF_LITTLE_ENDIAN, contentBytes)) {
    headers.setContentType(MediaType.valueOf("image/tiff"));
    fileName += ".tif";
  }

  if (Arrays.equals(Constants.HEADER_BYTES_JPEG, contentBytes)) {
    headers.setContentType(MediaType.IMAGE_JPEG);
    fileName += ".jpg";
  }

  //Handle other types if necessary

  headers.add("Content-Disposition", , disposition + ";filename=" + fileName);
  return new ResponseEntity<byte[]>(uploadedBytes, headers, HttpStatus.OK);
}

What about:关于什么:

PrintWriter out = response.getWriter();
out.println("THE_STRING_TO_SEND_AS_RESPONSE");
return null;

This woks for me.这对我有用。

For outputing String as text/plain use:String输出为text/plain使用:

@RequestMapping(value="/foo", method=RequestMethod.GET, produces="text/plain")
@ResponseBody
public String foo() {
    return "bar";
}

Simplest solution:最简单的解决方案:

Just add quotes, I really don't know why it's not auto-implemented by Spring boot when response type defined as application/json, but it works great.只需添加引号,我真的不知道为什么当响应类型定义为 application/json 时它没有由 Spring boot 自动实现,但它工作得很好。

@PostMapping("/create")
public String foo()
{
    String result = "something"
    return "\"" + result + "\"";
}
@Controller
public class HelloController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    ResponseEntity<String> sayHello() {
        return ResponseEntity.ok("Hello");
    }
}
@ResponseBody
@RequestMapping(value="/get-text", produces="text/plain")
public String myMethod() {
     return "Response!";
}
  • You see that @ResponseBody ?你看到@ResponseBody吗?

It's telling that the method returns some text and not to interpret it as a view etc.这表明该方法返回一些文本而不是将其解释为视图等。

  • You see that produces="text/plain" ?你看到produces="text/plain"吗?

It's just a good practice as it tells what will be returned from the method :)这只是一个很好的做法,因为它说明了该方法将返回的内容:)

There are two possible solution有两种可能的解决方案

  1. Use @Controller and @ResponseBody , to combine HTML page and the string message for different functions使用@Controller@ResponseBody ,结合不同功能的 HTML 页面和字符串消息

    @Controller @RequestMapping({ "/user/registration"}) public class RegistrationController { @GetMapping public String showRegistrationForm(Model model) { model.addAttribute("user", new UserDto()); return "registration"; //Returns the registration.html } @PostMapping @ResponseBody public String registerUserAccount(@Valid final UserDto accountDto, final HttpServletRequest request) { LOGGER.debug("Registering user account with information: {}", accountDto); return "Successfully registered" // Returns the string }
  2. Use @RestController to return String message.使用@RestController返回字符串消息。 In this case, you cannot have functions which returns HTML page.在这种情况下,您不能拥有返回 HTML 页面的函数。

     @RestController @RequestMapping({ "/user/registration"}) public class RegistrationController { @PostMapping public String registerUserAccount(@Valid @RequestBody final UserDto accountDto, final HttpServletRequest request) { LOGGER.debug("Registering user account with information: {}", accountDto); return "Successfully registered" // Returns the string }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM