当我@ExceptionHandler在控制器中使用时,它没有按预期工作。
这是我的代码:
@Controller
public class PageController {
@RequestMapping("/page")
public ModelAndView index(ModelAndView modelAndView){
String mess = null;
mess.split(",");
modelAndView.setViewName("index");
return modelAndView;
}
@ExceptionHandler({Exception.class})
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Bad Request")
public ModelAndView handleException(Exception ex, HttpServletRequest request, HttpServletResponse response){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message", ex.getMessage());
modelAndView.addObject("url", request.getRequestURL());
modelAndView.addObject("code", response.getStatus());
modelAndView.setViewName("exception");
return modelAndView;
}
}
Run Code Online (Sandbox Code Playgroud)
应用程序以调试模式启动后,我访问http://localhost:8080/page,并且handleException正在运行,但视图低于预期excepction视图。为什么?

我是 Spring Boot 的新手,我非常有兴趣学习这项技术。问题是,我得到了一个带有 @configuration 标记的配置文件。因此,当我尝试添加 @enablemvc 注释或者在 Spring Boot 应用程序中添加带有 @enablemvc 注释的新文件时,我无法运行该应用程序。如果有人能帮助我解决这个问题,我真的很感激。
日志
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourceHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is org.springframework.beans.factory.BeanInitializationException: Failed to init ResourceHttpRequestHandler; nested exception is java.lang.IllegalStateException: WebApplicationObjectSupport instance [ResourceHttpRequestHandler [locations=[class path resource [resources/], class path resource [images/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@39e6b948]]] does not run in a WebApplicationContext but in: org.springframework.context.annotation.AnnotationConfigApplicationContext@19b44076: startup …Run Code Online (Sandbox Code Playgroud) 验证发布请求 DTO bean 的推荐/最佳方法是什么?如果验证失败,我需要发送自定义错误消息,例如
{
"code": "invalid_fields",
"fields": {
"email": "Required",
"password": "Required",
}
}
Run Code Online (Sandbox Code Playgroud)
DTO模型
public class SignUpRequest {
@JsonProperty("email")
String email;
@JsonProperty("password")
String password;
public Result validate(){
}
}
Run Code Online (Sandbox Code Playgroud)
控制器
@PostMapping(value = "/register")
public ResponseEntity<Object> signupRider(@RequestBody SignUpRequest signUpRequest) {
Result result = signUpRequest.validate();
return new ResponseEntity<>(x, HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)
SignUpRequest DTO 具有 validate 方法。 spring 进行验证的方式是什么?
谢谢。
我希望在页面上显示此文件,但此代码可直接下载
<a th:href="@{/pdf/Manjaro-User-Guide.pdf}">Show Pdf file</a>
我正在使用 Spring-Thymeleaf
谢谢!
我有一个尤里卡服务器运行 application.yml 看起来像
server:
port: 8761
eureka:
client:
registerWithEureka: false
fetch-registry: false
server:
wait-time-in-ms-when-sync-empty: 5
enable-self-preservation: false
Run Code Online (Sandbox Code Playgroud)
在客户端,我有
eureka:
instance:
prefer-ip-address: true
lease-renewal-interval-in-seconds: 1
lease-expiration-duration-in-seconds: 1
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:8761/eureka
Run Code Online (Sandbox Code Playgroud)
我特意放了
lease-renewal-interval-in-seconds: 1
lease-expiration-duration-in-seconds: 1
Run Code Online (Sandbox Code Playgroud)
而不是租约到期持续时间(以秒为单位)的默认值 90。
然而,Eureka 注销客户端需要接近 30 秒的时间,这与默认情况下注册客户端所需的时间类似,而无需显式添加 wait-time-in-ms-when-sync-empty: 5 eureka服务器的application.yml
有没有办法加快注销过程?看来我的加速尝试没有奏效
创建不同的层(即服务层)来实现业务逻辑而不是在控制器本身中实现该业务逻辑有什么用
我确实有一个类CustomResponseEntityExceptionHandler扩展ResponseEntityExceptionHandler了两种方法,一种用于处理错误的格式,另一种用于请求资源(url)但不存在时。我想给用户一条自定义消息,而不是 Spring 默认的白标错误页面。我试图理解为什么我的handleResourceNotFoundException方法来自CustomResponseEntityExceptionHandler当请求不存在的 URI 时不调用,而是一直显示白标签错误页面。感谢您的帮助!
curl localhost:8080/doesnotexist\nRun Code Online (Sandbox Code Playgroud)\n\n这是我的CustomResponseEntityExceptionHandler
@ExceptionHandler(Exception.class)\npublic final ResponseEntity<ErrorDetails> handleAllWrongFormatExceptions(WrongFormatException ex,\n WebRequest request) {\n ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(true));\n return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);\n}\n\n@ExceptionHandler(ResourceNotFoundException.class)\npublic final ResponseEntity<ErrorDetails> handleResourceNotFoundException(ResourceNotFoundException ex,\n WebRequest request) {\n ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));\n return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);\n}\nRun Code Online (Sandbox Code Playgroud)\n\n用于保存自定义错误详细信息的简单类
\n\npublic class ErrorDetails {\n\nprivate Date timestamp;\nprivate String message;\nprivate String details;\n\npublic ErrorDetails(Date timestamp, String message, String details) …Run Code Online (Sandbox Code Playgroud) 我有一个带有以下 pom.xml 的 SpringBoot 应用程序:
\n\n...\n<parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>2.0.6.RELEASE</version>\n <relativePath/> \n </parent>\n\n<!-- Spring Security -->\n <dependency>\n <groupId>org.thymeleaf.extras</groupId>\n <artifactId>thymeleaf-extras-springsecurity4</artifactId>\n </dependency>\n...\nRun Code Online (Sandbox Code Playgroud)\n\n并且运行良好。\n然后我将 SpringBoot 版本更新为
\n\n...\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>2.1.0.RELEASE</version>\n <relativePath/> \n </parent>\n\n <dependency>\n <groupId>org.thymeleaf.extras</groupId>\n <artifactId>thymeleaf-extras-springsecurity4</artifactId>\n <version>3.0.4.RELEASE</version> \n </dependency>\n...\nRun Code Online (Sandbox Code Playgroud)\n\n我在 1 个模板中收到此错误:
\n\nException evaluating SpringEL expression: "#authorization.expression(\'hasRole(\'\'ROLE_ADMIN\'\')\')" (template: "tdk/common/menu" - line 87, col 21)\nRun Code Online (Sandbox Code Playgroud)\n\n这里是模板:
\n\n <li th:if="${#authorization.expression(\'hasRole(\'\'ROLE_ADMIN\'\')\')}" class="menu-principal pure-menu-item" th:classappend="${activeMenuItem == \xe2\x80\x98tdkMessages\'} ? pure-menu-selected">\n <a href=\xe2\x80\x9c/tdk/list" class="pure-menu-link">\n <i class="fas fa-cloud-download-alt fa-lg fa-fw"></i> tdk\n </a>\n </li>\nRun Code Online (Sandbox Code Playgroud)\n 我正在开发一个 REST API,其中有一个接口定义了由 4 个不同类实现的方法列表,并且将来有可能添加更多类。
当我收到来自客户端的 HTTP 请求时,URL 中包含一些信息,这些信息将确定需要使用哪个实现。
在我的控制器中,我希望端点方法包含一个 switch 语句,用于检查 URL 路径变量,然后使用适当的实现。
我知道我可以定义具体的实现并将其注入到控制器中,然后在 switch 语句中的每种特定情况下插入我想要使用的实现,但这看起来不太优雅或可扩展,原因有两个:
我现在必须实例化所有服务,即使我只需要使用一项服务。
该代码似乎可以更简洁,因为我实际上是使用相同的参数调用接口中定义的相同方法,虽然在示例中这并不是真正的问题,但在实现列表增长的情况下。 .. 案例和冗余代码的数量也是如此。
有没有更好的方案来解决此类情况呢?我正在使用 SpringBoot 2 和 JDK 10,理想情况下,我想实现最现代的解决方案。
我目前的方法
@RequestMapping(Requests.MY_BASE_API_URL)
public class MyController {
//== FIELDS ==
private final ConcreteServiceImpl1 concreteService1;
private final ConcreteServiceImpl2 concreteService2;
private final ConcreteServiceImpl3 concreteService3;
//== CONSTRUCTORS ==
@Autowired
public MyController(ConcreteServiceImpl1 concreteService1, ConcreteServiceImpl2 concreteService2,
ConcreteServiceImpl3 concreteService3){
this.concreteService1 = concreteService1;
this.concreteService2 = concreteService2;
this.concreteService3 = concreteService3;
}
//== REQUEST MAPPINGS ==
@GetMapping(Requests.SPECIFIC_REQUEST)
public ResponseEntity<?> handleSpecificRequest(@PathVariable String source,
@RequestParam …Run Code Online (Sandbox Code Playgroud) 我现在开始学习Spring Security,但遇到了麻烦。我编写了配置类,从数据库获取数据等,但在我的网页中,我在登录后看到消息“用户帐户已锁定”和 url 中的错误参数。
MessengerApplication.java
@SpringBootApplication
public class MessengerApplication {
public static void main(String[] args) {
SpringApplication.run(MessengerApplication.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
MainPageController.java
@RestController
public class MainPageController {
@RequestMapping("/")
public ModelAndView greeting() {
Map<String, Object> model = new HashMap<>();
model.put("data", "world");
return new ModelAndView("main_page", model);
}
}
Run Code Online (Sandbox Code Playgroud)
安全配置.java
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserServiceImpl userService;
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider
= new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userService);
authProvider.setPasswordEncoder(encoder());
return …Run Code Online (Sandbox Code Playgroud)