• action解耦方式


    ServletAction方式,必须要有Servlet容器作支持

    package com.hanqi.action;

    import javax.servlet.ServletContext;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpSession;

    import org.apache.struts2.ServletActionContext;

    public class TestServletAction {

    public String testServletAction()
    {
    	//访问原生的web资源
    	
    	
    	//1得到servletContext,相当于application
    	ServletContext sc= ServletActionContext.getServletContext();
    	
    	System.out.println("app1="+sc.getAttribute("app1"));
    	
    	sc.setAttribute("app2", "原生的方式加入的application");
    	
    	//2访问Session
    	HttpServletRequest hsr=ServletActionContext.getRequest();
    	HttpSession hs=hsr.getSession();
    	System.out.println("ses1="+hs.getAttribute("ses1"));
    	hs.setAttribute("ses2", "原生方式放入的session");
    	
    	
    	//3访问request
    	System.out.println("req1="+hsr.getAttribute("req1"));
    	
    	hsr.setAttribute("req2", "原生方式放入的request");
    	
    	
    	//4 访问parameter
    	
    	System.out.println("user1="+hsr.getParameter("user"));
    	System.out.println("user2="+hsr.getParameter("user"));
    	return "success";
    }
    

    }

    实现接口方式

    package com.hanqi.action;

    import javax.servlet.ServletContext;
    import javax.servlet.ServletRequest;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpSession;

    import org.apache.struts2.interceptor.ServletRequestAware;
    import org.apache.struts2.util.ServletContextAware;

    public class TestServletActionAware
    implements ServletRequestAware, ServletContextAware {

    private ServletContext sc;
    private HttpServletRequest hsr;
    private HttpSession hs;
    @Override
    public void setServletContext(ServletContext arg0) {
    
    	sc=arg0;
    
    }
    
    @Override
    public void setServletRequest(HttpServletRequest arg0) {
    
    	hsr=arg0;
    	
    	hs=arg0.getSession();
    }
    
    public String testServletAware()
    {
    	System.out.println("app1="+sc.getAttribute("app1"));
    	
    	sc.setAttribute("app2", "新的application");
    	System.out.println("ses1="+hs.getAttribute("ses1"));
    	
    	hs.setAttribute("ses2","新的session");
    	System.out.println("user="+hsr.getParameter("user"));
    	
    	hsr.setAttribute("req2", "新的request");
    	return "success";
    }
    

    }

  • 相关阅读:
    VS自带的诊断工具
    Electron学习
    PC跨*台
    .NET调试学习
    Mac使用
    SSL/TLS
    UKey学习
    授权机制OAuth、JWT
    代理服务器
    .NET相关源码查找
  • 原文地址:https://www.cnblogs.com/nicebaby/p/6086555.html
Copyright © 2020-2023  润新知