Struts 2におけるrequest,response,session,applicationオブジェクトへのアクセス方法

964 ワード

1.クラス内の静的メソッドを使用して直接アクセス
//  request  .
	HttpServletRequest request = ServletActionContext.getRequest();
	//  session  .
	Map session = ActionContext.getContext().getSession();
	//  application  .
	ServletContext application = ServletActionContext.getServletContext();
この方法は直感的に簡単であるが、ユニットテストに不便である.
2.
ActionContext context=ActionContext.getContext(); 
HttpServletRequest request = (HttpServletRequest)context.get(ServletActionContext.HTTP_REQUEST); 

3..対応するインタフェースAwareを実装し、Struts 2のファクトリからオブジェクトを注入します.
public class HelloStruts extends ActionSupport implements ServletRequestAware {
	private HttpServletRequest request;
	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
}

Actionでは、複数のプロパティを1つのクラスにカプセル化し、クラスのインスタンス化オブジェクトを作成し、クラスのオブジェクトをsessionに保存し、ログインまたは結果ページをuserで表示できます.username,user.password表示、または#session.user.username.