两种方法
1、request.getSession().getAttribute("X")
2、${sessionScope.X}
九大内置对象
JSP中有九大内置对象,可以直接用session,也可以获取从request中取,其本质都是同一个。九大内置对象如下:
JSP中九大内置对象为:
内置对象 | 说明 | 类型 | 作用域 |
---|---|---|---|
request | 请求对象 | javax.servlet.ServletRequest | Request |
response | 响应对象 | javax.servlet.SrvletResponse | Page |
pageContext | 页面上下文对象 | javax.servlet.jsp.PageContext | Page |
session | 会话对象 | javax.servlet.http.HttpSession | Session |
application | 应用程序对象 | javax.servlet.ServletContext | Application |
out | 输出对象 | javax.servlet.jsp.JspWriter | Page |
config | 配置对象 | javax.servlet.ServletConfig | Page |
page | 页面对象 | javax.lang.Object | Page |
exception | 异常对象 | javax.lang.Throwable | page |
代码实例
jsp
<button type="button" class="username dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
${sessionScope.currentUser.username}<span class="caret"></span>
</button>
java
package com.restfeel.controller
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import java.util.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
* Created by jack on 2017/3/30.
*/
@Controller
class HomeController {
internal var logger = LoggerFactory.getLogger(AppController::class.java)
@Value("\${application.message:REST Feel}")
private val message = "REST Feel"
@RequestMapping("/")
fun home(model: MutableMap<String, Any>, request: HttpServletRequest, response: HttpServletResponse): String {
model.put("time", Date())
model.put("message", this.message)
val authentication = SecurityContextHolder.getContext().authentication
val currentUser =if (authentication == null) null!! else authentication.principal as UserDetails
model.put("currentUser", currentUser)
// put currentUser into session
request.getSession().setAttribute("currentUser",currentUser)
return "jsp/home"
}
}
源代码工程: