我刚刚开始学习Spring Boot应用程序。下面是我在网页上显示一些文本的代码。一切都是运行文件,我的eclipse也启动了8080门户。但我用来打印的文本没有显示在网页上。 谁能帮我解决我哪里出错了。
package com.luv2code.springboot.demo.mycoolapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MycoolappApplication {
public static void main(String[] args) {
SpringApplication.run(MycoolappApplication.class, args);
}
}
package com.luv2code.springboot.demo.mycoolapp;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.GetMapping;
@SpringBootApplication
@ControllerAdvice
public class FunRestController {
//expose "/" that return "Hello World"
@GetMapping("/")
public String sayHello() {
return "Hello World";
}
//expose a new endpoing for "workout"
@GetMapping("/workout")
public String getDailyWorkout() {
return "Run a hard 5k!";
}
}
package com.luv2code.springboot.demo.mycoolapp;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class CustomErrorController implements ErrorController {
@RequestMapping("/error")
public String handleError() {
return "customError"; // Return the name of your custom error view
}
}
我希望在我的网页中看到 Run a Hard 5k!,但我得到的是空白页面作为输出。
谢谢你
@ControllerAdvice
是错误处理注释。例如:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ExampleException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEntity<String> handleIllegalArgumentException(ExampleException ex) {
return new ResponseEntity<>("Error: " + ex.getMessage(), HttpStatus.BAD_REQUEST);
}
}
@Controller
public class GlobalExceptionHandler {
@GetMapping
public void endpoint() {
throw new ExampleException();
}
}
如果您想使用 RestAPI,请使用 @RestController 进行请求处理,使用 @RestControllerAdvice 进行错误处理,并使用 json 响应而不使用 ResponseEntity。 (Ofc,不强制使用@Rest版本)
参见:
@RestController // <-- Not advice, + @RestController
public class CustomErrorController { // <-- Not need ErrorController
//expose "/" that return "Hello World"
@GetMapping("/")
public String sayHello() {
return "Hello World";
}
//expose a new endpoing for "workout"
@GetMapping("/workout")
public String getDailyWorkout() {
return "Run a hard 5k!";
}
}