zoukankan      html  css  js  c++  java
  • spring 普通类获取四大作用域request、applicationContext、session、page

    几乎所有web应用容器都提供了四种类似Map的结构:application session request page,Jsp或者Servlet通过向着这四个对象放入数据,从而实现Jsp和Servlet之间数据的共享。

    application:整个应用  对应servlet中ServletContext

    session:会话    对应servlet中HttpSession

    request:一次请求  对应servlet中的HttpServletRequest

    page:当前页面

    在使用spring时,经常需要在普通类中获取session,request等对像.
    比如一些AOP拦截器类,在有使用struts2时,因为struts2有一个接口使用org.apache.struts2.ServletActionContext即可很方便的取到session对像.
    用法:ServletActionContext.getRequest().getSession();
    但在单独使用spring时如何在普通类中获取session,reuqest呢?
    其实也是有办法的.

    在Java web 项目中
    首先要在web.xml增加如下代码:

     <listener>
            <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
     </listener>

    接着在普通bean类中:

    @Autowired  
    private HttpSession session;  
      
    @Autowired  
    private HttpServletRequest request;  



    即可,在类中使用session对像了,是不是很方便呢..
    之所以要写出来是因为目前网上关于这个的用法,都是用什么写个lister再把session保存起来,太麻烦了.
    spring这么强大的框架,当然他们早也想到了.所以才有了我们这么方便的使用方法.

    当前加了上面的listener后也可以使用代码的方式获取reuqest对像

    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

    或者在普通Java程序中 可实现HttpServlet 

    public class StartApplicationService  extends HttpServlet
    
    ServletContext application = getServletConfig().getServletContext();
  • 相关阅读:
    List of the best open source software applications
    Owin对Asp.net Web的扩展
    NSwag给api加上说明
    'workspace' in VS Code
    unable to find valid certification path to requested target
    JMeter的下载以及安装使用
    exception disappear when forgot to await an async method
    Filter execute order in asp.net web api
    记录web api的request以及response(即写log)
    asp.net web api的源码
  • 原文地址:https://www.cnblogs.com/chen-lhx/p/5609639.html
Copyright © 2011-2022 走看看