白季飞龙的个人主页

Spring大杂烩

获取当前Request

((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()返回当前的HttpServletRequest

Spring异常处理

package bj

import org.omg.CORBA.Object
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.event.ApplicationReadyEvent
import org.springframework.context.ApplicationListener
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.*
import org.springframework.web.servlet.HandlerExceptionResolver
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer

@SpringBootApplication
@RestController
class App : ApplicationListener<ApplicationReadyEvent>, WebMvcConfigurer {

    override fun onApplicationEvent(event: ApplicationReadyEvent?) {
        println("here")
    }

    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            SpringApplication.run(App::class.java, *args)
        }
    }

    @RequestMapping("/")
    fun home(): Object {
        throw StackOverflowError("Over")
    }

    @RequestMapping("/err")
    fun err(): Object {
        throw IndexOutOfBoundsException("Index")
    }

    override fun extendHandlerExceptionResolvers(resolvers: MutableList<HandlerExceptionResolver>) {
        super.extendHandlerExceptionResolvers(resolvers)
        resolvers.add(HandlerExceptionResolver { request, response, handler, ex ->
            println("Exception: $ex")
            return@HandlerExceptionResolver null
        })
    }
}

@ControllerAdvice
@RestController
class MyAdv {
    @ExceptionHandler(IndexOutOfBoundsException::class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    fun processException(e: Exception): Any {
        return e.localizedMessage;
    }
}

@RestController注解

org.springframework.web.bind.annotation.RestController#value表示的是 bean 的名字,不是 URL ,配置 URL 要用注解 @RequestMapping

404页面的处理

Spring默认404不抛异常,所以需要强制抛出异常,然后用@ExceptionHandler(NoHandlerFoundException::class)处理

以下两条属性的设置缺一不可:

spring.resources.add-mappings=false
spring.mvc.throw-exception-if-no-handler-found=true

文章首发: https://baijifeilong.github.io


漫漫路,莫论逍遥;潜心修,只为悟道