• java中获取ServletContext常见方法


    转自:http://chen106106.iteye.com/blog/1318596

    1.在javax.servlet.Filter中直接获取

    ServletContext context = config.getServletContext(); 

    2.在HttpServlet中直接获取

    this.getServletContext() 

    3.在其他方法中,通过HttpRequest获得

    request.getSession().getServletContext(); 

    当然struts2中还有常见的两种方法获得:
      获取HttpServletRequest / HttpSession / ServletContext / HttpServletResponse对象

    方法一,通过ServletActionContext.类直接获取:

    public String rsa() throws Exception{
      HttpServletRequest request = ServletActionContext.getRequest();
      ServletContext servletContext = ServletActionContext.getServletContext();
      request.getSession()
      HttpServletResponse response = ServletActionContext.getResponse();
      return "scope";
    } 

    方法二,实现指定接口,由struts框架运行时注入:

    public class HelloWorldAction implements ServletRequestAware, ServletResponseAware, ServletContextAware{
      private HttpServletRequest request;
      private ServletContext servletContext;
      private HttpServletResponse response;
      public void setServletRequest(HttpServletRequest req) {
        this.request=req;
      }
      public void setServletResponse(HttpServletResponse res) {
        this.response=res;
      }
      public void setServletContext(ServletContext ser) {
        this.servletContext=ser;
      }
    }
  • 相关阅读:
    bat学习
    Eclipse调试方法及快捷键
    JDK中的设计模式
    开源-自由-乔布斯
    AOP
    编程语言
    [LeetCode] 160. Intersection of Two Linked Lists(两个单链表的交集)
    [LeetCode] 198. House Robber(小偷)
    [LeetCode] 155. Min Stack(最小栈)
    [LeetCode] 1. Two Sum(两数之和)
  • 原文地址:https://www.cnblogs.com/tv151579/p/3269273.html
Copyright © 2020-2023  润新知