struts2 如何获取request,session,response

import java.util.Map;

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

import org.apache.struts2.ServletActionContext;

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

public class NonIoCServlet extends ActionSupport {

	private static final long serialVersionUID = 1L;
	private String message;
    
    public String getMessage() {
        return message;        
    }
    
    @Override
    public String execute() {    
        ActionContext.getContext().getSession().put("msg", "Hello World from Session!");
        
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();        
        HttpSession session = request.getSession();
        
        HttpServletRequest request2 = (HttpServletRequest)ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST ); 
        Map session2 =(Map)ActionContext.getContext().get(ActionContext.SESSION);
        
        StringBuffer sb =new StringBuffer("Message from request: ");
        sb.append(request.getParameter("msg"));
        sb.append("<br>Response Buffer Size: ");
        sb.append(response.getBufferSize());
        sb.append("<br>Session ID: ");
        sb.append(session.getId());
        
        message = sb.toString();
        return SUCCESS;
    }
}

 

2.

package qy.test.action;

import java.util.Map;

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

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;

public class IoCServlet extends ActionSupport implements SessionAware,
		ServletRequestAware, ServletResponseAware {
	
	private static final long serialVersionUID = 1L;
	private String message;
	private Map session;
	private HttpServletRequest request;
	private HttpServletResponse response;

	public String getMessage() {
		return message;
	}

	public void setSession(Map session) {
		this.session = session;
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	@Override
	public String execute() {
		session.put("msg", "Hello World from Session!");
		
		HttpSession session = request.getSession();
		StringBuffer sb = new StringBuffer("Message from request: ");
		sb.append(request.getParameter("msg"));
		sb.append("<br>Response Buffer Size: ");
		sb.append(response.getBufferSize());
		sb.append("<br>Session ID: ");
		sb.append(session.getId());

		message = sb.toString();
		return SUCCESS;
	}
}
 

你可能感兴趣的:(apache,servlet)