Action中直接访问Servlet API

利用前面一节的配置稍作修改即可运行

LoginAction.java

package org.sadhu.app.action;
import com.opensymphony.xwork2.Action;
import org.apache.struts2.interceptor.ServletResponseAware;
import javax.servlet.http.HttpServletResponse;
import com.opensymphony.xwork2.ActionContext;
import javax.servlet.http.Cookie;
/*
 * Action中直接访问Servlet API
 * 如果需要用Response对象,需要继承ServletResponseAwara
 * 如果需要访问ServletContext对象,那么需要继承ServletContextAwara
 * */
public class LoginAction implements Action,ServletResponseAware {
	private String username;
	private String password;
	//定义一个response对象,如果使用response对象直接生成响应代码是没有实际意义也是不可能的因为Action是业务控制器。
	//例如:response.getWriter().println("hello Wrold");
	private HttpServletResponse response;
	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;
	}
	//重写实现ServletResponseAwara接口必须实现的方法
	public void setServletResponse(HttpServletResponse response)
	{
		this.response = response;
	}
	public String execute() throws Exception
	{
		ActionContext ctx = ActionContext.getContext();
		Integer counter = (Integer)ctx.getApplication().get("counter");
		if(counter == null)
		{
			counter = 1;
		}
		else
		{
			counter++;
		}
		//通过ActionContext设置application范围的属性
		ctx.getApplication().put("counter", counter);
		//通过ActionContext设置session范围的属性
		ctx.getSession().put("user",getUsername());
		if(getUsername().equals("sadhu") && getPassword().equals("sadhu"))
		{
			//通过response对象把数据添加到Cookie里面去
			Cookie c = new Cookie("user",getUsername());
			c.setMaxAge(60*60);
			response.addCookie(c);
			//通过ActionContext设置request范围的属性
			ctx.put("tip","服务器提示,您已经成功的登陆");
			return SUCCESS;
		}
		else
		{
			ctx.put("tip", "服务器提示,登陆失败");
			return ERROR;
		}
	}
}

welcome.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>登陆成功</title>
</head>
<body>欢迎进入系统!
<br />本站访问次数为:${applicationScope.counter}<br/>
${sessionScope.user},您已经登陆!<br/>
${requestScope.tip}<br />
从系统读取Cookie值:${cookie.user.value}
</body>
</html>


你可能感兴趣的:(Action中直接访问Servlet API)