Struts2获得Servlet对象的几种方式

第一种:ActionContext(首选)
public String execute() {
		if ("ping".equals(username)) {
			/*
			 * ActionContext可以获得Servlet对象 但是无法获得response响应对象获得
			 * 获得的request、session、Application 都是Map类型
			 */

			ActionContext.getContext().put("用户名", username);
			ActionContext.getContext().getSession();
			ActionContext.getContext().getApplication();
			Map request=(Map)ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST);
		} else {
			ActionContext.getContext().put("info", "信息");
		}
		return SUCCESS;
	}
第二种: 实现ServletRequestAware,
ServletResponseAwareServletSessionAware接口(第三选择 不推荐)
public class LoginAction extends ActionSupport implements ServletRequestAware


private HttpServletRequest request;
//需实现方法 public void setServletRequest(HttpServletRequest request) { this.request=request; } //response示例
public String execute1() throws IOException {
		if ("ping".equals(username)) {
			response.setContentType("text/html;charset=utf-8");   
			PrintWriter out = response.getWriter();   
			out.print("<script type='text/javascript'>alert('验证码输入错误!')</script>");   
			out.print("<script type='text/javascript'>location.href='/index.jsp'</script>");   
			out.flush();   
			out.close();  
		} else {
			response.setContentType("text/html;charset=utf-8");   
			PrintWriter out = response.getWriter();   
			out.print("<script type='text/javascript'>alert('验证码输入错误!')</script>");   
			out.flush();   
			out.close();  
		}
		System.out.println(username);
		return SUCCESS;
	}
第三种:ServletActionContext(第二选择)
public String execute2() throws IOException {
		if ("ping".equals(username)) { 
			ServletActionContext.getResponse();
			ServletActionContext.getRequest();
			ServletActionContext.getRequest().getSession();
			ServletActionContext.getServletContext();
		} else {
			
		}
		System.out.println(username);
		return SUCCESS;
	}
第四种:XXXAware接口(类似于第一种)
public class LoginAction2 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;
	}
	
	
}

转载于:https://my.oschina.net/u/1246663/blog/175178

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值