您当前的位置: 首页 >  spring

程序员一灯

暂无认证

  • 2浏览

    0关注

    152博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

SpringBoot 内置对象

程序员一灯 发布时间:2021-11-05 10:40:11 ,浏览量:2

Web内置对象主要有

    request

    response

    session

    servletContext

   各个模板引擎自定义内置对象(工具类)

session、servletContext都可以通过request对象来进行获取

通过注入方法参数获取内置对象
@RestController
@RequestMapping("/innerObject")
public class InnerObjectAction {
    @RequestMapping("/get")
    public Map getObjects(HttpServletRequest request,
                                          HttpServletResponse response, HttpSession session) {
        Map map = new LinkedHashMap();
        map.put("【request】 contextPath", request.getContextPath());
        map.put("【response】 encoding", response.getCharacterEncoding());
        map.put("【session】 sessionId", session.getId());
        map.put("【servletContext】 servletName", request.getServletContext().getVirtualServerName());
        map.put("【servletContext】 initParam", request.getServletContext().getInitParameter("message"));
        return map;
    }
}
在application.properties文件中设置servlet初始化参数:
server.servlet.context-parameters.message= hello SpringBoot !!!

 启动项目,访问:http://localhost:8888/innerObject/get发现可以正常取得所有的内置对象:

通过ServletRequestAttributes取得 
    @RequestMapping("/getObjects")
    public Map getObjects() {
        // 取得属性信息
        ServletRequestAttributes attributes = 
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpServletResponse response = attributes.getResponse();

        Map map = new LinkedHashMap();
        map.put("【request】 contextPath", request.getContextPath());
        map.put("【response】 encoding", response.getCharacterEncoding());
        map.put("【session】 sessionId", request.getSession().getId());
        map.put("【servletContext】 servletName", request.getServletContext().getVirtualServerName());
        map.put("【servletContext】 initParam", request.getServletContext().getInitParameter("message"));
        return map;
    }

在每次请求时都会将请求的request对象封装为RequestAttributes保存在ThreadLocal中,而通过RequestContextHolder类可以取得RequestAttributes,而RequestAttributes是一个接口,要将其转换为ServletRequestAttributes才可以取出request对象。response对象同理。

关注
打赏
1645367472
查看更多评论
立即登录/注册

微信扫码登录

0.0405s