struts2访问WEB元素

直接贴代码,

第一种:

public class Test1 extends ActionSupport {
	
	private Map request;
	private Map session;
	private Map application;
	//虽然说上面定义的是map类型,但是struts在解析的时候可以把它们转换成HttpServletRequest、
	//HttpSession等,这样你在页面上就可以直接用了,而且可以拿出相应的值来,这些值是在Action里面
	//设置好的,如下面的execute方法里面设置的key和相应的value;
	public Test1() {
		request = (Map)ActionContext.getContext().get("request");
		session = ActionContext.getContext().getSession();
		application = ActionContext.getContext().getApplication();
	}
	
	public String execute() {
		request.put("r1", "r1");
		session.put("s1", "s1");
		application.put("a1", "a1");
		return SUCCESS; 
	}
	
	
}

 

 

第二种:

public class Test2 extends ActionSupport implements RequestAware,SessionAware, ApplicationAware {
	
	private Map<String, Object> request;
	private Map<String, Object> session;
	private Map<String, Object> application;
	
	//DI dependency injection
	//IoC inverse of control
	public String execute() {
		request.put("r1", "r1");
		session.put("s1", "s1");
		application.put("a1", "a1");
		return SUCCESS; 
	}

	@Override
	public void setRequest(Map<String, Object> request) {
		this.request = request;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	@Override
	public void setApplication(Map<String, Object> application) {
		this.application = application;
	}
	
	
}

 

 

第三种:

//这种方式也挺好用的,个人也经常使用这种方式
public class Test3 extends ActionSupport {
	
	private HttpServletRequest request;
	private HttpSession session;
	private ServletContext application;
	
	public Test3() {
		request = ServletActionContext.getRequest();
		session = request.getSession();
		application = session.getServletContext();
	}
	
	public String execute() {
		request.setAttribute("r1", "r1");
		session.setAttribute("s1", "s1");
		application.setAttribute("a1", "a1");
		return SUCCESS; 
	}
	
}

 

上一篇:redis连接过多的一个解决方法


下一篇:C语言中宏与内联函数解析