ssh入门学习笔记之struts 内置对象

 struts2拿到session的三种方法。

其中ActionContext完全与web 容易不耦合。

 

1,通过ActionContext得到session,实现如下

 

ActionContext ac = ActionContext.getContext();

Map session = ac.getSession();

 

 

2,实现ServletRequestAware(只是只这一个就可以),和ServletResponseAware接口

 

package cn.edu.cqupt.action;

import java.util.Map;

import javax.servlet.ServletRequest;
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 com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class Login2Action extends ActionSupport implements ServletRequestAware,ServletResponseAware{
	private String username;
	private String password;
	private HttpServletRequest request;
	private HttpServletResponse response;
	@Override
	public String execute() throws Exception {
		if(username.equals("kevin")&&password.equals("123456"))
		{
			HttpSession session = request.getSession();
			session.setAttribute("result", "success");
			return SUCCESS;
		}
		return INPUT;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public void setServletRequest(HttpServletRequest request) {
		this.request=request;
		
	}
	public void setServletResponse(HttpServletResponse response) {
		this.response=response;
	}
	
}

 

3、通过ServletActionContext 得到

HttpServletRequest request =ServletActionContext.getRequest();

HttpServletResponse response = ServletActionContext.getResponse();

你可能感兴趣的:(session,struts2)