Recently I'm doing web development with Spring Boot. I would like to manage sessions with @SessionScope as much as possible instead of using HttpSession directly. I investigated how to reference @SeesionScope beans in Filter.
name | version |
---|---|
macOS | Catalina 10.15.4 |
IntelliJ IDEA | 2019.3.4 (Community Edition) |
Java | "11.0.2" 2019-01-15 |
Spring Boot | 2.2.6 |
Kotlin | 1.3.71 |
Sample code and projects are available on GitHub. Please have a look if you like.
There is a lot of information and the contents of the investigation will be described later, but I will write from the conclusion first.
A simple configuration could only be achieved with @Autowired
.
UserInfo.kt(@SessionScope)
@Component
@SessionScope
data class UserInfo(
var name: String?
) : Serializable
SessionFilter.kt(OncePerRequestFilter)
@Component
class SessionFilter : OncePerRequestFilter() {
//It was the same as DI with Controller.
@Autowired
private lateinit var userInfo: UserInfo
override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, filterChain: FilterChain) {
println("name: ${userInfo.name}")
filterChain.doFilter(request, response)
}
}
Although it is not a book of Spring Boot 2, it seems to be famous in the Spring area Introduction to Spring Java application development with Spring Framework DelegatingFilterProxy
A method has been proposed to define in XML to register a filter in.
Therefore, I decided to try the method using DelegatingFilterProxy
first. I don't like the method of defining in XML, so I rewrote it in Java Config (Kotlin).
SessionFilter.kt(OncePerRequestFilter)
@Component("SessionFilter") //I was specifying a name.
class SessionFilter : OncePerRequestFilter() {
:
: (Same as the code posted in the conclusion)
:
}
WebInitializer.kt
class WebInitializer : AbstractAnnotationConfigDispatcherServletInitializer() {
override fun getRootConfigClasses(): Array<Class<*>>? {
return null
}
override fun getServletMappings(): Array<String> {
return arrayOf("/")
}
override fun getServletFilters(): Array<Filter> {
val dfp = DelegatingFilterProxy().apply {
// SessionFilter.kt@Set the name specified in Component.
setTargetBeanName("SessionFilter")
}
return arrayOf(dfp)
}
override fun getServletConfigClasses(): Array<Class<*>>? {
return arrayOf(WebConfig::class.java)
}
}
I've seen some FAQs that can't DI in `Filter, and the above countermeasures have been introduced, but in my environment Conclusion / e02cad0e81ad8ba9d73e #% E7% B5% 90% E8% AB% 96), I achieved the purpose without this description. There may be a difference between Spring MVC and Spring Boot 2, but there is too little information to investigate.
Compared to other well-known web frameworks (though I don't think it's a minor web framework), I got the impression that Spring-related information is often complicated and legacy. Therefore, I posted an article for the first time in a long time, hoping that it would be useful for something.
Recommended Posts