Struts2_访问Web元素

在Serlvet中,我们可以直接用到HttpServletRequest  HttpServletResponse  ServletContext,

在Struts2中,有三种获取Web元素

1. 依赖于容器,如下

package com.test;

import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class Login1Action extends ActionSupport{

 private Map request;
 private Map session;
 private Map application;
 
 public Login1Action(){
  request = (Map)ActionContext.getContext().get("request");
  session = ActionContext.getContext().getSession();
  application = ActionContext.getContext().getApplication();
 }
 
 public String execute(){
  request.put("r1","r11");
  session.put("s1","s11");
  application.put("a1","a11");
  return SUCCESS;
 }
}

2. Ioc (Inverse of Control)控制反转  依赖注入  。这种最为常用

package com.test;

 
import java.util.Map;

import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

//IoC(inverse of control)控制反转  DI(dependency injection)依赖注入   设计思想  
public class Login2Action extends ActionSupport implements RequestAware,SessionAware,ApplicationAware{


 
 private Map<String,Object> request;
 private Map<String,Object> session;
 private Map<String,Object> application;
 
 
 public String execute(){
  
  request.put("r1","r11");
  session.put("s1","s11");
  application.put("a1","a11");
  return SUCCESS;
 }

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

 public void setSession(Map<String, Object> arg0) {

  this.session = arg0;
  
 }

 public void setApplication(Map<String, Object> arg0) {

  this.application = arg0;
  
 }
}

UML顺序图如下,IoC用通俗的话解释本来是自己控制的,变成给容器控制。所以就是IoC了



3. 也是依赖于容器

package com.test;

 


import java.util.Map;

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

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

//IoC(inverse of control)控制反转  DI(dependency injection)依赖注入   设计思想 
public class Login3Action extends ActionSupport{


 
 private HttpServletRequest request;
 private HttpSession session;
 private ServletContext application;
 
 
 public String execute(){
  
  request.setAttribute("r1","r11");
  session.setAttribute("s1","s11");
  application.setAttribute("a1","a11");
  return SUCCESS;
 }

 public Login3Action(){
  request = ServletActionContext.getRequest();
  session = request.getSession();
  application = session.getServletContext();
 }
}

你可能感兴趣的:(Web,object,struts,IOC,action,login)